asx3m

asx3m is a library that enables serialization of objects to XML and back again. The de/serializer is designed to be compatible with Java XStream library, but it’s not related to XStream project in any other way.

The class has dependencies with Maashaack library.

Sample

package hr.binaria.dto 
{
        public class Client
        {
                private var _age:int;

                public var id:Number;
                public var name:String;
                public var contacted:Boolean;
                public var mainProduct:Product;
                public var products:Array;

                public function get age():int{
                        return _age;
                }
                public function set age(value:int):void {
                        return _age;
                }
        }
}

package hr.binaria.dto
{
        public class Product
        {
                public var id:Number;
                public var name:String;
        }
}

package {
       import flash.display.Sprite;

       import hr.binaria.dto.Product;
       import hr.binaria.dto.Client;
       import hr.binaria.asx3m.Asx3mer;

        public class Asx3mTest extends Sprite
        {

                public function Asx3mTest()
                {       

                        var client:Client=new Client();                         
                        client.contacted=false;
                        client.name="John";

                        client.mainProduct=new Product();
                        client.mainProduct.id=0;
                        client.mainProduct.name="Main product";

                        var prod1:Product=new Product();
                        prod1.id=1;
                        prod1.name="Product 1";
                        var prod2:Product=new Product();
                        prod2.id=2;
                        prod2.name="Product 2";

                        client.products=new Array;
                        client.products.push(prod1);
                        client.products.push(prod2);

                        //convert object to XML
                        var xmlObj:XML=Asx3mer.instance.toXML(client);
                        trace(xmlObj);  

                        //decode object from XML                                
                        var clientDecoded:Client=Asx3mer.instance.fromXML(xmlObj) as Client;                            

                        //convert object to xml forcing type    
                        var xmlObjForced:XML=Asx3mer.instance.toXML(client,"SomeOtherType");
                        trace(xmlObjForced);    
                }               
        }
}

// Output
<hr.binaria.dto.Client>
  <name>John</name>
  <mainProduct>
    <name>Main product</name>
    <id>0</id>
  </mainProduct>
  <products>
    <hr.binaria.dto.Product>
      <name>Product 1</name>
      <id>1</id>
    </hr.binaria.dto.Product>
    <hr.binaria.dto.Product>
      <name>Product 2</name>
      <id>2</id>
    </hr.binaria.dto.Product>
  </products>
  <contacted>false</contacted>
</hr.binaria.dto.Client>

<SomeOtherType>
  <name>John</name>
  <mainProduct>
    <name>Main product</name>
    <id>0</id>
  </mainProduct>
  <products>
    <hr.binaria.dto.Product>
      <name>Product 1</name>
      <id>1</id>
    </hr.binaria.dto.Product>
    <hr.binaria.dto.Product>
      <name>Product 2</name>
      <id>2</id>
    </hr.binaria.dto.Product>
  </products>
  <contacted>false</contacted>
</SomeOtherType>
Serialization
Leave a comment

FlexXB

FlexXB is a serializer for Flex and Air applications, using annotations in order to automate the (de)serialization process. It has built-in support for (de)serializing xml. In order for FlexXB to be able to automate the (de)serialization process, the model objects involved must be “decorated” with AS3 metadata tags that will instruct it on how they should be processed.

The tool is serialization format agnostic and allows users to extend the engine and add support for different serialization formats (JSON, etc) while still sharing the base features such as object caching, circular reference handling, constructor annotations, id fields, version extraction.

Sample

// Class
[XmlClass(alias="MOck2Replacement", idField="id")]
public class Mock3
{
  [XmlAttribute]
  public var id : Number = 3;
  [XmlAttribute]
  public var attribute : Boolean;
  [XmlElement(alias="objectVersion")]
  public var version : Number;

  public function Mock3()
  {
    super();
  }
}

// The object has been built as:
var target : Mock3 = new Mock3();
target.attribute = true;
target.id = 5;
target.version = 33;

// The resulting XML is:

    33
Serialization
Leave a comment

DragonBones

DragonBones is a 2D skeleton animation framework based on assets parsing. It contains a design panel (Flash Pro extension) and a Starling based library that allows you to design skeleton animation in Flash Pro, then export it to texture atlas and render on top of Starling.

Instead of having giant “sprite sheets” for sequence frame based animation, the skeleton animation powered by Dragonbones can help you save resources and memory consumption.

Sample

package
{
	import dragonBones.Armature;
	import dragonBones.Bone;
	import dragonBones.factorys.StarlingFactory;

	import flash.geom.Point;
	import flash.ui.Mouse;

	import starling.display.Image;
	import starling.display.Sprite;
	import starling.events.EnterFrameEvent;
	import starling.events.TouchEvent;
	import starling.textures.Texture;
	import flash.events.Event;

	public class Dragon_ChaseStarling extends Sprite
	{
		[Embed(source = "../assets/DragonWithClothes.png", mimeType = "application/octet-stream")]
		public static const ResourcesData:Class;

		[Embed(source = "../assets/starling.png")]
		private static const starlingImg:Class;

		private var factory:StarlingFactory;
		private var armature:Armature;
		private var armatureClip:Sprite;

		private var mouseX:Number = 0;
		private var mouseY:Number = 0;
		private var moveDir:int=0;
		private var dist:Number;
		private var speedX:Number = 0;
		private var starlingBird:Image;
		private var _r:Number;

		private var _head:Bone;
		private var _armR:Bone;
		private var _armL:Bone;

		public function Dragon_ChaseStarling()
		{
			factory = new StarlingFactory();
			factory.addEventListener(Event.COMPLETE, textureCompleteHandler);
			factory.parseData(new ResourcesData());
		}
		private function textureCompleteHandler(e:Event):void
		{
			armature = factory.buildArmature("Dragon");
			armatureClip = armature.display as Sprite;

			armatureClip.x = 400;
			armatureClip.y = 550;
			addChild(armatureClip);
			updateBehavior(0)
			addEventListener(EnterFrameEvent.ENTER_FRAME, onEnterFrameHandler);
			stage.addEventListener(TouchEvent.TOUCH, onMouseMoveHandler);

			starlingBird=new Image(Texture.fromBitmap(new starlingImg()))
			addChild(starlingBird);
			Mouse.hide();
			//get the bones which you want to control
			_head = armature.getBone("head");
			_armR = armature.getBone("armUpperR");
			_armL = armature.getBone("armUpperL");

		}

		private function onEnterFrameHandler(_e:EnterFrameEvent):void
		{
			checkDist();
			updateMove();
			updateBones();
			armature.update();		
		}

		private function checkDist():void
		{
			dist = armatureClip.x-mouseX;
			if(dist190)
			{
				updateBehavior(-1)
			}
			else
			{
				updateBehavior(0)
			}

		}

		private function onMouseMoveHandler(_e:TouchEvent):void
		{
			var _p:Point = _e.getTouch(stage).getLocation(stage);
			mouseX = _p.x;
			mouseY = _p.y;
			starlingBird.x=mouseX-73;
			starlingBird.y=mouseY-73;
		}
		private function updateBehavior(dir:int):void 
		{
			if(moveDir==dir)return;
			moveDir=dir;
			if (moveDir == 0)
			{
				speedX = 0;
				armature.animation.gotoAndPlay("stand");
			}
			else
			{
				speedX=6*moveDir;
				armature.animation.gotoAndPlay("walk");
			}
		}
		private function updateMove():void
		{
			if (speedX != 0) 
			{
				armatureClip.x += speedX;
				if (armatureClip.x < 0)  				{ 					armatureClip.x = 0; 				} 				else if (armatureClip.x > 800) 
				{
					armatureClip.x = 800;
				}
			}
		}
		private function updateBones():void
		{
			//update the bones' pos or rotation
			_r = Math.PI + Math.atan2(mouseY - armatureClip.y+armatureClip.height/2, mouseX - armatureClip.x);
			if (_r > Math.PI)
			{
				_r -= Math.PI * 2;
			}
			_head.node.rotation = _r*0.3		
			_armR.node.rotation = _r *0.8;
			_armL.node.rotation = _r * 1.5;

			starlingBird.rotation=_r*0.2;
		}
	}
}
Animation
Leave a comment

Pomelo

Pomelo is a fast, scalable game server framework for node.js. It provides the basic development framework and a lot of related components, including libraries and tools. It is also suitable for realtime web application, its distributed architecture makes it scales better than other realtime web framework.

Some features:

  • High scalable multi-process architecture, supporting MMO based area partition and other partition strategies
  • Easy extention mechnisam, you can scale up your server types and server instances conveniently.
  • Easy request, response, broadcast and rpc mechnisam, almost zero configuration.
  • Focus on performance, a lot of stress testing and tune in performance and scalability
  • Providing a lot tools and libraries, which are quite useful for game development.
  • Providing full MMO demo code(html5 client), for good development reference.
  • Based on socket.io, which means it can support all the clients that compatible with socket.io.
Multiplayer
Leave a comment

Anthill

Anthill is a tiny framework focused on game development. It has a small set of classes so it’s not a complete tool for creating games, it’s more an add-on to complement Flash working flow.

The framework was inspired by Flixel game engine, but with significant differences in terms of graphics. A key difference (and feature) is the rasterization of vector graphics (*.FLA or *. SWC) on the fly and the possibility to work with raster images and animations instead of normal MovieClips.

Sample

package ru.antkarlov.anthill
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.StageScaleMode;
	import flash.display.StageAlign;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.MouseEvent;
	import flash.events.KeyboardEvent;
	import flash.utils.getTimer;

	/**
	 * Ядро игрового движка.
	 * 
	 * @langversion ActionScript 3
	 * @playerversion Flash 9.0.0
	 * 
	 * @author Anton Karlov
	 * @since  29.08.2012
	 */
	public class Anthill extends Sprite
	{
		[Embed(source= "resources/iFlash706.ttf",fontFamily="system",mimeType="application/x-font",
			unicodeRange="U+0020-U+002F,U+0030-U+0039,U+003A-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E,U+0400-U+04CE,U+2000-U+206F,U+20A0-U+20CF,U+2100-U+2183")] protected var junk:String;

		public var state:AntState;
		protected var _initialState:Class;
		protected var _framerate:uint;
		protected var _isCreated:Boolean;
		protected var _isStarted:Boolean;
		internal var _elapsed:Number;
		internal var _total:uint;

		public function Anthill(aInitialState:Class = null)
		{
			super();

			_initialState = aInitialState;
			_framerate = 35;
			_isCreated = false;
			_isStarted = false;

			(stage == null) ? addEventListener(Event.ADDED_TO_STAGE, create) : create();
		}

		public function create(event:Event = null):void
		{
			if (event != null)
			{
				removeEventListener(Event.ADDED_TO_STAGE, create);
			}

			AntG.init(this);

			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			stage.frameRate = _framerate;

			stage.addEventListener(KeyboardEvent.KEY_DOWN, AntG.debugger.console.keyDownHandler);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, AntG.keys.keyDownHandler);
			stage.addEventListener(KeyboardEvent.KEY_UP, AntG.keys.keyUpHandler);
			stage.addEventListener(MouseEvent.MOUSE_DOWN, AntG.mouse.mouseDownHandler);
			stage.addEventListener(MouseEvent.MOUSE_UP, AntG.mouse.mouseUpHandler);
			stage.addEventListener(MouseEvent.MOUSE_OUT, AntG.mouse.mouseOutHandler);
			stage.addEventListener(MouseEvent.MOUSE_OVER, AntG.mouse.mouseOverHandler);
			stage.addEventListener(MouseEvent.MOUSE_WHEEL, AntG.mouse.mouseWheelHandler);

			AntG.debugger.perfomance.start();

			_isCreated = true;
			switchState(new _initialState());
			start();
		}

		public function start():void
		{
			if (!_isStarted && _isCreated)
			{
				addEventListener(Event.ENTER_FRAME, enterFrameHandler);
				_isStarted = true;
			}
		}

		public function stop():void
		{
			if (_isStarted && _isCreated)
			{
				removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
				_isStarted = false;
			}
		}

		public function switchState(aState:AntState):void
		{
			addChild(aState);
			if (state != null)
			{
				state.dispose();
				swapChildren(state, aState);
				removeChild(state);
			}

			state = aState;
			state.create();
		}

		protected function enterFrameHandler(event:Event):void
		{
			// Рассчет времени между кадрами.
			var ct:uint = getTimer();
			var ems:uint = ct - _total;
			AntG.debugger.perfomance.ratingTotal.add(ems);
			_elapsed = ems / 1000;
			_total = ct;
			AntG.elapsed = (_elapsed > AntG.maxElapsed) ? AntG.maxElapsed : _elapsed;
			AntG.elapsed *= AntG.timeScale;

			// Процессинг содержимого игры.
			AntG.updateInput();
			AntG.updateSounds();

			AntBasic._numOfActive = 0;

			state.preUpdate();
			state.update();
			state.postUpdate();

			// Расчет времени ушедшего на процессинг.
			var updCt:uint = getTimer();
			AntG.debugger.perfomance.ratingUpdate.add(updCt - ct);

			// Рендер графического контента.
			AntBasic._numOfVisible = 0;
			AntBasic._numOnScreen = 0;

			// Подготовка камер к рендеру.
			var cam:AntCamera;
			var n:int = AntG.cameras.length;
			for (var i:int = 0; i < n; i++)
			{
				cam = AntG.cameras[i] as AntCamera;
				if (cam != null)
				{
					cam.draw();
				}
			}

			// Рендер состояния.
			state.draw();

			// Рассчет времени ушедшего на рендер.
			var rndCt:uint = getTimer();
			AntG.debugger.perfomance.ratingRender.add(rndCt - updCt);

			// Рассчет времени ушедшего на физику.
			AntG.debugger.perfomance.ratingPhysics.add(getTimer() - rndCt);
			AntG.debugger.update();
		}

		public function set framerate(value:uint):void
		{
			_framerate = value;
			if (stage != null)
			{
				stage.frameRate = _framerate;
			}
		}

		public function get framerate():uint
		{
			return _framerate;
		}

	}

}
2D
2 Comments

Device Identification

Device Identification is a Native Extension  that provides access to device identification data. It is possible to read the IMEI code, IMEI SV code, Device Serial Number, MODEL and IMSI code.

Sample

import com.flashvisions.mobile.android.extensions.system.data.DeviceIdentity;
import com.flashvisions.mobile.android.extensions.system.SystemNFO;

var systemInfo:SystemNFO = new SystemNFO();
var result:DeviceIdentity = systemInfo.getDeviceIdentity();

trace(result.IMEI);
trace(result.IMEISV);
trace(result.IMSI);
trace(result.MODEL);
trace(result.SERIAL);
trace(result.PHONENUMBER);
Air Native Extension, Android ,
16 Comments

ANE StoreKit

ANE StoreKit is a native extension that allows the use of in-app purchase capabilities. Even though StoreKit is a framework originally developed for iOS, the extension allows the use of its features on Android as well.

The API provides methods to register products and to make transactions (payment). There are several events that can be listened to monitor what is happening during the process.

Sample

import com.jesusla.storekit.*;

// StoreKit listeners should be setup as soon as app starts
StoreKit.addEventListener(TransactionEvent.TRANSACTION_PURCHASED, storeKit_purchaseHandler);
StoreKit.addEventListener(TransactionEvent.TRANSACTION_FAILED, storeKit_failureHandler);
StoreKit.addEventListener(TransactionEvent.TRANSACTION_REVOKED, storeKit_revokeHandler);
StoreKit.addEventListener(TransactionEvent.TRANSACTION_VERIFY, storeKit_verifyHandler);

// Once listeners are setup, StoreKit should be initialized
// PRODUCTS should be an array of Product IDs, which need to be previously configured in
// iTunesConnect / GooglePlay / Amazon Market.
const PRODUCTS:Array = [
  'sku1', 'sku2', 'sku3', 'sku4', 'sku5', 'sku6'
];
StoreKit.init(PRODUCTS, initCallback);

function initCallback(success:Boolean):void

// initCallback is called with a flag indicating the initialization status
// If true, the system is ready to process orders. This flag can be
// obtained at any time with the canMakePayments property. The caller
// should adjust the UI appropriately in those cases when this flag is false.
StoreKit.canMakePayments;

// To request a purchase:
StoreKit.requestPayment('sku1', requestCallback);

// The success/failure of the purchase is reported in the optional
// request callback. A true value does not mean that the purchase
// went through. It simply means that the request was successful.
function requestCallback(success:Boolean):void

// As the transaction is processed, several events are fired.
// If there's a problem with the transaction (e.g. user cancels
// the transaction, the payment was declined, etc.) the event
// TRANSACTION_FAILED is fired. The failure must be acknowledged
// by finishing the transaction with acknowledgeTransaction()
function storeKit_failureHandler(event:TransactionEvent):void {
  // Acknowledge the failure. Omitting this step will
  // cause the event to be constantly fired for this
  // transaction until acknowledged.
  StoreKit.acknowledgeTransaction(event.transaction);
}

// If the transaction succeeds, the TRANSACTION_VERIFY event
// is fired. The client must now verify the transaction in an
// implementation-specific manner (e.g. verifying its cryptographic
// signature via a server-side request, etc.). The transaction
// should be acknowledged if verification passes. Otherwise,
// the transaction should be rejected.
function storeKit_verifyHandler(event:TransactionEvent):void {
  if (serverSideVerification(event.transaction))
    StoreKit.acknowledgeTransaction(event.transaction);
  else
    StoreKit.rejectTransaction(event.transaction);
}

// After being successfully verified, the TRANSACTION_PURCHASED
// event is fired. The transaction is now complete and should
// be fulfilled. It is important not to acknowledge the transaction
// before it is fulfilled.
function storeKit_purchaseHandler(event:TransactionEvent):void {
  if (fulfillTransaction(event.transaction))
    StoreKit.acknowledgeTransaction(event.transaction);
}

// Finally, the TRANSACTION_REVOKED event may be fired for
// transactions that are revoked/refunded server-side. The client must
// revoke the goods (e.g. deduct coins, etc) and acknowledge the
// transaction.
function storeKit_revokeHandler(event:TransactionEvent):void {
  if (revokeTransaction(event.transaction))
    StoreKit.acknowledgeTransaction(event.transaction);
}

// Transactions are plain objects with the following properties:
var transaction:Object = event.transaction;
transaction.vendor; // One of VENDOR_APPLE, VENDOR_GOOGLE, VENDOR_AMAZON
transaction.transactionState; // One of STATE_FAILED, STATE_VERIFY,
                              // STATE_PURCHASED, STATE_REVOKED
transaction.productIdentifier; // e.g. 'sku1' (String)

// Note that during a VERIFY, only the first two fields are guaranteed
// to be present. The rest of the fields will be vendor-specific.

// Finally, the app may request restoring completed transactions.
// This will cause all non-consumable historic transactions to be
// resent to the client with a STATE_PURCHASED state. The optional callback
// is notified with a flag indicating success/failure
StoreKit.restoreCompletedTransactions(restoreCallback);

function restoreCallback(success:Boolean):void
Air Native Extension, Android, iOS
2 Comments

OimoPhysics

OimoPhysics is a 3D physics engine. It supports rigid bodies and has some out of the box collision detectors such as sphere/box and box/shape. There are two built-in shapes ready to be used: box and sphere.

Sample

/* Copyright (c) 2012 EL-EMENT saharan
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this
 * software and associated documentation  * files (the "Software"), to deal in the Software
 * without restriction, including without limitation the rights to use, copy,  * modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to
 * whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.element.oimo.physics.test {
	import com.element.oimo.physics.collision.shape.BoxShape;
	import com.element.oimo.physics.collision.shape.Shape;
	import com.element.oimo.physics.collision.shape.ShapeConfig;
	import com.element.oimo.physics.collision.shape.SphereShape;
	import com.element.oimo.physics.dynamics.RigidBody;
	import com.element.oimo.physics.dynamics.World;
	import com.element.oimo.math.Mat33;
	import com.element.oimo.math.Quat;
	import com.element.oimo.math.Vec3;
	import com.element.oimo.physics.OimoPhysics;
	import com.element.oimo.physics.util.DebugDraw;
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.ui.Keyboard;
	import net.hires.debug.Stats;
	/**
	 * 動作テスト
	 * @author saharan
	 */
	[SWF(width = "640", height = "480", frameRate = "60")]
	public class BoxTest extends Sprite {
		private var s3d:Stage3D;
		private var world:World;
		private var renderer:DebugDraw;
		private var rigid:RigidBody;
		private var count:uint;
		private var tf:TextField;
		private var fps:Number;
		private var l:Boolean;
		private var r:Boolean;
		private var u:Boolean;
		private var d:Boolean;
		private var ctr:RigidBody;

		public function BoxTest() {
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}

		private function init(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);

			var debug:Stats = new Stats();
			debug.x = 570;
			addChild(debug);
			tf = new TextField();
			tf.selectable = false;
			tf.defaultTextFormat = new TextFormat("_monospace", 12, 0xffffff);
			tf.x = 0;
			tf.y = 0;
			tf.width = 400;
			tf.height = 400;
			addChild(tf);
			trace(OimoPhysics.DESCRIPTION);
			initWorld();
			fps = 0;

			s3d = stage.stage3Ds[0];
			s3d.addEventListener(Event.CONTEXT3D_CREATE, onContext3DCreated);
			s3d.requestContext3D();
			stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void {
				var code:uint = e.keyCode;
				if (code == Keyboard.W) {
					u = true;
				}
				if (code == Keyboard.S) {
					d = true;
				}
				if (code == Keyboard.A) {
					l = true;
				}
				if (code == Keyboard.D) {
					r = true;
				}
				if (code == Keyboard.SPACE) {
					initWorld();
				}
			});
			stage.addEventListener(KeyboardEvent.KEY_UP, function(e:KeyboardEvent):void {
				var code:uint = e.keyCode;
				if (code == Keyboard.W) {
					u = false;
				}
				if (code == Keyboard.S) {
					d = false;
				}
				if (code == Keyboard.A) {
					l = false;
				}
				if (code == Keyboard.D) {
					r = false;
				}
			});
			addEventListener(Event.ENTER_FRAME, frame);
		}

		private function initWorld():void {
			world = new World();
			if (!renderer) renderer = new DebugDraw(640, 480);
			renderer.setWorld(world);
			var rb:RigidBody;
			var s:Shape;
			var c:ShapeConfig = new ShapeConfig();
			c.restitution = 0;
			rb = new RigidBody();
			c.position.init(0, -0.5, 0);
			c.rotation.init();
			s = new BoxShape(32, 1, 32, c);
			rb.addShape(s);
			rb.setupMass(RigidBody.BODY_STATIC);
			world.addRigidBody(rb);

			c.rotation.init();
			var width:uint = 6;
			var height:uint = 6;
			var depth:uint = 6;
			var bw:Number = 0.7;
			var bh:Number = 0.7;
			var bd:Number = 0.7;
			for (var i:int = 0; i < width; i++) {
				for (var j:int = 0; j < height; j++) {
					for (var k:int = 0; k < depth; k++) { 						rb = new RigidBody(); 						c.position.init( 							(i - (width - 1) * 0.5) * bw, 							j * (bh * 1.1) + bh * 0.5 + 0.05, 							(k - (depth - 1) * 0.5) * bd 						); 						s = new BoxShape(bw, bh, bd, c); 						rb.addShape(s); 						rb.setupMass(RigidBody.BODY_DYNAMIC); 						world.addRigidBody(rb); 					} 				} 			} 			 			c.friction = 2; 			c.position.init(0, 1, 8); 			c.density = 10; 			c.rotation.init(); 			s = new SphereShape(1, c); 			ctr = new RigidBody(); 			ctr.addShape(s); 			ctr.setupMass(RigidBody.BODY_DYNAMIC); 			world.addRigidBody(ctr); 		} 		 		private function onContext3DCreated(e:Event = null):void { 			renderer.setContext3D(s3d.context3D); 			renderer.camera(0, 2, 4); 		} 		 		private function frame(e:Event = null):void { 			count++; 			var ang:Number = (320 - mouseX) * 0.01 + Math.PI * 0.5; 			renderer.camera( 				ctr.position.x + Math.cos(ang) * 8, 				ctr.position.y + (240 - mouseY) * 0.1, 				ctr.position.z + Math.sin(ang) * 8, 				ctr.position.x, ctr.position.y, ctr.position.z 			); 			if (l) { 				ctr.linearVelocity.x -= Math.cos(ang - Math.PI * 0.5) * 0.8; 				ctr.linearVelocity.z -= Math.sin(ang - Math.PI * 0.5) * 0.8; 			} 			if (r) { 				ctr.linearVelocity.x -= Math.cos(ang + Math.PI * 0.5) * 0.8; 				ctr.linearVelocity.z -= Math.sin(ang + Math.PI * 0.5) * 0.8; 			} 			if (u) { 				ctr.linearVelocity.x -= Math.cos(ang) * 0.8; 				ctr.linearVelocity.z -= Math.sin(ang) * 0.8; 			} 			if (d) { 				ctr.linearVelocity.x += Math.cos(ang) * 0.8; 				ctr.linearVelocity.z += Math.sin(ang) * 0.8; 			} 			world.step(); 			fps += (1000 / world.performance.totalTime - fps) * 0.5; 			if (fps > 1000 || fps != fps) {
				fps = 1000;
			}
			tf.text =
				"Rigid Body Count: " + world.numRigidBodies + "\n" +
				"Shape Count: " + world.numShapes + "\n" +
				"Contacts Count: " + world.numContacts + "\n\n" +
				"Broad Phase Time: " + world.performance.broadPhaseTime + "ms\n" +
				"Narrow Phase Time: " + world.performance.narrowPhaseTime + "ms\n" +
				"Constraints Time: " + world.performance.constraintsTime + "ms\n" +
				"Update Time: " + world.performance.updateTime + "ms\n" +
				"Total Time: " + world.performance.totalTime + "ms\n" +
				"Physics FPS: " + fps.toFixed(2) + "\n"
			;
			renderer.render();
			var len:uint = world.numRigidBodies;
			var rbs:Vector. = world.rigidBodies;
			for (var i:int = 0; i < len; i++) {
				var r:RigidBody = rbs[i];
				if (r.position.y < -12) {
					r.position.init(Math.random() * 8 - 4, Math.random() * 4 + 8, Math.random() * 8 - 4);
					r.linearVelocity.x *= 0.8;
					r.linearVelocity.z *= 0.8;
				}
			}
		}

	}

}
3D
Leave a comment

ANE TestFlight

ANE TestFlight is an Adobe Native Extension that allows the use of TestFlight SDK. TestFlight is a service that makes the testing process of an application a much easier task.

Sample

public static function init():void
public static function crash(message:String):void 
public function getQualifiedClassName(obj:Object):String
public function enumerateObjectProperties(obj:Object):Array
public function __retainObject(obj:Object):int
public function __getObject(id:int):Object
Air Native Extension, Android, iOS
3 Comments

WorkerCompat

WorkerCompat is a Worker wrapper for compatibility with all AS3 versions of the Flash Player (9 and later). It simply uses dynamic-lookup to determine if the Worker API is available and supported. This allows SWFs compiled with this code to be playable on all version of the Flash Player, not just those with Worker support (11.4 and later).

The wrapper is an alternative to using static imports, which would cause runtime-error in Flash Player earlier than 11.4 when using the Workers API.

Sample

package com.lilcodemonkey.workers
{

  import flash.display.Bitmap;
  import flash.display.BitmapData;
  import flash.display.Shape;
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.external.ExternalInterface;
  import flash.system.Capabilities;
  import flash.text.TextField;
  import flash.utils.getTimer;
  import flash.utils.setInterval;

  /**
   * This test showcases the backward-compatible use of AS3 Workers.  It runs
   * in all versions of the Flash Player, and takes advantage of AS3 workers
   * whenever possible (Flash Player >= 11.4 && Worker.isSupported)
   *
   * A notable exception is Google Chrome under Windows (PPAPI)... for some
   * reason Google has disabled workers in their bundled version of Flash 11.4
   *
   * This simple demo does not demonstrate intra-thread communication.
   */
  public class WorkerCompatTest extends Sprite
  {
    private var shape:Shape;
    private var bitmap:Bitmap;

    // Constructor
    public function WorkerCompatTest():void
    {
      stage.align = 'topLeft';
      stage.scaleMode ='noScale';
      stage.frameRate = 60;

      showInfo();

      if (WorkerCompat.workersSupported) {
        // Setup threading
        setupThreads();
      } else {
        // Fallback: Do all the work in this thread
        doGuiWork();
        doBackgroundWork();
      }
    }

    private function showInfo():void
    {
      var userAgent:String;
      try {
        userAgent = ExternalInterface.call("(function() { return window.navigator.userAgent })");
      } catch (e:Error) {
        userAgent = "unknown";
      }

      var text:TextField = new TextField();
      text.width = text.height = 500;
      text.x = 105;
      text.text = "Flash Player version: " + Capabilities.version+"\n"+
                  "userAgent: "+userAgent+"\n"+
                  "WorkerClass: "+WorkerCompat.Worker+"\n"+
                  "workersSupported: " + WorkerCompat.workersSupported;
      addChild(text);
    }

    private function setupThreads():void
    {
      if (WorkerCompat.Worker.current.isPrimordial) {
        // Main thread runs this
        doGuiWork();

        // And creates a duplicate of itself to run as the background worker
        var bgWorker:* = WorkerCompat.WorkerDomain.current.createWorker(this.loaderInfo.bytes);
        bgWorker.start();
      } else {
        // Background thread runs this
        doBackgroundWork();
      }
    }

    private function doGuiWork():void
    {
      shape = new Shape();
      bitmap = new Bitmap(new BitmapData(100, 100, false, 0x0));
      addChild(bitmap);
      this.addEventListener(Event.ENTER_FRAME, onFrame);
    }

    private function doBackgroundWork():void
    {
      // Every 200 ms, burn the CPU for 170 ms
      setInterval(function():void {
        var t:Number = getTimer();
        while (getTimer()-t < 170) { }
      }, 200);
    }

    private function onFrame(e:Event):void
    {
      var t:Number = getTimer();

      // Fade to black
      shape.graphics.clear();
      shape.graphics.beginFill(0x0, 0.05);
      shape.graphics.drawRect(0,0,100,100);
      bitmap.bitmapData.draw(shape);

      // Draw red circle/line
      shape.graphics.clear();
      shape.graphics.lineStyle(3, 0xff0000, 1, true);
      shape.graphics.drawCircle(50, 50, 46);
      shape.graphics.moveTo(50, 50);
      shape.graphics.lineTo(50+45*Math.cos(t/300), 50+45*Math.sin(t/300));
      bitmap.bitmapData.draw(shape);
    }

  }

}
Misc
2 Comments

Red2D

Red2D is a GPU accelerated 2D framework.  It was designed to make it easy to use Stage3D capabilities.  The framework has a complete set of features supporting cameras, filters, particles, texts and materials.

Sample

package basicAPIEx
{
    import red2D.Red_Scene;
    import red2D.display.Red_Sprite;
    import red2D.material.ColorMaterial;
    import red2D.text.Red_TextField;

    public class Test01_helloRed2D extends Red_Scene
    {

        private var _testRedSprite:Red_Sprite;
        private var _testText:Red_TextField;

        public function Test01_helloRed2D($bgColor:int=0)
        {
            super($bgColor);
        }

        public override function setDesign():void{

            _testRedSprite = new Red_Sprite(
                new ColorMaterial,
                {
                    x:0.5*stage.stageWidth,
                    y:0.5*stage.stageHeight
                }
            )

            addChild(_testRedSprite)

            _testText = new Red_TextField("Hello Red2DPlus",{size:30})
            _testText.textColor=0xffffff
            _testText.x = stage.stageWidth/2
            _testText.y = _testRedSprite.y+100
            addChild(_testText)
        }

        public override function update():void{
            _testRedSprite.rotation++
        }
    }
}
2D
2 Comments

Gleed2D

Gleed2D (Generic LEvel EDitor 2D) is a general purpose, non tile-based Level Editor for 2D games. It allows arbitrary placement of textures and other items in 2D space. Levels are saved in XML format. Custom Properties can be added to the items in order to represent game-specific data/events/associations between items etc.

Some features:

  • placing & editing textures (move, rotate, scale, flip, tint)
  • multiple layers
  • several tools (align horizontally, etc.)
  • primitive items (rectangle, circle, path)
  • Custom Properties per item/layer/level
  • undo/redo
  • save to XML
  • editing multiple items at once
  • toggle visibility per item/layer/level
  • preview in your application
  • parallax scrolling
GLEED2D

 

Editors
Leave a comment

ServerSocketANE

ServerSocketANE is an Air Native Extension (ANE) for ServerSocket on mobile platforms. The ServerSocket class is not available on mobile platforms directly from Adobe in the Air SDK. This extension implements the API on the iOS platform.

The package path com.thejustinwalsh.net is a direct analog to flash.net and the extension implements a working default package as well. So everywhere you would use flash.net.ServerSocket use com.thejustinwalsh.net.ServerSocket instead.

Sample

public function close():void
public function bind(localPort:int = 0, localAddress:String = "0.0.0.0"):void
public function listen(backlog:int = 0):void
public function get bound():Boolean
public function get listening():Boolean
public function get localAddress():String
public function get localPort():int
Air Native Extension
1 Comment

Diadraw Air Camera

Diadraw Air Camera is an Adobe Native Extension that allows you to capture static frames from the iPhone/iPad video camera at a chosen frame rate and resolution. It is possible to choose whether to lock the focus, exposure or white balance or to have them done automatically by the camera.

It is also possible to set a point of interest to expose for or to focus on. The extension also allows you to rotate, crop or translate frames.

Sample

private var m_lastFrameIdx : Number;

var minFramesPerSecond : Number = 15;
var maxFramesPerSecond : Number = 30;

var usingFrontCamera : Boolean = false;

if ( m_cameraExt.startVideoCamera( NativeCameraExtension.Preset640x480, 
                                   minFramesPerSecond, 
                                   maxFramesPerSecond, 
                                   usingFrontCamera ) )
{
     m_lastFrameIdx = int.MIN_VALUE;
     m_cameraExt.addEventListener( NativeCameraExtensionEvent.IMAGE_READY, handleImageReady );
}

private function handleImageReady( _event : NativeCameraExtensionEvent ) : void
{
    // Create a ByteArray to get the frame data into. You don't need to resize the array:
    m_byteArray = new ByteArray();                   
    var currentFrameIdx : Number = m_cameraExt.getFrameBuffer( m_byteArray, m_lastFrameIdx );

    // Check if we have already got this frame:                                
    if ( currentFrameIdx != m_lastFrameIdx )
    {
        m_lastFrameWidth = _event.frameWidth;
        m_lastFrameHeight = _event.frameHeight;

        // Extract BitmapData from the ByteArray
        var bd : BitmapData = new BitmapData( m_lastFrameWidth, m_lastFrameHeight, true );
        bd.setPixels( renderRect, _byteArray );

        // Perform any pixel processing here

        m_lastFrameIdx = currentFrameIdx;
    }       
}

// x and y can come from the point, where the user tapped the screen:
var pointOfInterest : Point = new Point( x, y );
m_cameraExt.setFocusMode( NativeCameraExtension.FocusModeContinuousAutoFocus, pointOfInterest );

// x and y can come from the point, where the user tapped the screen:
var pointOfInterest : Point = new Point( x, y );
m_cameraExt.setExposureMode( NativeCameraExtension.ExposureModeContinuousAutoExposure, pointOfInterest );
Air Native Extension, iOS
2 Comments

AS3LinAlg

AS3LinAlg is a linear algebra library. Its provides  up to four solvers: Jacobi SVD, Eigen Vectors/Values,  Cholesky, LU and Polynomial. The library requires Apparat to be compiled, but it doesn’t use Memory op-codes.

Sample

// JacobiSVD API:
public function decompose(A:Vector., m:int, n:int,  W:Vector., U:Vector., V:Vector., computeUV:Boolean = true, transposeV:Boolean = false, transposeU:Boolean = false):void
public function pseudoInverse(inv:Vector., mtx:Vector., m:int, n:int):void
public function solve(A:Vector., m:int, n:int, x:Vector., B:Vector.):void
Math
1 Comment