package aerys.minko.scene.controller.camera
{
	import aerys.minko.render.Viewport;
	import aerys.minko.scene.controller.AbstractScriptController;
	import aerys.minko.scene.controller.EnterFrameController;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.type.math.Matrix4x4;
	import aerys.minko.type.math.Vector4;

	import flash.display.BitmapData;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Keyboard;

	public class FirstPersonCameraController extends AbstractScriptController
	{
		private static const TMP_MATRIX 	: Matrix4x4 = new Matrix4x4();

		private var _ghostMode				: Boolean	= true;
		private var _rotation				: Vector4	= new Vector4();
		private var _enabled				: Boolean	= true;
		private var _update					: Boolean	= false;
		private var _step					: Number	= 1;

		private var _mousePosition			: Point		= new Point();
		private var _position				: Vector4	= new Vector4(0, 0, 0, 1);
		private var _lookAt					: Vector4	= new Vector4(0, 0, 0, 1);
		private var _up						: Vector4	= new Vector4(0, 1, 0, 1);

		public function get enabled() : Boolean
		{
			return _enabled;
		}

		public function set enabled(value : Boolean) : void
		{
			_enabled = value;
		}

		public function get ghostMode() : Boolean
		{
			return _ghostMode;
		}

		public function set ghostMode(value : Boolean) : void
		{
			_ghostMode = value;
		}

		public function get step() : Number
		{
			return _step;
		}

		public function set step(value : Number) : void
		{
			_step = value;
		}

		public function FirstPersonCameraController()
		{
			super ();
		}

		public function bindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
		{
			dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

			return this;
		}

		public function unbindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
		{
			dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

			return this;
		}

		override protected function sceneEnterFrameHandler(scene		: Scene,
														   viewport		: Viewport,
														   destination	: BitmapData,
														   time			: Number) : void
		{
			super.sceneEnterFrameHandler(scene, viewport, destination, time);

			if (_update && _enabled)
			{
				_lookAt.x = _position.x + Math.sin(_rotation.y) * Math.cos(_rotation.x);
				_lookAt.y = _position.y + Math.sin(_rotation.x);
				_lookAt.z = _position.z + Math.cos(_rotation.y) * Math.cos(_rotation.x);

				TMP_MATRIX.lookAt(_lookAt, _position, _up);

				var numTargets : uint = this.numTargets;
				for (var targetId : uint = 0; targetId < numTargets; ++targetId)
					getTarget(targetId).transform.copyFrom(TMP_MATRIX);

				_update = false;
			}
		}

		public function walk(distance : Number) : void
		{
			if (_ghostMode)
			{
				_position.y += Math.sin(_rotation.x) * distance;
				_position.x += Math.sin(_rotation.y) * Math.cos(-_rotation.x) * distance;
				_position.z += Math.cos(_rotation.y) * Math.cos(-_rotation.x) * distance;
			}
			else
			{
				_position.x += Math.sin(_rotation.y) * distance;
				_position.z += Math.cos(_rotation.y) * distance;
			}

			_update = true;
		}

		public function strafe(distance : Number) : void
		{
			_position.x += Math.sin(_rotation.y + Math.PI / 2) * distance;
			_position.z += Math.cos(_rotation.y + Math.PI / 2) * distance;

			_update = true;
		}

		override protected function update(target : ISceneNode) : void
		{
			if (keyboard.keyIsDown(Keyboard.RIGHT))
				strafe(_step);
			if (keyboard.keyIsDown(Keyboard.LEFT))
				strafe(-_step);
			if (keyboard.keyIsDown(Keyboard.UP))
				walk(_step);
			if (keyboard.keyIsDown(Keyboard.DOWN))
				walk(-_step);
		}

		override protected function targetAddedHandler(ctrl 	: EnterFrameController,
													   target 	: ISceneNode) : void
		{
			super.targetAddedHandler(ctrl, target);

			_update = true;
		}

		private function mouseMoveHandler(event : MouseEvent) : void
		{
			if (event.buttonDown)
			{
				_rotation.y += -(_mousePosition.x - event.stageX) * .005;
				_rotation.x += (_mousePosition.y - event.stageY) * .005;

				_update = true;
			}

			_mousePosition.setTo(event.stageX, event.stageY);
		}
	}
}

package aerys.minko.scene.controller.camera
{
	import aerys.minko.render.Viewport;
	import aerys.minko.scene.controller.AbstractScriptController;
	import aerys.minko.scene.controller.EnterFrameController;
	import aerys.minko.scene.node.ISceneNode;
	import aerys.minko.scene.node.Scene;
	import aerys.minko.type.math.Matrix4x4;
	import aerys.minko.type.math.Vector4;

	import flash.display.BitmapData;
	import flash.display.Stage;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Keyboard;

	public class FirstPersonCameraController extends AbstractScriptController
	{
		private static const TMP_MATRIX 	: Matrix4x4 = new Matrix4x4();

		private var _stage					: Stage		= null;

		private var _ghostMode				: Boolean	= true;
		private var _rotation				: Vector4	= new Vector4();
		private var _enabled				: Boolean	= true;
		private var _update					: Boolean	= false;
		private var _step					: Number	= 1;

		private var _mousePosition			: Point		= new Point();
		private var _position				: Vector4	= new Vector4(0, 0, 0, 1);
		private var _lookAt					: Vector4	= new Vector4(0, 0, 0, 1);
		private var _up						: Vector4	= new Vector4(0, 1, 0, 1);

		public function get enabled() : Boolean
		{
			return _enabled;
		}

		public function set enabled(value : Boolean) : void
		{
			_enabled = value;
		}

		public function get ghostMode() : Boolean
		{
			return _ghostMode;
		}

		public function set ghostMode(value : Boolean) : void
		{
			_ghostMode = value;
		}

		public function get step() : Number
		{
			return _step;
		}

		public function set step(value : Number) : void
		{
			_step = value;
		}

		public function FirstPersonCameraController(stage : Stage)
		{
			_stage = stage;
		}

		public function bindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
		{
			dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

			return this;
		}

		public function unbindDefaultControls(dispatcher : IEventDispatcher) : FirstPersonCameraController
		{
			dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);

			return this;
		}

		override protected function sceneEnterFrameHandler(scene		: Scene,
														   viewport		: Viewport,
														   destination	: BitmapData,
														   time			: Number) : void
		{
			super.sceneEnterFrameHandler(scene, viewport, destination, time);

			if (_update && _enabled)
			{
				_lookAt.x = _position.x + Math.sin(_rotation.y) * Math.cos(_rotation.x);
				_lookAt.y = _position.y + Math.sin(_rotation.x);
				_lookAt.z = _position.z + Math.cos(_rotation.y) * Math.cos(_rotation.x);

				TMP_MATRIX.lookAt(_lookAt, _position, _up);

				var numTargets : uint = this.numTargets;
				for (var targetId : uint = 0; targetId < numTargets; ++targetId)
					getTarget(targetId).transform.copyFrom(TMP_MATRIX);

				_update = false;
			}
		}

		public function walk(distance : Number) : void
		{
			if (_ghostMode)
			{
				_position.y += Math.sin(_rotation.x) * distance;
				_position.x += Math.sin(_rotation.y) * Math.cos(-_rotation.x) * distance;
				_position.z += Math.cos(_rotation.y) * Math.cos(-_rotation.x) * distance;
			}
			else
			{
				_position.x += Math.sin(_rotation.y) * distance;
				_position.z += Math.cos(_rotation.y) * distance;
			}

			_update = true;
		}

		public function strafe(distance : Number) : void
		{
			_position.x += Math.sin(_rotation.y + Math.PI / 2) * distance;
			_position.z += Math.cos(_rotation.y + Math.PI / 2) * distance;

			_update = true;
		}

		override protected function update(target : ISceneNode) : void
		{
			if (keyboard.keyIsDown(Keyboard.RIGHT))
				strafe(_step);
			if (keyboard.keyIsDown(Keyboard.LEFT))
				strafe(-_step);
			if (keyboard.keyIsDown(Keyboard.UP))
				walk(_step);
			if (keyboard.keyIsDown(Keyboard.DOWN))
				walk(-_step);
		}

		override protected function targetAddedHandler(ctrl 	: EnterFrameController,
													   target 	: ISceneNode) : void
		{
			super.targetAddedHandler(ctrl, target);

			_update = true;
		}

		private function mouseMoveHandler(event : MouseEvent) : void
		{
			if (event.buttonDown)
			{
				if (_stage && _stage.mouseLock)
				{
					_rotation.y += event.movementX * .005;
					_rotation.x += -event.movementY * .005;
				}
				else
				{
					_rotation.y += -(_mousePosition.x - event.stageX) * .005;
					_rotation.x += (_mousePosition.y - event.stageY) * .005;
				}

				_update = true;
			}

			_mousePosition.setTo(event.stageX, event.stageY);
		}
	}
}

Enable Mouse Lock API when available in the FPS camera.


##                                                         -*- shell-script -*-
## base.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##

m4_pattern_forbid([^_?URBI_])dnl

# m4_define([_m4_divert(M4SH-INIT)],   5)
m4_define([_m4_divert(URBI-INIT)],    10)

m4_defun([_URBI_ABSOLUTE_PREPARE],
[
# is_absolute PATH
# ----------------
is_absolute ()
{
  case $[1] in
    ([[\\/]]* | ?:[[\\/]]*) return 0;;
    (                    *) return 1;;
  esac
}

# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
  local res
  AS_IF([is_absolute "$[1]"],
  [# Absolute paths do not need to be expanded.
   res=$[1]],
  [local dir=$(pwd)/$(dirname "$[1]")
   if test -d "$dir"; then
     res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]")
   else
     fatal "absolute: not a directory: $dir"
   fi])

  # On Windows, we must make sure we have a Windows-like UNIX-friendly path (of
  # the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice
  # the use of forward slashes in the Windows path.  Windows *does* understand
  # paths with forward slashes).
  case $(uname -s) in
    (CYGWIN*) res=$(cygpath "$res")
  esac
  echo "$res"
}
])

m4_defun([_URBI_FIND_PROG_PREPARE],
[# find_file FILE PATH
# -------------------
# Return full path to FILE in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
  _AS_PATH_WALK([$[2]],
                [AS_IF([test -f $as_dir/$[1]],
                       [echo "$as_dir/$[1]"; break])])
}

# xfind_file PROG PATH
# --------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_file ()
{
  local res
  res=$(find_prog "$[1]" "$[2]")
  test -n "$res" ||
    error OSFILE "cannot find $[1] in $[2]"
  echo "$res"
}

# find_prog PROG [PATH=$PATH]
# ---------------------------
# Return full path to PROG in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
  local path=$PATH
  test -z "$[2]" || path=$[2]

  _AS_PATH_WALK([$path],
                [AS_IF([AS_TEST_X([$as_dir/$[1]])],
                       [echo "$as_dir/$[1]"; break])])
}

# xfind_prog PROG [PATH=$PATH]
# ----------------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_prog ()
{
  local path=$PATH
  test -z "$[2]" || path=$[2]
  local res
  res=$(find_prog "$[1]" "$path")
  test -n "$res" ||
    error OSFILE "cannot find executable $[1] in $path"
  echo "$res"
}

# require_thing TEST-FLAG ERROR_MESSAGE THING [HINT]
# --------------------------------------------------
require_thing ()
{
  local flag=$[1]
  local error="$[2]: $[3]"
  local thing=$[3]
  shift 3
  test $flag "$thing" ||
    error OSFILE "$error" "$[@]"
}

# require_dir DIR [HINT]
# ----------------------
require_dir ()
{
  require_thing -d "no such directory" "$[@]"
}

# require_file FILE [HINT]
# ------------------------
require_file ()
{
  require_thing -f "no such file" "$[@]"
}

])

m4_defun([_URBI_STDERR_PREPARE],
[
# stderr LINES
# ------------
stderr ()
{
  local i
  for i
  do
    echo >&2 "$as_me: $i"
  done
# This line is a nuisance in usual output, yet it makes sense in debug
# output in RST files.  But the problem should be solved there
# instead.
#
#  echo >&2
}

# verbose LINES
# -------------
verbose ()
{
  case $verbose:" $VERBOSE " in
    (*true:*|*" $me "*) stderr "$@";;
  esac
}

# error EXIT MESSAGES
# -------------------
error ()
{
  local exit=$[1]
  shift
  stderr "$[@]"
  ex_exit $exit
}

# fatal MESSAGES
# --------------
fatal ()
{
  # To help the user, just make sure that she is not confused between
  # the prototypes of fatal and error: the first argument is unlikely
  # to be integer.
  case $[1] in
    (*[[!0-9]]*|'') ;;
    (*)  stderr "warning: possible confusion between fatal and error" \
                "fatal $[*]";;
  esac

  error 1 "$[@]"
}

# ex_to_string EXIT
# -----------------
# Return a decoding of EXIT status if available, nothing otherwise.
ex_to_string ()
{
  case $[1] in
     (  0) echo ' (EX_OK: successful termination)';;
     ( 64) echo ' (EX_USAGE: command line usage error)';;
     ( 65) echo ' (EX_DATAERR: data format error)';;
     ( 66) echo ' (EX_NOINPUT: cannot open input)';;
     ( 67) echo ' (EX_NOUSER: addressee unknown)';;
     ( 68) echo ' (EX_NOHOST: host name unknown)';;
     ( 69) echo ' (EX_UNAVAILABLE: service unavailable)';;
     ( 70) echo ' (EX_SOFTWARE: internal software error)';;
     ( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';;
     ( 72) echo ' (EX_OSFILE: critical OS file missing)';;
     ( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';;
     ( 74) echo ' (EX_IOERR: input/output error)';;
     ( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';;
     ( 76) echo ' (EX_PROTOCOL: remote error in protocol)';;
     ( 77) echo ' (EX_NOPERM: permission denied)';;
     ( 78) echo ' (EX_CONFIG: configuration error)';;
     (176) echo ' (EX_SKIP: skip this test with unmet dependencies)';;
     (177) echo ' (EX_HARD: hard error that cannot be saved)';;
     (242) echo ' (killed by Valgrind)';;
     (  *) if test 127 -lt $[1]; then
            echo " (SIG$(kill -l $[1] || true))"
          fi;;
  esac
}

# ex_to_int CODE
# --------------
# Decode the CODE and return the corresponding int.
ex_to_int ()
{
  case $[1] in
    (OK         |EX_OK)          echo 0;;
    (USAGE      |EX_USAGE)       echo 64;;
    (DATAERR    |EX_DATAERR)     echo 65;;
    (NOINPUT    |EX_NOINPUT)     echo 66;;
    (NOUSER     |EX_NOUSER)      echo 67;;
    (NOHOST     |EX_NOHOST)      echo 68;;
    (UNAVAILABLE|EX_UNAVAILABLE) echo 69;;
    (SOFTWARE   |EX_SOFTWARE)    echo 70;;
    (OSERR      |EX_OSERR)       echo 71;;
    (OSFILE     |EX_OSFILE)      echo 72;;
    (CANTCREAT  |EX_CANTCREAT)   echo 73;;
    (IOERR      |EX_IOERR)       echo 74;;
    (TEMPFAIL   |EX_TEMPFAIL)    echo 75;;
    (PROTOCOL   |EX_PROTOCOL)    echo 76;;
    (NOPERM     |EX_NOPERM)      echo 77;;
    (CONFIG     |EX_CONFIG)      echo 78;;

    (SKIP       |EX_SKIP)        echo 176;;
    (HARD       |EX_HARD)        echo 177;;

    (*)                          echo $[1];;
  esac
}

ex_exit ()
{
  exit $(ex_to_int $[1])
}
])

# URBI_GET_OPTIONS
# ----------------
# Generate get_options().
m4_define([URBI_GET_OPTIONS],
[# Parse command line options
get_options ()
{
  while test $[#] -ne 0; do
    case $[1] in
        (--*=*)
            opt=$(echo "$[1]" | sed -e 's/=.*//')
            val=$(echo "$[1]" | sed -e ['s/[^=]*=//'])
            shift
            set dummy "$opt" "$val" ${1+"$[@]"};
            shift
            ;;
    esac

    case $[1] in
      $@
    esac
    shift
  done
}
])

m4_defun([_URBI_PREPARE],
[
# mkcd DIR
# --------
# Remove, create, and cd into DIR.
mkcd ()
{
  local dir=$[1]
  rm -rf "$dir"
  mkdir -p "$dir"
  cd "$dir"
}

# truth TEST-ARGUMENTS...
# -----------------------
# Run "test TEST-ARGUMENTS" and echo true/false depending on the result.
truth ()
{
  if test "$[@]"; then
    echo true
  else
    echo false
  fi
}

_URBI_ABSOLUTE_PREPARE
_URBI_FIND_PROG_PREPARE
_URBI_STDERR_PREPARE

])

# URBI_PREPARE
# ------------
# Output all the M4sh possible initialization into the initialization
# diversion.
m4_defun([URBI_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl
URBI_RST_PREPARE()dnl
URBI_INSTRUMENT_PREPARE()dnl
URBI_CHILDREN_PREPARE()dnl
])

# URBI_INIT
# ---------
# Replaces the AS_INIT invocation.
# Must be defined via "m4_define", not "m4_defun" since it is AS_INIT
# which will set up the diversions used for "m4_defun".
m4_define([URBI_INIT],
[AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
  (x) set -x;;
esac

# We can only check absolute dirs, since we may be called from other
# directories than the ones we were created from.
: ${abs_builddir='@abs_builddir@'}
: ${abs_srcdir='@abs_srcdir@'}
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
: ${builddir='@builddir@'}
: ${srcdir='@srcdir@'}
: ${top_builddir='@top_builddir@'}
: ${top_srcdir='@top_srcdir@'}

# Bounce the signals to trap 0, passing the signal as exit value.
for signal in 1 2 13 15; do
  trap 'error $((128 + $signal)) \
	      "received signal $signal ($(kill -l $signal))"' $signal
done
])

##                                                         -*- shell-script -*-
## base.as: This file is part of build-aux.
## Copyright (C) Gostai S.A.S., 2006-2008.
##
## This software is provided "as is" without warranty of any kind,
## either expressed or implied, including but not limited to the
## implied warranties of fitness for a particular purpose.
##
## See the LICENSE file for more information.
## For comments, bug reports and feedback: http://www.urbiforge.com
##

m4_pattern_forbid([^_?URBI_])dnl

# m4_define([_m4_divert(M4SH-INIT)],   5)
m4_define([_m4_divert(URBI-INIT)],    10)

m4_defun([_URBI_ABSOLUTE_PREPARE],
[
# is_absolute PATH
# ----------------
is_absolute ()
{
  case $[1] in
    ([[\\/]]* | ?:[[\\/]]*) return 0;;
    (                    *) return 1;;
  esac
}

# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
  local res
  AS_IF([is_absolute "$[1]"],
  [# Absolute paths do not need to be expanded.
   res=$[1]],
  [local dir=$(pwd)/$(dirname "$[1]")
   if test -d "$dir"; then
     res=$(cd "$dir" 2>/dev/null && pwd)/$(basename "$[1]")
   else
     fatal "absolute: not a directory: $dir"
   fi])

  # On Windows, we must make sure we have a Windows-like UNIX-friendly path (of
  # the form C:/cygwin/path/to/somewhere instead of /path/to/somewhere, notice
  # the use of forward slashes in the Windows path.  Windows *does* understand
  # paths with forward slashes).
  case $(uname -s) in
    (CYGWIN*) res=$(cygpath "$res")
  esac
  echo "$res"
}
])

m4_defun([_URBI_FIND_PROG_PREPARE],
[# find_file FILE PATH
# -------------------
# Return full path to FILE in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
  _AS_PATH_WALK([$[2]],
                [AS_IF([test -f $as_dir/$[1]],
                       [echo "$as_dir/$[1]"; break])])
}

# xfind_file PROG PATH
# --------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_file ()
{
  local res
  res=$(find_prog "$[1]" "$[2]")
  test -n "$res" ||
    error OSFILE "cannot find $[1] in $[2]"
  echo "$res"
}

# find_prog PROG [PATH=$PATH]
# ---------------------------
# Return full path to PROG in PATH ($PATH_SEPARATOR separated),
# nothing if not found.
find_prog ()
{
  local path=$PATH
  test -z "$[2]" || path=$[2]

  _AS_PATH_WALK([$path],
                [AS_IF([AS_TEST_X([$as_dir/$[1]])],
                       [echo "$as_dir/$[1]"; break])])
}

# xfind_prog PROG [PATH=$PATH]
# ----------------------------
# Same as xfind_prog, but don't take "no" for an answer.
xfind_prog ()
{
  local path=$PATH
  test -z "$[2]" || path=$[2]
  local res
  res=$(find_prog "$[1]" "$path")
  test -n "$res" ||
    error OSFILE "cannot find executable $[1] in $path"
  echo "$res"
}

# require_thing TEST-FLAG ERROR_MESSAGE THING [HINT]
# --------------------------------------------------
require_thing ()
{
  local flag=$[1]
  local error="$[2]: $[3]"
  local thing=$[3]
  shift 3
  test $flag "$thing" ||
    error OSFILE "$error" "$[@]"
}

# require_dir DIR [HINT]
# ----------------------
require_dir ()
{
  require_thing -d "no such directory" "$[@]"
}

# require_file FILE [HINT]
# ------------------------
require_file ()
{
  require_thing -f "no such file" "$[@]"
}

])

m4_defun([_URBI_STDERR_PREPARE],
[
# stderr LINES
# ------------
stderr ()
{
  local i
  for i
  do
    echo >&2 "$as_me: $i"
  done
# This line is a nuisance in usual output, yet it makes sense in debug
# output in RST files.  But the problem should be solved there
# instead.
#
#  echo >&2
}

# verbose LINES
# -------------
verbose ()
{
  case $verbose:" $VERBOSE " in
    (true:*|*" $me "*) stderr "$[@]";;
  esac
}

# error EXIT MESSAGES
# -------------------
error ()
{
  local exit=$[1]
  shift
  stderr "$[@]"
  ex_exit $exit
}

# fatal MESSAGES
# --------------
fatal ()
{
  # To help the user, just make sure that she is not confused between
  # the prototypes of fatal and error: the first argument is unlikely
  # to be integer.
  case $[1] in
    (*[[!0-9]]*|'') ;;
    (*)  stderr "warning: possible confusion between fatal and error" \
                "fatal $[*]";;
  esac

  error 1 "$[@]"
}

# ex_to_string EXIT
# -----------------
# Return a decoding of EXIT status if available, nothing otherwise.
ex_to_string ()
{
  case $[1] in
     (  0) echo ' (EX_OK: successful termination)';;
     ( 64) echo ' (EX_USAGE: command line usage error)';;
     ( 65) echo ' (EX_DATAERR: data format error)';;
     ( 66) echo ' (EX_NOINPUT: cannot open input)';;
     ( 67) echo ' (EX_NOUSER: addressee unknown)';;
     ( 68) echo ' (EX_NOHOST: host name unknown)';;
     ( 69) echo ' (EX_UNAVAILABLE: service unavailable)';;
     ( 70) echo ' (EX_SOFTWARE: internal software error)';;
     ( 71) echo ' (EX_OSERR: system error (e.g., cannot fork))';;
     ( 72) echo ' (EX_OSFILE: critical OS file missing)';;
     ( 73) echo ' (EX_CANTCREAT: cannot create (user) output file)';;
     ( 74) echo ' (EX_IOERR: input/output error)';;
     ( 75) echo ' (EX_TEMPFAIL: temp failure; user is invited to retry)';;
     ( 76) echo ' (EX_PROTOCOL: remote error in protocol)';;
     ( 77) echo ' (EX_NOPERM: permission denied)';;
     ( 78) echo ' (EX_CONFIG: configuration error)';;
     (176) echo ' (EX_SKIP: skip this test with unmet dependencies)';;
     (177) echo ' (EX_HARD: hard error that cannot be saved)';;
     (242) echo ' (killed by Valgrind)';;
     (  *) if test 127 -lt $[1]; then
            echo " (SIG$(kill -l $[1] || true))"
          fi;;
  esac
}

# ex_to_int CODE
# --------------
# Decode the CODE and return the corresponding int.
ex_to_int ()
{
  case $[1] in
    (OK         |EX_OK)          echo 0;;
    (USAGE      |EX_USAGE)       echo 64;;
    (DATAERR    |EX_DATAERR)     echo 65;;
    (NOINPUT    |EX_NOINPUT)     echo 66;;
    (NOUSER     |EX_NOUSER)      echo 67;;
    (NOHOST     |EX_NOHOST)      echo 68;;
    (UNAVAILABLE|EX_UNAVAILABLE) echo 69;;
    (SOFTWARE   |EX_SOFTWARE)    echo 70;;
    (OSERR      |EX_OSERR)       echo 71;;
    (OSFILE     |EX_OSFILE)      echo 72;;
    (CANTCREAT  |EX_CANTCREAT)   echo 73;;
    (IOERR      |EX_IOERR)       echo 74;;
    (TEMPFAIL   |EX_TEMPFAIL)    echo 75;;
    (PROTOCOL   |EX_PROTOCOL)    echo 76;;
    (NOPERM     |EX_NOPERM)      echo 77;;
    (CONFIG     |EX_CONFIG)      echo 78;;

    (SKIP       |EX_SKIP)        echo 176;;
    (HARD       |EX_HARD)        echo 177;;

    (*)                          echo $[1];;
  esac
}

ex_exit ()
{
  exit $(ex_to_int $[1])
}
])

# URBI_GET_OPTIONS
# ----------------
# Generate get_options().
m4_define([URBI_GET_OPTIONS],
[# Parse command line options
get_options ()
{
  while test $[#] -ne 0; do
    case $[1] in
        (--*=*)
            opt=$(echo "$[1]" | sed -e 's/=.*//')
            val=$(echo "$[1]" | sed -e ['s/[^=]*=//'])
            shift
            set dummy "$opt" "$val" ${1+"$[@]"};
            shift
            ;;
    esac

    case $[1] in
      $@
    esac
    shift
  done
}
])

m4_defun([_URBI_PREPARE],
[
# mkcd DIR
# --------
# Remove, create, and cd into DIR.
mkcd ()
{
  local dir=$[1]
  rm -rf "$dir"
  mkdir -p "$dir"
  cd "$dir"
}

# truth TEST-ARGUMENTS...
# -----------------------
# Run "test TEST-ARGUMENTS" and echo true/false depending on the result.
truth ()
{
  if test "$[@]"; then
    echo true
  else
    echo false
  fi
}

_URBI_ABSOLUTE_PREPARE
_URBI_FIND_PROG_PREPARE
_URBI_STDERR_PREPARE

])

# URBI_PREPARE
# ------------
# Output all the M4sh possible initialization into the initialization
# diversion.
m4_defun([URBI_PREPARE],
[m4_divert_text([M4SH-INIT], [_URBI_PREPARE])dnl
URBI_RST_PREPARE()dnl
URBI_INSTRUMENT_PREPARE()dnl
URBI_CHILDREN_PREPARE()dnl
])

# URBI_INIT
# ---------
# Replaces the AS_INIT invocation.
# Must be defined via "m4_define", not "m4_defun" since it is AS_INIT
# which will set up the diversions used for "m4_defun".
m4_define([URBI_INIT],
[AS_INIT()dnl
URBI_PREPARE()
set -e
case $VERBOSE in
  (x) set -x;;
esac

# We can only check absolute dirs, since we may be called from other
# directories than the ones we were created from.
: ${abs_builddir='@abs_builddir@'}
: ${abs_srcdir='@abs_srcdir@'}
: ${abs_top_builddir='@abs_top_builddir@'}
check_dir abs_top_builddir config.status
: ${abs_top_srcdir='@abs_top_srcdir@'}
check_dir abs_top_srcdir configure.ac
: ${builddir='@builddir@'}
: ${srcdir='@srcdir@'}
: ${top_builddir='@top_builddir@'}
: ${top_srcdir='@top_srcdir@'}

# Bounce the signals to trap 0, passing the signal as exit value.
for signal in 1 2 13 15; do
  trap 'error $((128 + $signal)) \
	      "received signal $signal ($(kill -l $signal))"' $signal
done
])

Fix m4 quotation issues.

Fix m4 quotation issues.

	* build-aux/base.as (verbose): here.


print("XML statics");
(function () {
  var tests = [
    [XML.ignoreWhitespace = true, XML.ignoreWhitespace],
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

print("Testing Basic XML");
(function () {
  var x = <foo a="aaa"><bar b="bbb">e=mc^2</bar></foo>;
  x.cat = <cat c="ccc"/>;
  x.@name = "x";
  x.@type = "T";
  var tests = [
    [x.name() == "foo", x.name()],
    [x.bar.name() == "bar", x.bar.name()],
    [x.@a == "aaa", x.@a],
    [x.@type == "T", x.@type],
    [x..bar == "e=mc^2", x..bar],
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

print("Testing Any Name");
(function () {
  var x = <foo a="aaa"><bar b="bbb"/><cat c="ccc"/></foo>;
  var r1 = <><bar b="bbb"/><cat c="ccc"/></>;
  var tests = [
    [x.*.toXMLString() === r1.toXMLString(), x.*.toXMLString()],
    [x.@*.toString() === "aaa", x.@*.toString()],
    [x.*.@*.toString() === "bbbccc", x.*.@*.toString()],
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

print("Testing attribute() and attributes() methods");
(function () {
  var x = <foo a="aaa"><bar b="bbb"/><cat c="ccc"/></foo>;
  var r1 = <><bar b="bbb"/><cat c="ccc"/></>;
  var tests = [
    [x.attribute("*"), x.attribute("*")],
    [x.attributes(), x.attributes()],
    [x.*.attribute("*"), x.*.attribute("*")],
    [x.*.attributes(), x.*.attributes()],
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

print("Testing enumeration");
(function () {
  var x = <><foo a="aaa"/><bar b="bbb"/><cat c="ccc"/></>;
  x.foo;
  var a = []
  for each (var v in x) {
    a.push(v.@*);
  }
  var tests = [
    [a]
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

print("Testing XMLList.prototype.setProperty() (aka [[PUT]])");
(function () {
  var x = <foo a="aaa"><bar b="bbb"/><bar/><cat c="ccc"/></foo>;
  var tests = [
    [x.bar.toXMLString()],
//    [x.bar = "barbarbar", x.bar.toXMLString()],
//    [x.* = "***", x.toXMLString()]
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

print("Testing YouTube use of E4X");
class A {}
(function () {
  var variable:*;
  var type:XML;
  var eventClass:Class;

  var loc1:*;
  variable = undefined;
  eventClass = A;
  type =
    <type name="avmplus::A" base="Class" isDynamic="true" isFinal="true" isStatic="true">
      <extendsClass type="Class"/>
      <extendsClass type="Object"/>
      <variable name="c" type="String"/>
      <variable name="b" type="String"/>
      <variable name="a" type="String"/>
      <factory type="avmplus::A">
        <extendsClass type="Object"/>
        <variable name="x" type="*"/>
        <variable name="z" type="*"/>
        <variable name="y" type="*"/>
      </factory>
    </type>;

  var loc2:*=0;
  var loc5:*=0;
  var loc6:*=type;
  var loc4:*=new XMLList("");
  for each (var loc7:* in loc6.*) {
    var loc8:*;
    with (loc8 = loc7) {
      if (@type == "String") {
        loc4[loc5++] = loc7;
      }
    }
  }
  var loc3:*=loc4;
  for each (variable in loc3) {
      eventClass[variable.@name] = type.@name + "." + variable.@name;
  }
  var keys = [];
  for (var p in eventClass) {
    keys.push(p);
  }
  keys.sort();
  for (var i = 0; i < keys.length; i++) {
    var p = keys[i];
    print("eventClass[p]="+eventClass[p]);
  }
})();

print("Testing XML.prototype.child as used by Candy Crush");
(function () {
  var x = new XML(
    '<gamedata randomseed="1282661104" version="1">' +
    '<musicOn>false</musicOn>' +
    '<soundOn>true</soundOn>' +
    '<isShortGame>false</isShortGame>' +
    '<booster_1>0</booster_1>' +
    '<booster_2>0</booster_2>' +
    '<booster_3>0</booster_3>' +
    '<booster_4>0</booster_4>' +
    '<booster_5>0</booster_5>' +
    '<bestScore>100</bestScore>' +
    '<bestChain>2</bestChain>' +
    '<bestLevel>1</bestLevel>' +
    '<bestCrushed>5</bestCrushed>' +
    '<bestMixed>2</bestMixed>' +
    '<text id="intro.time">Le jeu commence dans {0} secondes</text>' +
    '<text id="intro.title">Speel als volgt:</text>' +
    '<text id="intro.info1">Sett sammen 3 godteri i samme farge for å knuse  ...</text>' +
    '<text id="intro.info2">You can also combine the power candy for additio ...</text>' +
    '<text id="game.nomoves">No more moves!</text>' +
    '<text id="outro.opengame">Please register to play the full game</text>' +
    '<text id="outro.title">Game Over</text>' +
    '<text id="outro.now">now</text>' +
    '<text id="outro.bestever">best ever</text>' +
    '<text id="outro.score">Score</text>' +
    '<text id="outro.chain">Longest chain</text>' +
    '<text id="outro.level">Level reached</text>' +
    '<text id="outro.crushed">Candy crushed</text>' +
    '<text id="outro.time">Game ends in {0} seconds</text>' +
    '<text id="outro.trophy.one">crushed {0} candy in one game</text>' +
    '<text id="outro.trophy.two">scored {0} in one game</text>' +
    '<text id="outro.trophy.three">made {0} combined candy in one game</text>' +
    '<text id="outro.combo_wrapper_line">combo wrapper line description</text>' +
    '<text id="outro.combo_color_color">combo color color description</text>' +
    '<text id="outro.combo_color_line">combo color line description</text>' +
    '<text id="outro.combo_color_wrapper">combo color wrapper description. ...</text>' +
    '</gamedata>');
  var tests = [
    [x.child("text").length()],
  ];
  for (var i = 0; i < tests.length; i++) {
    print(i + ": " + tests[i]);
  }
})();

Add test for XML.prototype.child() as used by Candy Crush


package com.axis.rtspclient {
  import com.axis.ErrorManager;

  import flash.utils.ByteArray;

  public class BitArray extends ByteArray {
    private var src:ByteArray;
    private var byte:uint;
    private var bitpos:uint;

    public function BitArray(src:ByteArray) {
      this.src    = src;
      this.bitpos = 0;
      this.byte   = 0; /* This should really be undefined, uint wont allow it though */
    }

    public function readBits(length:uint):uint {
      if (32 < length || 0 === length) {
       /* To big for an uint */
       ErrorManager.dispatchError(819, null, true);
      }

      var result:uint = 0;
      for (var i:uint = 1; i <= length; ++i) {
        if (0 === bitpos) {
          /* Previous byte all read out. Get a new one. */
          byte = src.readUnsignedByte();
        }

        /* Shift result one left to make room for another bit,
           then add the next bit on the stream. */
        result = (result << 1) | ((byte >> (8 - (++bitpos))) & 0x01);
        bitpos %= 8;
      }

      return result;
    }

    public function readUnsignedExpGolomb():uint {
      var bitsToRead:uint = 0;
      while (readBits(1) !== 1) bitsToRead++;

      if (bitsToRead == 0) return 0; /* Easy peasy, just a single 1. This is 0 in exp golomb */
      if (bitsToRead >= 31) ErrorManager.dispatchError(820, null, true);

      var n:uint = readBits(bitsToRead); /* Read all bits part of this number */
      n |= (0x1 << (bitsToRead)); /* Move in the 1 read by while-statement above */

      return n - 1; /* Because result in exp golomb is one larger */
    }

    private function readSignedExpGolomb(sps:BitArray):uint {
        var r:uint = this.readUnsignedExpGolomb();
        if (r & 0x01) {
            r = (r+1) >> 1;
        } else {
            r = -(r >> 1);
        }
        return r;
    }
  }
}

package com.axis.rtspclient {
  import com.axis.ErrorManager;

  import flash.utils.ByteArray;

  public class BitArray extends ByteArray {
    private var src:ByteArray;
    private var byte:uint;
    private var bitpos:uint;

    public function BitArray(src:ByteArray) {
      this.src    = src;
      this.bitpos = 0;
      this.byte   = 0; /* This should really be undefined, uint wont allow it though */
    }

    public function readBits(length:uint):uint {
      if (32 < length || 0 === length) {
       /* To big for an uint */
       ErrorManager.dispatchError(819, null, true);
      }

      var result:uint = 0;
      for (var i:uint = 1; i <= length; ++i) {
        if (0 === bitpos) {
          /* Previous byte all read out. Get a new one. */
          byte = src.readUnsignedByte();
        }

        /* Shift result one left to make room for another bit,
           then add the next bit on the stream. */
        result = (result << 1) | ((byte >> (8 - (++bitpos))) & 0x01);
        bitpos %= 8;
      }

      return result;
    }

    public function readUnsignedExpGolomb():uint {
      var bitsToRead:uint = 0;
      while (readBits(1) !== 1) bitsToRead++;

      if (bitsToRead == 0) return 0; /* Easy peasy, just a single 1. This is 0 in exp golomb */
      if (bitsToRead >= 31) ErrorManager.dispatchError(820, null, true);

      var n:uint = readBits(bitsToRead); /* Read all bits part of this number */
      n |= (0x1 << (bitsToRead)); /* Move in the 1 read by while-statement above */

      return n - 1; /* Because result in exp golomb is one larger */
    }

    public function readSignedExpGolomb(sps:BitArray):uint {
        var r:uint = this.readUnsignedExpGolomb();
        if (r & 0x01) {
            r = (r+1) >> 1;
        } else {
            r = -(r >> 1);
        }
        return r;
    }
  }
}

make readSignedExpGolomb public

make readSignedExpGolomb public


package battlecode.common {

    public class RobotType {
        public static const ARCHON:String = "ARCHON";
        public static const SCOUT:String = "SCOUT";
        public static const SOLDIER:String = "SOLDIER";
        public static const GUARD:String = "GUARD";
        public static const VIPER:String = "VIPER";
        public static const TURRET:String = "TURRET";
        public static const TTM:String = "TTM";

        public static const ZOMBIEDEN:String = "ZOMBIEDEN";
        public static const STANDARDZOMBIE:String = "STANDARDZOMBIE";
        public static const FASTZOMBIE:String = "FASTZOMBIE";
        public static const RANGEDZOMBIE:String = "RANGEDZOMBIE";
        public static const BIGZOMBIE:String = "BIGZOMBIE";

        public function RobotType() {
        }

        public static function values():Array {
            return [
                ARCHON,
                SCOUT,
                SOLDIER,
                GUARD,
                VIPER,
                TURRET,
                TTM,
                ZOMBIEDEN,
                STANDARDZOMBIE,
                FASTZOMBIE,
                RANGEDZOMBIE,
                BIGZOMBIE
            ];
        }

        public static function units():Array {
            return [
                SOLDIER,
                GUARD,
                VIPER,
                SCOUT,
                TURRET,
                TTM
            ];
        }

        public static function zombies():Array {
            return [
                ZOMBIEDEN,
                STANDARDZOMBIE,
                FASTZOMBIE,
                RANGEDZOMBIE,
                BIGZOMBIE
            ]
        }

        public static function maxEnergon(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 1000;
                case SCOUT:
                    return 100;
                case SOLDIER:
                    return 60;
                case GUARD:
                    return 150;
                case VIPER:
                    return 120;
                case TURRET:
                    return 100;
                case TTM:
                    return 100;
                case ZOMBIEDEN:
                    return 2000;
                case STANDARDZOMBIE:
                    return 60;
                case RANGEDZOMBIE:
                    return 60;
                case FASTZOMBIE:
                    return 80;
                case BIGZOMBIE:
                    return 500;
            }
            throw new ArgumentError("Unknown type: " + type);
        }

        public static function movementDelay(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 2;
                case SCOUT:
                    return 1.4;
                case SOLDIER:
                    return 2;
                case GUARD:
                    return 2;
                case VIPER:
                    return 2;
                case TURRET:
                    return 0;
                case TTM:
                    return 2;
                case STANDARDZOMBIE:
                    return 3;
                case RANGEDZOMBIE:
                    return 3;
                case FASTZOMBIE:
                    return 1.4;
                case BIGZOMBIE:
                    return 3;
            }
            return 1;
        }

        public static function movementDelayDiagonal(type:String):uint {
            return movementDelay(type) * Math.SQRT2;
        }

        public static function attackDelay(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 2;
                case SCOUT:
                    return 1;
                case SOLDIER:
                    return 2;
                case GUARD:
                    return 2;
                case VIPER:
                    return 2;
                case TURRET:
                    return 0;
                case TTM:
                    return 2;
                case STANDARDZOMBIE:
                    return 2;
                case RANGEDZOMBIE:
                    return 1;
                case FASTZOMBIE:
                    return 1;
                case BIGZOMBIE:
                    return 3;
            }
            return 0;
        }

        public static function partValue(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 0;
                case SCOUT:
                    return 40;
                case SOLDIER:
                    return 30;
                case GUARD:
                    return 30;
                case VIPER:
                    return 100;
                case TURRET:
                    return 125;
                case TTM:
                    return 125;
                default:
                    return 0;
            }
        }

        public static function isZombie(type:String):Boolean {
            switch (type) {
                case ZOMBIEDEN:
                case STANDARDZOMBIE:
                case FASTZOMBIE:
                case RANGEDZOMBIE:
                case BIGZOMBIE:
                    return true;
            }
            return false;
        }
    }
}

package battlecode.common {

    public class RobotType {
        public static const ARCHON:String = "ARCHON";
        public static const SCOUT:String = "SCOUT";
        public static const SOLDIER:String = "SOLDIER";
        public static const GUARD:String = "GUARD";
        public static const VIPER:String = "VIPER";
        public static const TURRET:String = "TURRET";
        public static const TTM:String = "TTM";

        public static const ZOMBIEDEN:String = "ZOMBIEDEN";
        public static const STANDARDZOMBIE:String = "STANDARDZOMBIE";
        public static const FASTZOMBIE:String = "FASTZOMBIE";
        public static const RANGEDZOMBIE:String = "RANGEDZOMBIE";
        public static const BIGZOMBIE:String = "BIGZOMBIE";

        public function RobotType() {
        }

        public static function values():Array {
            return [
                ARCHON,
                SCOUT,
                SOLDIER,
                GUARD,
                VIPER,
                TURRET,
                TTM,
                ZOMBIEDEN,
                STANDARDZOMBIE,
                FASTZOMBIE,
                RANGEDZOMBIE,
                BIGZOMBIE
            ];
        }

        public static function units():Array {
            return [
                SOLDIER,
                GUARD,
                VIPER,
                SCOUT,
                TURRET,
                TTM
            ];
        }

        public static function zombies():Array {
            return [
                ZOMBIEDEN,
                STANDARDZOMBIE,
                FASTZOMBIE,
                RANGEDZOMBIE,
                BIGZOMBIE
            ]
        }

        public static function maxEnergon(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 1000;
                case SCOUT:
                    return 80;
                case SOLDIER:
                    return 60;
                case GUARD:
                    return 145;
                case VIPER:
                    return 120;
                case TURRET:
                    return 100;
                case TTM:
                    return 100;
                case ZOMBIEDEN:
                    return 2000;
                case STANDARDZOMBIE:
                    return 60;
                case RANGEDZOMBIE:
                    return 60;
                case FASTZOMBIE:
                    return 80;
                case BIGZOMBIE:
                    return 500;
            }
            throw new ArgumentError("Unknown type: " + type);
        }

        public static function movementDelay(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 2;
                case SCOUT:
                    return 1.4;
                case SOLDIER:
                    return 2;
                case GUARD:
                    return 2;
                case VIPER:
                    return 2;
                case TURRET:
                    return 0;
                case TTM:
                    return 2;
                case STANDARDZOMBIE:
                    return 3;
                case RANGEDZOMBIE:
                    return 3;
                case FASTZOMBIE:
                    return 1.4;
                case BIGZOMBIE:
                    return 3;
            }
            return 1;
        }

        public static function movementDelayDiagonal(type:String):uint {
            return movementDelay(type) * Math.SQRT2;
        }

        public static function attackDelay(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 2;
                case SCOUT:
                    return 1;
                case SOLDIER:
                    return 2;
                case GUARD:
                    return 2;
                case VIPER:
                    return 2;
                case TURRET:
                    return 0;
                case TTM:
                    return 2;
                case STANDARDZOMBIE:
                    return 2;
                case RANGEDZOMBIE:
                    return 1;
                case FASTZOMBIE:
                    return 1;
                case BIGZOMBIE:
                    return 3;
            }
            return 0;
        }

        public static function partValue(type:String):Number {
            switch (type) {
                case ARCHON:
                    return 0;
                case SCOUT:
                    return 25;
                case SOLDIER:
                    return 30;
                case GUARD:
                    return 30;
                case VIPER:
                    return 120;
                case TURRET:
                    return 130;
                case TTM:
                    return 130;
                default:
                    return 0;
            }
        }

        public static function isZombie(type:String):Boolean {
            switch (type) {
                case ZOMBIEDEN:
                case STANDARDZOMBIE:
                case FASTZOMBIE:
                case RANGEDZOMBIE:
                case BIGZOMBIE:
                    return true;
            }
            return false;
        }
    }
}

update robot type constants

update robot type constants


package org.denivip.osmf.elements.m3u8Classes
{
	import flash.events.EventDispatcher;

	import org.denivip.osmf.net.HLSDynamicStreamingResource;
	import org.osmf.events.ParseEvent;
	import org.osmf.logging.Log;
	import org.osmf.logging.Logger;
	import org.osmf.media.MediaResourceBase;
	import org.osmf.media.MediaType;
	import org.osmf.media.URLResource;
	import org.osmf.metadata.Metadata;
	import org.osmf.metadata.MetadataNamespaces;
	import org.osmf.net.DynamicStreamingItem;
	import org.osmf.net.DynamicStreamingResource;
	import org.osmf.net.StreamType;
	import org.osmf.net.StreamingItem;
	import org.osmf.net.StreamingURLResource;

	[Event(name="parseComplete", type="org.osmf.events.ParseEvent")]
	[Event(name="parseError", type="org.osmf.events.ParseEvent")]

	/**
	 * You will not belive, but this class parses *.m3u8 playlist
	 */
	public class M3U8PlaylistParser extends EventDispatcher
	{
		public function M3U8PlaylistParser(){
			// nothing todo here...
		}

		public function parse(value:String, baseResource:URLResource):void{

			if(!value || value == ''){
				throw new ArgumentError("Parsed value is missing =(");
			}

			var lines:Array = value.split(/\r?\n/);

			if(lines[0] != '#EXTM3U'){
				;
				CONFIG::LOGGING
				{
					logger.warn('Incorrect header! {0}', lines[0]);
				}
			}

			var result:MediaResourceBase;
			var isLive:Boolean = true;
			var streamItems:Vector.<DynamicStreamingItem>;
			var tempStreamingRes:StreamingURLResource = null;
			var tempDynamicRes:DynamicStreamingResource = null;
			var alternateStreams:Vector.<StreamingItem> = null;
			for(var i:int = 1; i < lines.length; i++){
				var line:String = String(lines[i]).replace(/^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2");

				if(line.indexOf("#EXTINF:") == 0){
					result = baseResource;
					tempStreamingRes = result as StreamingURLResource;

					if(tempStreamingRes && tempStreamingRes.streamType == StreamType.LIVE_OR_RECORDED){
						for(var j:int = i+1; j < lines.length; j++){
							if(String(lines[j]).indexOf('#EXT-X-ENDLIST') == 0){
								isLive = false;
								break;
							}
						}
						if(isLive)
							tempStreamingRes.streamType = StreamType.LIVE;
					}
					break;
				}

				if(line.indexOf("#EXT-X-STREAM-INF:") == 0){
					if(!result){
						result = new HLSDynamicStreamingResource(baseResource.url);
						tempDynamicRes = result as DynamicStreamingResource;
						tempStreamingRes = baseResource as StreamingURLResource;
						if(tempStreamingRes){
							tempDynamicRes.streamType = tempStreamingRes.streamType;
							tempDynamicRes.clipStartTime = tempStreamingRes.clipStartTime;
							tempDynamicRes.clipEndTime = tempStreamingRes.clipEndTime;
						}
						streamItems = new Vector.<DynamicStreamingItem>();
					}

					var bw:Number;
					if(line.search(/BANDWIDTH=(\d+)/) > 0)
						bw = parseFloat(line.match(/BANDWIDTH=(\d+)/)[1])/1000;

					var width:int = -1;
					var height:int = -1;
					if(line.search(/RESOLUTION=(\d+)x(\d+)/) > 0){
						width = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[1]);
						height = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[2]);
					}

					var name:String = lines[i+1];
					streamItems.push(new DynamicStreamingItem(name, bw, width, height));

					DynamicStreamingResource(result).streamItems = streamItems;
				}

				if(line.indexOf("#EXT-X-MEDIA:") == 0){
					if(line.search(/TYPE=(.*?)\W/) > 0 && line.match(/TYPE=(.*?)\W/)[1] == 'AUDIO'){
						var stUrl:String;
						var lang:String;
						var stName:String;
						if(line.search(/URI="(.*?)"/) > 0){
							stUrl = line.match(/URI="(.*?)"/)[1];
							if(stUrl.search(/(file|https?):\/\//) != 0){
								stUrl = baseResource.url.substr(0, baseResource.url.lastIndexOf('/')+1) + stUrl;
							}
						}
						if(line.search(/LANGUAGE="(.*?)"/) > 0){
							lang = line.match(/LANGUAGE="(.*?)"/)[1]
						}
						if(line.search(/NAME="(.*?)"/) > 0){
							stName = line.match(/NAME="(.*?)"/)[1];
						}
						if(!alternateStreams)
							alternateStreams = new Vector.<StreamingItem>();

						alternateStreams.push(
							new StreamingItem(MediaType.AUDIO, stUrl, 0, {label:stName, language:lang})
						);
					}
				}
			}

			if(tempDynamicRes && tempDynamicRes.streamItems){
				if(tempDynamicRes.streamItems.length == 1){
					tempStreamingRes = baseResource as StreamingURLResource;
					if(tempStreamingRes){
						var url:String = tempDynamicRes.host.substr(0, tempDynamicRes.host.lastIndexOf('/')+1) + tempDynamicRes.streamItems[0].streamName;
						result = new StreamingURLResource(
							url,
							tempStreamingRes.streamType,
							tempStreamingRes.clipStartTime,
							tempStreamingRes.clipEndTime,
							tempStreamingRes.connectionArguments,
							tempStreamingRes.urlIncludesFMSApplicationInstance,
							tempStreamingRes.drmContentData
						);
					}
				}else if(baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) != null){
					var initialIndex:int = baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) as int;
					tempDynamicRes.initialIndex = initialIndex < 0 ? 0 : (initialIndex >= tempDynamicRes.streamItems.length) ? (tempDynamicRes.streamItems.length-1) : initialIndex;
				}
			}

			baseResource.addMetadataValue("HLS_METADATA", new Metadata()); // fix for multistreaming resources
			result.addMetadataValue("HLS_METADATA", new Metadata());

			var httpMetadata:Metadata = new Metadata();
			result.addMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA, httpMetadata);

			if(alternateStreams && result is StreamingURLResource){
				(result as StreamingURLResource).alternativeAudioStreamItems = alternateStreams;
			}

			if(result is StreamingURLResource && StreamingURLResource(result).streamType == StreamType.DVR){
				var dvrMetadata:Metadata = new Metadata();
				result.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
			}

			dispatchEvent(new ParseEvent(ParseEvent.PARSE_COMPLETE, false, false, result));
		}
		/*
		private function addDVRInfo():void{

			CONFIG::LOGGING
			{
				logger.info('DVR!!! \\o/'); // we happy!
			}

			// black magic...
			var dvrInfo:DVRInfo = new DVRInfo();
			dvrInfo.id = dvrInfo.url = '';
			dvrInfo.isRecording = true; // if live then in process
			//dvrInfo.startTime = 0.0;
			// attach info into playlist
		}
		*/
		CONFIG::LOGGING
		{
			private var logger:Logger = Log.getLogger("org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser");
		}
	}
}

package org.denivip.osmf.elements.m3u8Classes
{
	import flash.events.EventDispatcher;

	import org.denivip.osmf.net.HLSDynamicStreamingResource;
	import org.osmf.events.ParseEvent;
	import org.osmf.logging.Log;
	import org.osmf.logging.Logger;
	import org.osmf.media.MediaResourceBase;
	import org.osmf.media.MediaType;
	import org.osmf.media.URLResource;
	import org.osmf.metadata.Metadata;
	import org.osmf.metadata.MetadataNamespaces;
	import org.osmf.net.DynamicStreamingItem;
	import org.osmf.net.DynamicStreamingResource;
	import org.osmf.net.StreamType;
	import org.osmf.net.StreamingItem;
	import org.osmf.net.StreamingURLResource;

	[Event(name="parseComplete", type="org.osmf.events.ParseEvent")]
	[Event(name="parseError", type="org.osmf.events.ParseEvent")]

	/**
	 * You will not belive, but this class parses *.m3u8 playlist
	 */
	public class M3U8PlaylistParser extends EventDispatcher
	{
		public function M3U8PlaylistParser(){
			// nothing todo here...
		}

		public function parse(value:String, baseResource:URLResource):void{

			if(!value || value == ''){
				throw new ArgumentError("Parsed value is missing =(");
			}

			var lines:Array = value.split(/\r?\n/);

			if(lines[0] != '#EXTM3U'){
				;
				CONFIG::LOGGING
				{
					logger.warn('Incorrect header! {0}', lines[0]);
				}
			}

			var result:MediaResourceBase;
			var isLive:Boolean = true;
			var streamItems:Vector.<DynamicStreamingItem>;
			var tempStreamingRes:StreamingURLResource = null;
			var tempDynamicRes:DynamicStreamingResource = null;
			var alternateStreams:Vector.<StreamingItem> = null;
			var initialStreamName:String = '';
			for(var i:int = 1; i < lines.length; i++){
				var line:String = String(lines[i]).replace(/^([\s|\t|\n]+)?(.*)([\s|\t|\n]+)?$/gm, "$2");

				if(line.indexOf("#EXTINF:") == 0){
					result = baseResource;
					tempStreamingRes = result as StreamingURLResource;

					if(tempStreamingRes && tempStreamingRes.streamType == StreamType.LIVE_OR_RECORDED){
						for(var j:int = i+1; j < lines.length; j++){
							if(String(lines[j]).indexOf('#EXT-X-ENDLIST') == 0){
								isLive = false;
								break;
							}
						}
						if(isLive)
							tempStreamingRes.streamType = StreamType.LIVE;
					}
					break;
				}

				if(line.indexOf("#EXT-X-STREAM-INF:") == 0){
					if(!result){
						result = new HLSDynamicStreamingResource(baseResource.url);
						tempDynamicRes = result as DynamicStreamingResource;
						tempStreamingRes = baseResource as StreamingURLResource;
						if(tempStreamingRes){
							tempDynamicRes.streamType = tempStreamingRes.streamType;
							tempDynamicRes.clipStartTime = tempStreamingRes.clipStartTime;
							tempDynamicRes.clipEndTime = tempStreamingRes.clipEndTime;
						}
						streamItems = new Vector.<DynamicStreamingItem>();
					}

					var bw:Number;
					if(line.search(/BANDWIDTH=(\d+)/) > 0)
						bw = parseFloat(line.match(/BANDWIDTH=(\d+)/)[1])/1000;

					var width:int = -1;
					var height:int = -1;
					if(line.search(/RESOLUTION=(\d+)x(\d+)/) > 0){
						width = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[1]);
						height = parseInt(line.match(/RESOLUTION=(\d+)x(\d+)/)[2]);
					}

					var name:String = lines[i+1];
					streamItems.push(new DynamicStreamingItem(name, bw, width, height));
					// store stream name of first stream encountered
					if(initialStreamName == ''){
						initialStreamName = name;
					}
					DynamicStreamingResource(result).streamItems = streamItems;
				}

				if(line.indexOf("#EXT-X-MEDIA:") == 0){
					if(line.search(/TYPE=(.*?)\W/) > 0 && line.match(/TYPE=(.*?)\W/)[1] == 'AUDIO'){
						var stUrl:String;
						var lang:String;
						var stName:String;
						if(line.search(/URI="(.*?)"/) > 0){
							stUrl = line.match(/URI="(.*?)"/)[1];
							if(stUrl.search(/(file|https?):\/\//) != 0){
								stUrl = baseResource.url.substr(0, baseResource.url.lastIndexOf('/')+1) + stUrl;
							}
						}
						if(line.search(/LANGUAGE="(.*?)"/) > 0){
							lang = line.match(/LANGUAGE="(.*?)"/)[1]
						}
						if(line.search(/NAME="(.*?)"/) > 0){
							stName = line.match(/NAME="(.*?)"/)[1];
						}
						if(!alternateStreams)
							alternateStreams = new Vector.<StreamingItem>();

						alternateStreams.push(
							new StreamingItem(MediaType.AUDIO, stUrl, 0, {label:stName, language:lang})
						);
					}
				}
			}

			if(tempDynamicRes && tempDynamicRes.streamItems){
				if(tempDynamicRes.streamItems.length == 1){
					tempStreamingRes = baseResource as StreamingURLResource;
					if(tempStreamingRes){
						var url:String = tempDynamicRes.host.substr(0, tempDynamicRes.host.lastIndexOf('/')+1) + tempDynamicRes.streamItems[0].streamName;
						result = new StreamingURLResource(
							url,
							tempStreamingRes.streamType,
							tempStreamingRes.clipStartTime,
							tempStreamingRes.clipEndTime,
							tempStreamingRes.connectionArguments,
							tempStreamingRes.urlIncludesFMSApplicationInstance,
							tempStreamingRes.drmContentData
						);
					}
				}else{
					if(baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) != null){
						var initialIndex:int = baseResource.getMetadataValue(MetadataNamespaces.RESOURCE_INITIAL_INDEX) as int;
						tempDynamicRes.initialIndex = initialIndex < 0 ? 0 : (initialIndex >= tempDynamicRes.streamItems.length) ? (tempDynamicRes.streamItems.length-1) : initialIndex;
					}else{
						// set initialIndex to index of first stream name encountered
						tempDynamicRes.initialIndex = tempDynamicRes.indexFromName(initialStreamName);
					}
				}
			}

			baseResource.addMetadataValue("HLS_METADATA", new Metadata()); // fix for multistreaming resources
			result.addMetadataValue("HLS_METADATA", new Metadata());

			var httpMetadata:Metadata = new Metadata();
			result.addMetadataValue(MetadataNamespaces.HTTP_STREAMING_METADATA, httpMetadata);

			if(alternateStreams && result is StreamingURLResource){
				(result as StreamingURLResource).alternativeAudioStreamItems = alternateStreams;
			}

			if(result is StreamingURLResource && StreamingURLResource(result).streamType == StreamType.DVR){
				var dvrMetadata:Metadata = new Metadata();
				result.addMetadataValue(MetadataNamespaces.DVR_METADATA, dvrMetadata);
			}

			dispatchEvent(new ParseEvent(ParseEvent.PARSE_COMPLETE, false, false, result));
		}
		/*
		private function addDVRInfo():void{

			CONFIG::LOGGING
			{
				logger.info('DVR!!! \\o/'); // we happy!
			}

			// black magic...
			var dvrInfo:DVRInfo = new DVRInfo();
			dvrInfo.id = dvrInfo.url = '';
			dvrInfo.isRecording = true; // if live then in process
			//dvrInfo.startTime = 0.0;
			// attach info into playlist
		}
		*/
		CONFIG::LOGGING
		{
			private var logger:Logger = Log.getLogger("org.denivip.osmf.elements.m3u8Classes.M3U8PlaylistParser");
		}
	}
}

Set initial stream to be played to first entry in M3U8 playlist

According to HLS especficiation we should play initially the first item
in the m3u8 playlist:
"The first entry in the variant playlist is played when a user joins
the stream and is used as part of a test to determine which stream is
most appropriate. The order of the other entries is irrelevant."
from:
https://developer.apple.com/library/mac/documentation/networkinginternet
/conceptual/streamingmediaguide/UsingHTTPLiveStreaming/UsingHTTPLiveStre
aming.html#//apple_ref/doc/uid/TP40008332-CH102-SW18


class elevator_frontDoorCon {
    Hub @hub;
    Entity @doorWithX;
    Entity @doorWithService;
    Entity @puzzleBoard;
    bool openDoor;
    vec3 tempPosWithX;
    vec3 tempPosWithService;
    float boardPitch;
    float speed;
    float uniformScale;

    elevator_frontDoorCon(Entity @entity){
        @hub = Managers();
        @doorWithX = GetEntityByGUID(1511870049);
        @doorWithService = GetEntityByGUID(1511870278);
        @puzzleBoard = GetEntityByGUID(1512029307);
        openDoor = false;
        speed = 0.5f;
        uniformScale = 0;

        // Remove this if updates are not desired.
        RegisterUpdate();
    }

    // Called by the engine for each frame.
    void Update(float deltaTime) {
        if(openDoor == true) {
            if(tempPosWithX.z < 2.0f) {
                tempPosWithX = doorWithX.GetWorldPosition();
                tempPosWithService = doorWithService.GetWorldPosition();

                tempPosWithX.z -= speed * deltaTime;
                tempPosWithService.z += speed * deltaTime;

                doorWithX.SetWorldPosition(tempPosWithX);
                doorWithService.SetWorldPosition(tempPosWithService);
            }

            uniformScale += (1.0f / 3.5f) * deltaTime;
            if (uniformScale > 1.0f) {
                uniformScale = 1.0f;
            }

            puzzleBoard.scale = vec3(uniformScale, uniformScale, uniformScale);

        }

        if(openDoor == false) {
            if(tempPosWithX.z > 0.0f) {
                tempPosWithX = doorWithX.GetWorldPosition();
                tempPosWithService = doorWithService.GetWorldPosition();

                tempPosWithX.z += speed * deltaTime;
                tempPosWithService.z -= speed * deltaTime;

                doorWithX.SetWorldPosition(tempPosWithX);
                doorWithService.SetWorldPosition(tempPosWithService);
            }
        }
    }

	void OpenDoor() {
		openDoor = true;
        doorWithX.GetSoundSource().Play();
        doorWithService.GetSoundSource().Play();
	}

	void CloseDoor() {
		openDoor = false;
	}
}

Replace tabs with spaces.

Replace tabs with spaces.


package aerys.minko.render.shader.part.phong.attenuation
{
	import aerys.minko.render.material.phong.PhongProperties;
	import aerys.minko.render.shader.SFloat;
	import aerys.minko.render.shader.Shader;
	import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
	import aerys.minko.render.shader.part.phong.depth.LinearDepthFromLightShaderPart;
	import aerys.minko.scene.node.light.PointLight;
	import aerys.minko.type.enum.SamplerDimension;
	import aerys.minko.type.enum.SamplerFiltering;
	import aerys.minko.type.enum.SamplerMipMapping;
	import aerys.minko.type.enum.SamplerWrapping;
	import aerys.minko.type.enum.ShadowMappingQuality;

	/**
	 * Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS
	 * Where m = max( | ∂z/∂x | , | ∂z/∂y | )
	 * ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf
	 *
	 * @author Romain Gilliotte
	 */
	public class PCFShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
	{
		private var _depthShaderPart	: LinearDepthFromLightShaderPart;
		public function PCFShadowMapAttenuationShaderPart(main : Shader)
		{
			super(main);
			_depthShaderPart = new LinearDepthFromLightShaderPart(main);
		}

		public function getAttenuation(lightId : uint) : SFloat
		{
			// retrieve shadow bias
			var shadowBias : SFloat;
			if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
				shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
			else
				shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1);

			// retrieve depthmap matrix
			var lightType			: uint		= getLightProperty(lightId, 'type');
			var depthMap	: SFloat = getLightTextureParameter(
				lightId,
				'shadowMap',
				SamplerFiltering.NEAREST,
				SamplerMipMapping.DISABLE,
				SamplerWrapping.CLAMP,
				lightType == PointLight.LIGHT_TYPE ? SamplerDimension.CUBE : SamplerDimension.FLAT
			);

			var fsWorldPosition 	: SFloat 	= interpolate(vsWorldPosition);
			var uv 					: SFloat 	= _depthShaderPart.getUV(lightId, fsWorldPosition);
			var currentDepth 		: SFloat 	= _depthShaderPart.getDepthForAttenuation(lightId, fsWorldPosition);
			var precomputedDepth	: SFloat 	= unpack(sampleTexture(depthMap, uv));
			var curDepthSubBias		: SFloat 	= min(subtract(1, shadowBias), currentDepth);
			var noShadows			: SFloat 	= lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));

			if (lightType == PointLight.LIGHT_TYPE)
				return noShadows;

			var quality				: uint		= getLightProperty(lightId, 'shadowQuality');
			if (quality != ShadowMappingQuality.HARD)
			{
				var invertSize	: SFloat			= divide(
					getLightParameter(lightId, 'shadowSpread', 1),
					getLightParameter(lightId, 'shadowMapSize', 1)
				);

				var uvs 		: Vector.<SFloat>	= new <SFloat>[];
				var uvDelta		: SFloat;

				if (quality > ShadowMappingQuality.LOW)
				{
					uvDelta = multiply(float3(-1, 0, 1), invertSize);
					uvs.push(
						add(uv.xyxy, uvDelta.xxxy),	// (-1, -1), (-1,  0)
						add(uv.xyxy, uvDelta.xzyx),	// (-1,  1), ( 0, -1)
						add(uv.xyxy, uvDelta.yzzx),	// ( 0,  1), ( 1, -1)
						add(uv.xyxy, uvDelta.zyzz)	// ( 1,  0), ( 1,  1)
					);
				}

				if (quality > ShadowMappingQuality.MEDIUM)
				{
					uvDelta = multiply(float3(-2, 0, 2), invertSize);
					uvs.push(
						add(uv.xyxy, uvDelta.xyyx),	// (-2, 0), (0, -2)
						add(uv.xyxy, uvDelta.yzzy)	// ( 0, 2), (2, 0)
					);
				}

				if (quality > ShadowMappingQuality.HARD)
				{
					uvDelta = multiply(float4(-2, -1, 1, 2), invertSize);
					uvs.push(
						add(uv.xyxy, uvDelta.xzyw),	// (-2,  1), (-1,  2)
						add(uv.xyxy, uvDelta.zwwz),	// ( 1,  2), ( 2,  1)
						add(uv.xyxy, uvDelta.wyzx),	// ( 2, -1), ( 1, -2)
						add(uv.xyxy, uvDelta.xyyx)	// (-2, -1), (-1, -2)
					);
				}

				var numSamples : uint = uvs.length;
				for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2)
				{
					precomputedDepth = float4(
						unpack(sampleTexture(depthMap, uvs[sampleId].xy)),
						unpack(sampleTexture(depthMap, uvs[sampleId].zw)),
						unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)),
						unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw))
					);

					var localNoShadows : SFloat = lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));
					noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1)));
				}

				noShadows.scaleBy(1 / (2 * numSamples + 1));
			}

			//return noShadows.x;

			var insideShadow 	: SFloat = multiply(multiply(lessThan(uv.x, 1), greaterThan(uv.x, 0)), multiply(lessThan(uv.y, 1), greaterThan(uv.y, 0)));
			var outsideShadow	: SFloat = subtract(1, insideShadow);

			return add(multiply(noShadows.x, insideShadow), outsideShadow);
		}
	}
}

package aerys.minko.render.shader.part.phong.attenuation
{
	import aerys.minko.render.material.phong.PhongProperties;
	import aerys.minko.render.shader.SFloat;
	import aerys.minko.render.shader.Shader;
	import aerys.minko.render.shader.part.phong.LightAwareShaderPart;
	import aerys.minko.render.shader.part.phong.depth.LinearDepthFromLightShaderPart;
	import aerys.minko.scene.node.light.PointLight;
	import aerys.minko.type.enum.SamplerDimension;
	import aerys.minko.type.enum.SamplerFiltering;
	import aerys.minko.type.enum.SamplerMipMapping;
	import aerys.minko.type.enum.SamplerWrapping;
	import aerys.minko.type.enum.ShadowMappingQuality;

	/**
	 * Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS
	 * Where m = max( | ∂z/∂x | , | ∂z/∂y | )
	 * ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf
	 *
	 * @author Romain Gilliotte
	 */
	public class PCFShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart
	{
		private var _depthShaderPart	: LinearDepthFromLightShaderPart;
		public function PCFShadowMapAttenuationShaderPart(main : Shader)
		{
			super(main);
			_depthShaderPart = new LinearDepthFromLightShaderPart(main);
		}

		public function getAttenuation(lightId : uint) : SFloat
		{
			// retrieve shadow bias
			var shadowBias : SFloat;
			if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS))
				shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1);
			else
				shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1);

			// retrieve depthmap matrix
			var lightType			: uint		= getLightProperty(lightId, 'type');
			var depthMap	: SFloat = getLightTextureParameter(
				lightId,
				'shadowMap',
				SamplerFiltering.NEAREST,
				SamplerMipMapping.DISABLE,
				SamplerWrapping.CLAMP,
				lightType == PointLight.LIGHT_TYPE ? SamplerDimension.CUBE : SamplerDimension.FLAT
			);

			var fsWorldPosition 	: SFloat 	= interpolate(vsWorldPosition);
			var uv 					: SFloat 	= _depthShaderPart.getUV(lightId, fsWorldPosition);
			var currentDepth 		: SFloat 	= _depthShaderPart.getDepthForAttenuation(lightId, fsWorldPosition);
			var precomputedDepth	: SFloat 	= unpack(sampleTexture(depthMap, uv));
			var curDepthSubBias		: SFloat 	= min(subtract(1, shadowBias), currentDepth);
			var noShadows			: SFloat 	= lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));

			if (lightType == PointLight.LIGHT_TYPE)
				return noShadows;

			var quality				: uint		= getLightProperty(lightId, 'shadowQuality');
			if (quality != ShadowMappingQuality.HARD)
			{
				var invertSize	: SFloat			= divide(
					getLightParameter(lightId, 'shadowSpread', 1),
					getLightParameter(lightId, 'shadowMapSize', 1)
				);

				var uvs 		: Vector.<SFloat>	= new <SFloat>[];
				var uvDelta		: SFloat;

				if (quality > ShadowMappingQuality.LOW)
				{
					uvDelta = multiply(float3(-1, 0, 1), invertSize);
					uvs.push(
						add(uv.xyxy, uvDelta.xxxy),	// (-1, -1), (-1,  0)
						add(uv.xyxy, uvDelta.xzyx),	// (-1,  1), ( 0, -1)
						add(uv.xyxy, uvDelta.yzzx),	// ( 0,  1), ( 1, -1)
						add(uv.xyxy, uvDelta.zyzz)	// ( 1,  0), ( 1,  1)
					);
				}

				if (quality > ShadowMappingQuality.MEDIUM)
				{
					uvDelta = multiply(float3(-2, 0, 2), invertSize);
					uvs.push(
						add(uv.xyxy, uvDelta.xyyx),	// (-2, 0), (0, -2)
						add(uv.xyxy, uvDelta.yzzy)	// ( 0, 2), (2, 0)
					);
				}

				if (quality > ShadowMappingQuality.HARD)
				{
					uvDelta = multiply(float4(-2, -1, 1, 2), invertSize);
					uvs.push(
						add(uv.xyxy, uvDelta.xzyw),	// (-2,  1), (-1,  2)
						add(uv.xyxy, uvDelta.zwwz),	// ( 1,  2), ( 2,  1)
						add(uv.xyxy, uvDelta.wyzx),	// ( 2, -1), ( 1, -2)
						add(uv.xyxy, uvDelta.xyyx)	// (-2, -1), (-1, -2)
					);
				}

				var numSamples : uint = uvs.length;
				for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2)
				{
					precomputedDepth = float4(
						unpack(sampleTexture(depthMap, uvs[sampleId].xy)),
						unpack(sampleTexture(depthMap, uvs[sampleId].zw)),
						unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)),
						unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw))
					);

					var localNoShadows : SFloat = lessEqual(curDepthSubBias, add(shadowBias, precomputedDepth));
					noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1)));
				}

				noShadows.scaleBy(1 / (2 * numSamples + 1));
			}

			var insideShadow 	: SFloat = multiply(multiply(lessThan(uv.x, 1), greaterThan(uv.x, 0)), multiply(lessThan(uv.y, 1), greaterThan(uv.y, 0)));
			var outsideShadow	: SFloat = subtract(1, insideShadow);

			return add(multiply(noShadows.x, insideShadow), outsideShadow);
		}
	}
}

Remove comments

Remove comments


#include "includes/idiomes.as"
//Segonquart Studio 2007. Steal it with respect , honey ;-)
//-------------------------------
//Imports
//-------------------------------
import System.Objects.*;
import flash.filters.GlowFilter;
import mx.transitions.easing.*;
import com.mosesSupposes.fuse.*;
//Thanks Moses...and respect ;-)
//-------------------------------
ZigoEngine.simpleSetup (Shortcuts, PennerEasing);
ZigoEngine.register (PennerEasing, Shortcuts, FuseFMP, FuseItem);
Stage.scaleMode = "noScale";
//-------------------------------
//Variables
//-------------------------------
var m03:MovieClip;
var o3:MovieClip;
var cp:TextField;
/*Form */
var formulari_mc:MovieClip;
/*Inputs Fields */
var cp:MovieClip;
/*Button */
var ok_mc:MovieClip;

var gf:GlowFilter = new GlowFilter (0xBEE47E, 100, 3, 3, 5, 3, false, false);

function initialState ():Void
{

	this.m03.alphaTo (100, 2.2, "easeOutBounce");
	this.m03._brightOffset = 100;
	this.m03.brightOffsetTo (0, 1, 'easeInBack', .2);
	this.m03.o3.tw.alphaTo (100, 2, "easeOutQuad", 2.3);
	this.m03.o3.tw._scale = 40;
	this.m03.o3.tw.scaleTo (100, 1, 'easeOutElastic');
	this.ok_mc._visible = true;
	this.ok_mc.filters = [gf];
	this.ok_mc._alphaTo (100, 1, "linear");
	this.ok_mc._scale = 20;
	this.ok_mc.scaleTo (25, 1, "easeInOutBounce");
}

function transformElementsUI ():Void{

		this.onRollOver = this.pOver;
		this.onRollOut = this.pOut;
		this.onPress =this.pPress;

}

function pPress():Void{
	ok_mc.fadeOut ();
	_parent.formulari_mc.slideTo (600, '0', "easeInOutBack");
	_parent.contact_txt._visible = false;
	_parent.mail_txt._visible = false;
};

function pOver():Void{

	addEventListener (this, "onPress");
	ok_mc.scaleTo (60, 2, 'easeOutBounce');

	ok_mc.onEnterFrame = function ():Void
	{
		if (gf.blurX < 20)
		{
			gf.blurX++;
			gf.blurY++;
		}
		else
		{
			delete this.onEnterFrame;
		}
		this.filters = [gf];
	};
};

function pOut():Void{
	ok_mc.onEnterFrame = function ()
	{
		this.filters = [gf];
		if (gf.blurX > 3)
		{
			gf.blurX--;
			gf.blurY--;
		}
		else
		{
			delete this.onEnterFrame;
		}
	};
};

initialState();
transformElementsUI();
stop();

Update frame2.as

Update frame2.as


/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 *   Marc Alcaraz <ekameleon@gmail.com>.
 */

package com.google.analytics.core
{

    /**
     * The domain name mode enumeration class.
     */
    public class DomainNameMode
    {
        /**
         * @private
         */
        private var _value:int;

        /**
         * @private
         */
        private var _name:String;

        /**
         * Creates a new DomainNameMode instance.
         * @param value The enumeration value representation.
         * @param name The enumeration name representation.
         */
        public function DomainNameMode( value:int = 0, name:String = "" )
        {
            _value = value;
            _name  = name;
        }

        /**
         * Returns the primitive value of the object.
         * @return the primitive value of the object.
         */
        public function valueOf():int
        {
            return _value;
        }

        /**
         * Returns the String representation of the object.
         * @return the String representation of the object.
         */
        public function toString():String
        {
            return _name;
        }

        /**
         * Determinates the "none" DomainNameMode value.
         *
"none" is used in the following two situations :

         *
- You want to disable tracking across hosts.

         *
- You want to set up tracking across two separate domains.

         *
Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.

         */
        public static const none:DomainNameMode    = new DomainNameMode( 0, "none" );

        /**
         * Attempts to automaticaly resolve the domain name.
         */
        public static const auto:DomainNameMode    = new DomainNameMode( 1, "auto" );

        /**
         * Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
         * and you want to track visitor behavior across all hosts.
         *
For example, if you have two hosts : server1.example.com and server2.example.com,
         * you would set the domain name as follows :
         *

         * pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
         *

         */
        public static const custom:DomainNameMode  = new DomainNameMode( 2, "custom" );

    }
}

fix asdoc comment again

fix asdoc comment again


////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.controllers
{
	import flash.display.DisplayObject;

	import org.apache.flex.core.IBead;
	import org.apache.flex.core.IDragInitiator;
	import org.apache.flex.core.IStrand;
    import org.apache.flex.core.IUIBase;
	import org.apache.flex.core.UIBase;
	import org.apache.flex.events.DragEvent;
	import org.apache.flex.events.EventDispatcher;
	import org.apache.flex.events.IEventDispatcher;
    import org.apache.flex.events.MouseEvent;

    /**
     *  Indicates that the mouse has entered the component during
     *  a drag operatino.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
    [Event(name="dragEnter", type="org.apache.flex.events.DragEvent")]

    /**
     *  Indicates that the mouse is moving over a component during
     *  a drag/drop operation.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
    [Event(name="dragOver", type="org.apache.flex.events.DragEvent")]

    /**
     *  Indicates that a drop operation should be executed.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
    [Event(name="dragDrop", type="org.apache.flex.events.DragEvent")]

	/**
	 *  The DropMouseController bead handles mouse events on the
	 *  a component, looking for events from a drag/drop operation.
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10.2
	 *  @playerversion AIR 2.6
	 *  @productversion FlexJS 0.0
	 */
	public class DropMouseController extends EventDispatcher implements IBead
	{
		/**
		 *  constructor.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function DropMouseController()
		{
		}

		private var _strand:IStrand;

		/**
		 *  @copy org.apache.flex.core.IBead#strand
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function set strand(value:IStrand):void
		{
			_strand = value;

            IEventDispatcher(_strand).addEventListener(DragEvent.DRAG_MOVE, dragMoveHandler);
		}

		public function get strand():IStrand
		{
			return _strand;
		}

        private var inside:Boolean;

        private var dragSource:Object;
        private var dragInitiator:IDragInitiator;

        public function acceptDragDrop(target:IUIBase, type:String):void
        {
            // TODO: aharui: switch icons
        }

        /**
         *  @private
         */
        private function dragMoveHandler(event:DragEvent):void
        {
            trace("dragMove");
            var dragEvent:DragEvent;
            if (!inside)
            {
                dragEvent = new DragEvent("dragEnter", true, true);
                dragEvent.copyMouseEventProperties(event);
                dragSource = dragEvent.dragSource = event.dragSource;
                dragInitiator = dragEvent.dragInitiator = event.dragInitiator;
                dispatchEvent(dragEvent);
                inside = true;
                DisplayObject(_strand).stage.addEventListener(DragEvent.DRAG_END, dragEndHandler);
                DisplayObject(_strand).addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
            }
            else
            {
                dragEvent = new DragEvent("dragOver", true, true);
                dragEvent.copyMouseEventProperties(event);
                dragEvent.dragSource = event.dragSource;
                dragEvent.dragInitiator = event.dragInitiator;
                IEventDispatcher(_strand).dispatchEvent(dragEvent);
            }
        }

        private function rollOutHandler(event:MouseEvent):void
        {
            var dragEvent:DragEvent;

            if (inside)
            {
                dragEvent = new DragEvent("dragExit", true, true);
                dragEvent.copyMouseEventProperties(event);
                dragEvent.dragSource = dragSource;
                dragEvent.dragInitiator = dragInitiator;
                dragSource = null;
                dragInitiator = null;
                event.stopImmediatePropagation();
                dispatchEvent(dragEvent);
                inside = false;
            }
            DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
            DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
        }

        private function dragEndHandler(event:DragEvent):void
        {
            trace("dragEnd");
            var dragEvent:DragEvent;

            dragEvent = new DragEvent("dragDrop", true, true);
            dragEvent.copyMouseEventProperties(event);
            dragEvent.dragSource = event.dragSource;
            dragEvent.dragInitiator = event.dragInitiator;
            dragSource = null;
            dragInitiator = null;
            event.stopImmediatePropagation();
            dispatchEvent(dragEvent);

            DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
            DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
        }

	}
}

////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.controllers
{
	import flash.display.DisplayObject;

	import org.apache.flex.core.IBead;
	import org.apache.flex.core.IDragInitiator;
	import org.apache.flex.core.IStrand;
    import org.apache.flex.core.IUIBase;
	import org.apache.flex.core.UIBase;
	import org.apache.flex.events.DragEvent;
	import org.apache.flex.events.EventDispatcher;
	import org.apache.flex.events.IEventDispatcher;
    import org.apache.flex.events.MouseEvent;

    /**
     *  Indicates that the mouse has entered the component during
     *  a drag operatino.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
    [Event(name="dragEnter", type="org.apache.flex.events.DragEvent")]

    /**
     *  Indicates that the mouse is moving over a component during
     *  a drag/drop operation.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
    [Event(name="dragOver", type="org.apache.flex.events.DragEvent")]

    /**
     *  Indicates that a drop operation should be executed.
     *
     *  @langversion 3.0
     *  @playerversion Flash 10.2
     *  @playerversion AIR 2.6
     *  @productversion FlexJS 0.0
     */
    [Event(name="dragDrop", type="org.apache.flex.events.DragEvent")]

	/**
	 *  The DropMouseController bead handles mouse events on the
	 *  a component, looking for events from a drag/drop operation.
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10.2
	 *  @playerversion AIR 2.6
	 *  @productversion FlexJS 0.0
	 */
	public class DropMouseController extends EventDispatcher implements IBead
	{
		/**
		 *  constructor.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function DropMouseController()
		{
		}

		private var _strand:IStrand;

		/**
		 *  @copy org.apache.flex.core.IBead#strand
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10.2
		 *  @playerversion AIR 2.6
		 *  @productversion FlexJS 0.0
		 */
		public function set strand(value:IStrand):void
		{
			_strand = value;

            IEventDispatcher(_strand).addEventListener(DragEvent.DRAG_MOVE, dragMoveHandler);
		}

		public function get strand():IStrand
		{
			return _strand;
		}

        private var inside:Boolean;

        private var dragSource:Object;
        private var dragInitiator:IDragInitiator;

        public function acceptDragDrop(target:IUIBase, type:String):void
        {
            // TODO: aharui: switch icons
        }

        /**
         *  @private
         */
        private function dragMoveHandler(event:DragEvent):void
        {
            trace("dragMove");
            var dragEvent:DragEvent;
            if (!inside)
            {
                dragEvent = new DragEvent("dragEnter", true, true);
                dragEvent.copyMouseEventProperties(event);
                dragSource = dragEvent.dragSource = event.dragSource;
                dragInitiator = dragEvent.dragInitiator = event.dragInitiator;
                dispatchEvent(dragEvent);
                inside = true;
                DisplayObject(_strand).stage.addEventListener(DragEvent.DRAG_END, dragEndHandler);
                DisplayObject(_strand).addEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
            }
            else
            {
                dragEvent = new DragEvent("dragOver", true, true);
                dragEvent.copyMouseEventProperties(event);
                dragEvent.dragSource = event.dragSource;
                dragEvent.dragInitiator = event.dragInitiator;
                IEventDispatcher(_strand).dispatchEvent(dragEvent);
            }
        }

        private function rollOutHandler(event:MouseEvent):void
        {
            var dragEvent:DragEvent;

            if (inside)
            {
                dragEvent = new DragEvent("dragExit", true, true);
                dragEvent.copyMouseEventProperties(event);
                dragEvent.dragSource = dragSource;
                dragEvent.dragInitiator = dragInitiator;
                dragSource = null;
                dragInitiator = null;
                event.stopImmediatePropagation();
                dispatchEvent(dragEvent);
                inside = false;
            }
            DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
            DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
        }

        private function dragEndHandler(event:DragEvent):void
        {
            trace("dragEnd");
            var dragEvent:DragEvent;

            dragEvent = new DragEvent("dragDrop", true, true);
            dragEvent.copyMouseEventProperties(event);
            dragEvent.dragSource = event.dragSource;
            dragEvent.dragInitiator = event.dragInitiator;
            dragSource = null;
            dragInitiator = null;
            event.stopImmediatePropagation();
            dispatchEvent(dragEvent);

            inside = false;
            DisplayObject(_strand).stage.removeEventListener(DragEvent.DRAG_END, dragEndHandler);
            DisplayObject(_strand).removeEventListener(MouseEvent.ROLL_OUT, rollOutHandler);
        }

	}
}

reset vars after drop

reset vars after drop


package org.mangui.HLS.utils {
  import com.hurlant.crypto.symmetric.CBCMode;
  import com.hurlant.crypto.symmetric.ICipher;
  import com.hurlant.crypto.symmetric.IPad;
  import com.hurlant.crypto.symmetric.IVMode;
  import com.hurlant.crypto.symmetric.NullPad;
  import com.hurlant.crypto.symmetric.PKCS5;

  import flash.utils.ByteArray;
  import flash.utils.Timer;
  import flash.events.Event;
  import flash.events.TimerEvent;

  /**
   * Contains Utility functions for Decryption
   */
  public class AES
  {
    private var _key:FastAESKey;
    private var _mode:ICipher;
    private var _iv:ByteArray;
    /* callback function upon read complete */
    private var _callback:Function;
    /** Timer for decrypting packets **/
    private var _timer:Timer;
    /** Byte data to be decrypt **/
    private var _data:ByteArray;
    /** Byte data to be decrypt **/
    private var _decrypteddata:ByteArray;
    /** read position **/
    private var _read_position:Number;
    /** chunk size to avoid blocking **/
    private static const CHUNK_SIZE:uint = 2048;
    /** is bytearray full ? **/
    private var _data_complete:Boolean;

    public function AES(key:ByteArray,iv:ByteArray) {
      var pad:IPad = new PKCS5;
      _key = new FastAESKey(key);
      _mode = new CBCMode(_key, pad);
      pad.setBlockSize(_mode.getBlockSize());
      _iv = iv;
      if (_mode is IVMode) {
        var ivmode:IVMode = _mode as IVMode;
        ivmode.IV = iv;
      }
    }

    public function decrypt(data:ByteArray,callback:Function):void {
      Log.debug("AES:async decrypt starting");
      _data = data;
      _data_complete = false;
      _callback = callback;
      _decrypteddata = new ByteArray();
      _read_position = 0;
      _timer = new Timer(0,0);
      _timer.addEventListener(TimerEvent.TIMER, _decryptTimer);
      _timer.start();
    }

    public function notifyappend():void {
      //Log.info("notify append");
      _timer.start();
    }

    public function notifycomplete():void {
      //Log.info("notify complete");
      _data_complete = true;
      _timer.start();
    }

    public function cancel():void {
      if(_timer) {
        _timer.stop();
        _timer = null;
      }
    }

    private function _decryptTimer(e:Event):void {
      var start_time:Number = new Date().getTime();
      do {
         _decryptData();
      // dont spend more than 20 ms in the decrypt timer to avoid blocking/freezing video
      } while (_timer.running && new Date().getTime() - start_time < 20);
    }

    /** decrypt a small chunk of packets each time to avoid blocking **/
    private function _decryptData():void {
      _data.position = _read_position;
      if(_data.bytesAvailable) {
        var dumpByteArray:ByteArray = new ByteArray();
        var newIv:ByteArray;
        var pad:IPad;
        if(_data.bytesAvailable <= CHUNK_SIZE) {
          if (_data_complete) {
            //Log.info("data complete, last chunk");
            pad = new PKCS5;
            _read_position+=_data.bytesAvailable;
            _data.readBytes(dumpByteArray,0,_data.bytesAvailable);
          } else {
            //Log.info("data not complete, stop timer");
            // data not complete, and available data less than chunk size, stop timer and return
            _timer.stop();
            return;
          }
        } else { // bytesAvailable > CHUNK_SIZE
          //Log.info("process chunk");
          pad = new NullPad;
          _read_position+=CHUNK_SIZE;
          _data.readBytes(dumpByteArray,0,CHUNK_SIZE);
          // Save new IV from ciphertext
          newIv = new ByteArray();
          dumpByteArray.position = (CHUNK_SIZE-16);
          dumpByteArray.readBytes(newIv, 0, 16);
        }
        dumpByteArray.position = 0;
        //Log.info("before decrypt");
        _mode = new CBCMode(_key, pad);
        pad.setBlockSize(_mode.getBlockSize());
        (_mode as IVMode).IV = _iv;
        _mode.decrypt(dumpByteArray);
        //Log.info("after decrypt");
        _decrypteddata.writeBytes(dumpByteArray);

        // switch IV to new one in case more bytes are available
        if(newIv) {
          _iv = newIv;
        }
      } else {
        //Log.info("no bytes available, stop timer");
        _timer.stop();
        if (_data_complete) {
          Log.debug("AES:data+decrypt completed, callback");
          // callback
          _decrypteddata.position=0;
          _callback(_decrypteddata);
        }
      }
    }

    public function destroy():void {
      _key.dispose();
      //_key = null;
      _mode = null;
    }
  }
}

package org.mangui.HLS.utils {
  import com.hurlant.crypto.symmetric.CBCMode;
  import com.hurlant.crypto.symmetric.ICipher;
  import com.hurlant.crypto.symmetric.IPad;
  import com.hurlant.crypto.symmetric.IVMode;
  import com.hurlant.crypto.symmetric.NullPad;
  import com.hurlant.crypto.symmetric.PKCS5;

  import flash.utils.ByteArray;
  import flash.utils.Timer;
  import flash.events.Event;
  import flash.events.TimerEvent;

  /**
   * Contains Utility functions for Decryption
   */
  public class AES
  {
    private var _key:FastAESKey;
    private var _mode:ICipher;
    private var _iv:ByteArray;
    /* callback function upon read complete */
    private var _callback:Function;
    /** Timer for decrypting packets **/
    private var _timer:Timer;
    /** Byte data to be decrypt **/
    private var _data:ByteArray;
    /** Byte data to be decrypt **/
    private var _decrypteddata:ByteArray;
    /** read position **/
    private var _read_position:uint;
    /** chunk size to avoid blocking **/
    private static const CHUNK_SIZE:uint = 2048;
    /** is bytearray full ? **/
    private var _data_complete:Boolean;

    public function AES(key:ByteArray,iv:ByteArray) {
      var pad:IPad = new PKCS5;
      _key = new FastAESKey(key);
      _mode = new CBCMode(_key, pad);
      pad.setBlockSize(_mode.getBlockSize());
      _iv = iv;
      if (_mode is IVMode) {
        var ivmode:IVMode = _mode as IVMode;
        ivmode.IV = iv;
      }
    }

    public function decrypt(data:ByteArray,callback:Function):void {
      Log.debug("AES:async decrypt starting");
      _data = data;
      _data_complete = false;
      _callback = callback;
      _decrypteddata = new ByteArray();
      _read_position = 0;
      _timer = new Timer(0,0);
      _timer.addEventListener(TimerEvent.TIMER, _decryptTimer);
      _timer.start();
    }

    public function notifyappend():void {
      //Log.info("notify append");
      _timer.start();
    }

    public function notifycomplete():void {
      //Log.info("notify complete");
      _data_complete = true;
      _timer.start();
    }

    public function cancel():void {
      if(_timer) {
        _timer.stop();
        _timer = null;
      }
    }

    private function _decryptTimer(e:Event):void {
      var start_time:Number = new Date().getTime();
      do {
         _decryptData();
      // dont spend more than 20 ms in the decrypt timer to avoid blocking/freezing video
      } while (_timer.running && new Date().getTime() - start_time < 20);
    }

    /** decrypt a small chunk of packets each time to avoid blocking **/
    private function _decryptData():void {
      _data.position = _read_position;
      if(_data.bytesAvailable) {
        var dumpByteArray:ByteArray = new ByteArray();
        var newIv:ByteArray;
        var pad:IPad;
        if(_data.bytesAvailable <= CHUNK_SIZE) {
          if (_data_complete) {
            //Log.info("data complete, last chunk");
            pad = new PKCS5;
            _read_position+=_data.bytesAvailable;
            _data.readBytes(dumpByteArray,0,_data.bytesAvailable);
          } else {
            //Log.info("data not complete, stop timer");
            // data not complete, and available data less than chunk size, stop timer and return
            _timer.stop();
            return;
          }
        } else { // bytesAvailable > CHUNK_SIZE
          //Log.info("process chunk");
          pad = new NullPad;
          _read_position+=CHUNK_SIZE;
          _data.readBytes(dumpByteArray,0,CHUNK_SIZE);
          // Save new IV from ciphertext
          newIv = new ByteArray();
          dumpByteArray.position = (CHUNK_SIZE-16);
          dumpByteArray.readBytes(newIv, 0, 16);
        }
        dumpByteArray.position = 0;
        //Log.info("before decrypt");
        _mode = new CBCMode(_key, pad);
        pad.setBlockSize(_mode.getBlockSize());
        (_mode as IVMode).IV = _iv;
        _mode.decrypt(dumpByteArray);
        //Log.info("after decrypt");
        _decrypteddata.writeBytes(dumpByteArray);

        // switch IV to new one in case more bytes are available
        if(newIv) {
          _iv = newIv;
        }
      } else {
        //Log.info("no bytes available, stop timer");
        _timer.stop();
        if (_data_complete) {
          Log.debug("AES:data+decrypt completed, callback");
          // callback
          _decrypteddata.position=0;
          _callback(_decrypteddata);
        }
      }
    }

    public function destroy():void {
      _key.dispose();
      //_key = null;
      _mode = null;
    }
  }
}

switch to uint

switch to uint