CombinedText stringlengths 4 3.42M |
|---|
package ru.kokorin.astream.converter {
import flash.geom.Point;
public class PointConverter implements Converter {
public function fromString(string:String):Object {
const coordinates:Array = string.split(",");
const result:Point = new Point();
result.x = parseFloat(String(coordinates[0]));
result.y = parseFloat(String(coordinates[1]));
return result;
}
public function toString(value:Object):String {
const point:Point = value as Point;
return point.x + "," + point.y;
}
}
}
|
package kabam.rotmg.ui.controller {
import com.company.assembleegameclient.map.partyoverlay.GameObjectArrow;
import kabam.rotmg.core.view.Layers;
import robotlegs.bender.bundles.mvcs.Mediator;
public class GameObjectArrowMediator extends Mediator {
public function GameObjectArrowMediator() {
super();
}
[Inject]
public var view:GameObjectArrow;
[Inject]
public var layers:Layers;
override public function initialize():void {
this.view.menuLayer = this.layers.top;
}
}
}
|
package tetragon.core.au.events
{
import flash.events.Event;
/**
* A UpdateEvent is dispatched by a ApplicationUpdater object during the update process.
*/
public class AUUpdateEvent extends Event
{
/**
* The <code>UpdateEvent.INITIALIZED</code> constant defines the value of the
* <code>type</code> property of the event object for a <code>initialized</code> event.
*/
public static const INITIALIZED:String = "initialized";
/**
* The <code>UpdateEvent.BEFORE_INSTALL</code> constant defines the value of the
* <code>type</code> property of the event object for a <code>beforeInstall</code> event.
*/
public static const BEFORE_INSTALL:String = "beforeInstall";
/**
* The <code>UpdateEvent.CHECK_FOR_UPDATE</code> constant defines the value of the
* <code>type</code> property of the event object for a <code>checkForUpdate</code> event.
*/
public static const CHECK_FOR_UPDATE:String = "checkForUpdate";
/**
* The <code>UpdateEvent.DOWNLOAD_START</code> constant defines the value of the
* <code>type</code> property of the event object for a <code>downloadStart</code> event.
*/
public static const DOWNLOAD_START:String = "downloadStart";
/**
* The <code>UpdateEvent.DOWNLOAD_COMPLETE</code> constant defines the value of the
* <code>type</code> property of the event object for a <code>downloadComplete</code> event.
*/
public static const DOWNLOAD_COMPLETE:String = "downloadComplete";
public function AUUpdateEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
/**
* @inheritDoc
*/
override public function clone():Event
{
return new AUUpdateEvent(type, bubbles, cancelable);
}
/**
* @inheritDoc
*/
override public function toString():String
{
return "[UpdateEvent (type=" + type + ")]";
}
}
}
|
/**
* User: booster
* Date: 11/16/12
* Time: 20:59
*/
package medkit.collection {
import medkit.collection.error.ConcurrentModificationError;
import medkit.collection.iterator.ListIterator;
public class ArrayListListItr extends ArrayListItr implements ListIterator {
public function ArrayListListItr(list:ArrayList, index:int) {
super (list);
cursor = index;
}
public function hasPrevious():Boolean {
return cursor != 0;
}
public function nextIndex():int {
return cursor;
}
public function previousIndex():int {
return cursor - 1;
}
public function previous():* {
checkForCoModification();
var i:int = cursor - 1;
if (i < 0)
throw new RangeError("Iterating before first element of this iteration");
if (i >= list.elementData.length)
throw new ConcurrentModificationError();
cursor = i;
return list.elementData[lastRet = i];
}
public function set(e:*):void {
if (lastRet < 0)
throw new UninitializedError();
checkForCoModification();
try {
list.set(lastRet, e);
}
catch (e:RangeError) {
throw new ConcurrentModificationError();
}
}
public function add(e:*):void {
checkForCoModification();
try {
var i:int = cursor;
list.addAt(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = list.modCount;
}
catch (e:RangeError) {
throw new ConcurrentModificationError();
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
/*
classes that won't be detected through dependencies
* and root classes that needs to be includes in ASDOC
* */
internal class ExperimentalMobileClasses
{
import spark.components.MobileGrid; MobileGrid;
import spark.components.supportClasses.MobileGridColumn; MobileGridColumn;
import spark.skins.MobileGridHeaderButtonBarSkin; MobileGridHeaderButtonBarSkin;
import spark.skins.MobileGridSkin; MobileGridSkin;
}
}
|
package com.ankamagames.berilia.components.gridRenderer
{
import com.ankamagames.berilia.components.Label;
import com.ankamagames.berilia.components.MultipleComboBoxGrid;
import com.ankamagames.berilia.components.Texture;
import com.ankamagames.berilia.types.graphic.GraphicContainer;
import com.ankamagames.berilia.types.graphic.UiRootContainer;
import com.ankamagames.jerakine.data.XmlConfig;
import com.ankamagames.jerakine.types.Uri;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.utils.Dictionary;
public class MultipleComboBoxRenderer extends XmlUiGridRenderer
{
public var multiGrid:MultipleComboBoxGrid;
public var mainContainer:GraphicContainer;
public var placeholder:String = null;
private const LEFT_PADDING:Number = 10;
private const RIGHT_PADDING:Number = 40;
private const ICON_HORIZONTAL_PADDING:Number = 2;
private const ICON_VERTICAL_PADDING:Number = 5;
private const ITEM_PADDING:Number = 5;
private const MIN_LABEL_WIDTH:Number = 7;
private const HIDDEN_TEXT:String = "...";
private const LABEL_KEY_PREFIX:String = "lbl_";
private const TEXTURE_KEY_PREFIX:String = "tx_";
private const PLACEHOLDER_KEY:String = "lbl_placeholder";
private var _loadingIconsNb:Number = 0;
private var _labelCssUri:Uri;
private var _cachedElements:Dictionary;
public function MultipleComboBoxRenderer(strParams:String)
{
this._labelCssUri = new Uri(XmlConfig.getInstance().getEntry("config.ui.skin") + "css/small2.css");
this._cachedElements = new Dictionary();
super(strParams);
}
private static function sortItems(obj1:Object, obj2:Object) : Number
{
var sortValue1:* = undefined;
var sortValue2:* = undefined;
if(obj1.hasOwnProperty("order") && obj2.hasOwnProperty("order"))
{
sortValue1 = obj1.order;
sortValue2 = obj2.order;
}
else
{
sortValue1 = obj1.typeId;
sortValue2 = obj1.typeId;
}
if(sortValue1 > sortValue2)
{
return 1;
}
if(sortValue2 > sortValue1)
{
return -1;
}
return 0;
}
public function initialize() : void
{
var label:Label = new Label();
label.css = this._labelCssUri;
label.useTooltipExtension = false;
label.finalize();
this.mainContainer.addChild(label);
this._cachedElements[this.PLACEHOLDER_KEY] = label;
}
override public function update(data:*, index:uint, dispObj:DisplayObject, isSelected:Boolean, subIndex:uint = 0) : void
{
if(!(dispObj is UiRootContainer))
{
if(!(dispObj is GraphicContainer))
{
_log.warn("Can\'t update, " + dispObj.name + " is not a proper component");
return;
}
this.updateContainer();
return;
}
super.update(data,index,dispObj,isSelected,subIndex);
}
override public function destroy() : void
{
var element:GraphicContainer = null;
for each(element in this._cachedElements)
{
element.remove();
}
this._cachedElements = null;
super.destroy();
}
private function updateContainer() : void
{
var element:GraphicContainer = null;
var value:Object = null;
var label:Label = null;
var texture:Texture = null;
var labelKey:String = null;
var textureKey:String = null;
var values:Array = this.multiGrid.selectedValues;
for each(element in this._cachedElements)
{
element.visible = false;
}
if(values === null || values.length <= 0)
{
this.setElements();
return;
}
values = values.concat();
values.sort(sortItems);
var valuesNb:uint = values.length;
for(var index:uint = 0; index < valuesNb; index++)
{
value = values[index];
label = null;
texture = null;
labelKey = this.LABEL_KEY_PREFIX + value.typeId;
textureKey = this.TEXTURE_KEY_PREFIX + value.typeId;
if(!(labelKey in this._cachedElements))
{
label = new Label();
label.css = this._labelCssUri;
label.useTooltipExtension = false;
label.finalize();
this.mainContainer.addChild(label);
this._cachedElements[labelKey] = label;
}
else
{
label = this._cachedElements[labelKey];
}
label.text = index === valuesNb - 1 ? value.label : value.label + ", ";
label.fullWidth();
if(value.hasOwnProperty("icon") && value.icon !== null)
{
if(!(textureKey in this._cachedElements))
{
texture = new Texture();
texture.keepRatio = true;
texture.finalize();
texture.height = this.mainContainer.height - this.ICON_VERTICAL_PADDING;
texture.addEventListener(Event.COMPLETE,this.onIconLoaded);
this.mainContainer.addChild(texture);
this._cachedElements[textureKey] = texture;
}
else
{
texture = this._cachedElements[textureKey];
}
if(texture.uri !== value.icon)
{
++this._loadingIconsNb;
texture.uri = value.icon;
}
}
}
if(this._loadingIconsNb <= 0)
{
this.setElements();
}
}
private function setElements() : void
{
var element:GraphicContainer = null;
var placeholderLabel:Label = null;
var parent:DisplayObjectContainer = null;
var value:Object = null;
var texture:Texture = null;
var label:Label = null;
var offsetX:Number = NaN;
var values:Array = this.multiGrid.selectedValues.concat();
for each(element in this._cachedElements)
{
element.visible = false;
}
placeholderLabel = this._cachedElements[this.PLACEHOLDER_KEY];
placeholderLabel.visible = true;
parent = this.mainContainer.parent;
placeholderLabel.width = parent.width - placeholderLabel.x - this.RIGHT_PADDING;
if(values === null || values.length <= 0)
{
placeholderLabel.text = this.placeholder;
placeholderLabel.x = this.LEFT_PADDING;
placeholderLabel.y = parent.y + parent.height / 2 - placeholderLabel.height / 2;
return;
}
placeholderLabel.text = null;
values.sort(sortItems);
var previousLabel:Label = null;
var maxX:Number = parent.width - this.RIGHT_PADDING - this.MIN_LABEL_WIDTH;
for each(value in values)
{
label = null;
if(value.hasOwnProperty("icon") && value.icon !== null)
{
texture = this._cachedElements[this.TEXTURE_KEY_PREFIX + value.typeId];
}
else
{
texture = null;
}
label = this._cachedElements[this.LABEL_KEY_PREFIX + value.typeId];
offsetX = previousLabel !== null ? Number(previousLabel.x + previousLabel.width + this.ITEM_PADDING) : Number(this.LEFT_PADDING);
if(texture !== null)
{
texture.visible = true;
texture.x = offsetX;
texture.y = parent.y + parent.height / 2 - texture.height / 2;
label.x = texture.x + texture.width + this.ICON_HORIZONTAL_PADDING;
}
else
{
label.x = offsetX;
}
label.visible = true;
label.y = parent.y + parent.height / 2 - label.height / 2;
if(label.x + label.width > maxX || texture !== null && texture.x + texture.width > maxX)
{
label.width = Math.max(maxX - label.x,this.MIN_LABEL_WIDTH);
if(label.width <= this.MIN_LABEL_WIDTH && texture !== null)
{
label.text = this.HIDDEN_TEXT;
if(texture !== null)
{
texture.visible = false;
label.x = texture.x;
label.width = this.MIN_LABEL_WIDTH;
}
}
return;
}
previousLabel = label;
}
}
private function onIconLoaded(event:Event) : void
{
event.target.removeEventListener(Event.COMPLETE,this.onIconLoaded);
--this._loadingIconsNb;
if(this._loadingIconsNb > 0)
{
return;
}
this._loadingIconsNb = 0;
this.setElements();
}
}
}
|
/*******************************************************************************
* PushButton Engine
* Copyright (C) 2009 PushButton Labs, LLC
* For more information see http://www.pushbuttonengine.com
*
* This file is licensed under the terms of the MIT license, which is included
* in the License.html file at the root directory of this SDK.
******************************************************************************/
package com.pblabs.engine
{
import com.pblabs.engine.debug.Logger;
import flash.display.DisplayObject;
import flash.geom.Matrix;
/**
* Contains math related utility methods.
*/
public class PBUtil
{
public static const FLIP_HORIZONTAL:String = "flipHorizontal";
public static const FLIP_VERTICAL:String = "flipVertical";
/**
* Two times PI.
*/
public static const TWO_PI:Number = 2.0 * Math.PI;
/**
* Converts an angle in radians to an angle in degrees.
*
* @param radians The angle to convert.
*
* @return The converted value.
*/
public static function getDegreesFromRadians(radians:Number):Number
{
return radians * 180 / Math.PI;
}
/**
* Converts an angle in degrees to an angle in radians.
*
* @param degrees The angle to convert.
*
* @return The converted value.
*/
public static function getRadiansFromDegrees(degrees:Number):Number
{
return degrees * Math.PI / 180;
}
/**
* Keep a number between a min and a max.
*/
public static function clamp(v:Number, min:Number = 0, max:Number = 1):Number
{
if(v < min) return min;
if(v > max) return max;
return v;
}
/**
* Clones an array.
* @param array Array to clone.
* @return a cloned array.
*/
public static function cloneArray(array:Array):Array
{
var newArray:Array = [];
for each (var item:* in array)
newArray.push(item);
return newArray;
}
/**
* Take a radian measure and make sure it is between -pi..pi.
*/
public static function unwrapRadian(r:Number):Number
{
r = r % TWO_PI;
if (r > Math.PI)
r -= TWO_PI;
if (r < -Math.PI)
r += TWO_PI;
return r;
}
/**
* Take a degree measure and make sure it is between -180..180.
*/
public static function unwrapDegrees(r:Number):Number
{
r = r % 360;
if (r > 180)
r -= 360;
if (r < -180)
r += 360;
return r;
}
/**
* Return the shortest distance to get from from to to, in radians.
*/
public static function getRadianShortDelta(from:Number, to:Number):Number
{
// Unwrap both from and to.
from = unwrapRadian(from);
to = unwrapRadian(to);
// Calc delta.
var delta:Number = to - from;
// Make sure delta is shortest path around circle.
if(delta > Math.PI)
delta -= TWO_PI;
if(delta < -Math.PI)
delta += TWO_PI;
// Done
return delta;
}
/**
* Return the shortest distance to get from from to to, in degrees.
*/
public static function getDegreesShortDelta(from:Number, to:Number):Number
{
// Unwrap both from and to.
from = unwrapDegrees(from);
to = unwrapDegrees(to);
// Calc delta.
var delta:Number = to - from;
// Make sure delta is shortest path around circle.
if(delta > 180)
delta -= 360;
if(delta < -180)
delta += 360;
// Done
return delta;
}
/**
* Get number of bits required to encode values from 0..max.
*
* @param max The maximum value to be able to be encoded.
* @return Bitcount required to encode max value.
*/
public static function getBitCountForRange(max:int):int
{
var count:int = 0;
// Unfortunately this is a bug with this method... and requires this special
// case (same issue with the old method log calculation)
if (max == 1) return 1;
max--;
while (max >> count > 0) count++;
return count;
}
/**
* Pick an integer in a range, with a bias factor (from -1 to 1) to skew towards
* low or high end of range.
*
* @param min Minimum value to choose from, inclusive.
* @param max Maximum value to choose from, inclusive.
* @param bias -1 skews totally towards min, 1 totally towards max.
* @return A random integer between min/max with appropriate bias.
*
*/
public static function pickWithBias(min:int, max:int, bias:Number = 0):int
{
return clamp((((Math.random() + bias) * (max - min)) + min), min, max);
}
/**
* Assigns parameters from source to destination by name.
*
* <p>This allows duck typing - you can accept a generic object
* (giving you nice {foo:bar} syntax) and cast to a typed object for
* easier internal processing and validation.</p>
*
* @param source Object to read fields from.
* @param destination Object to assign fields to.
* @param abortOnMismatch If true, throw an error if a field in source is absent in destination.
*
*/
public static function duckAssign(source:Object, destination:Object, abortOnMismatch:Boolean = false):void
{
for(var field:String in source)
{
try
{
// Try to assign.
destination[field] = source[field];
}
catch(e:Error)
{
// Abort or continue, depending on user settings.
if(!abortOnMismatch)
continue;
throw new Error("Field '" + field + "' in source was not present in destination.");
}
}
}
/**
* Calculate length of a vector.
*/
public static function xyLength(x:Number, y:Number):Number
{
return Math.sqrt((x*x)+(y*y));
}
/**
* Replaces instances of less then, greater then, ampersand, single and double quotes.
* @param str String to escape.
* @return A string that can be used in an htmlText property.
*/
public static function escapeHTMLText(str:String):String
{
var chars:Array =
[
{char:"&", repl:"|amp|"},
{char:"<", repl:"<"},
{char:">", repl:">"},
{char:"\'", repl:"'"},
{char:"\"", repl:"""},
{char:"|amp|", repl:"&"}
];
for(var i:int=0; i < chars.length; i++)
{
while(str.indexOf(chars[i].char) != -1)
{
str = str.replace(chars[i].char, chars[i].repl);
}
}
return str;
}
/**
* Converts a String to a Boolean. This method is case insensitive, and will convert
* "true", "t" and "1" to true. It converts "false", "f" and "0" to false.
* @param str String to covert into a boolean.
* @return true or false
*/
public static function stringToBoolean(str:String):Boolean
{
switch(str.substring(1, 0).toUpperCase())
{
case "F":
case "0":
return false;
break;
case "T":
case "1":
return true;
break;
}
return false;
}
/**
* Capitalize the first letter of a string
* @param str String to capitalize the first leter of
* @return String with the first letter capitalized.
*/
public static function capitalize(str:String):String
{
return str.substring(1, 0).toUpperCase() + str.substring(1);
}
/**
* Removes all instances of the specified character from
* the beginning and end of the specified string.
*/
public static function trim(str:String, char:String):String {
return trimBack(trimFront(str, char), char);
}
/**
* Recursively removes all characters that match the char parameter,
* starting from the front of the string and working toward the end,
* until the first character in the string does not match char and returns
* the updated string.
*/
public static function trimFront(str:String, char:String):String
{
char = stringToCharacter(char);
if (str.charAt(0) == char) {
str = trimFront(str.substring(1), char);
}
return str;
}
/**
* Recursively removes all characters that match the char parameter,
* starting from the end of the string and working backward,
* until the last character in the string does not match char and returns
* the updated string.
*/
public static function trimBack(str:String, char:String):String
{
char = stringToCharacter(char);
if (str.charAt(str.length - 1) == char) {
str = trimBack(str.substring(0, str.length - 1), char);
}
return str;
}
/**
* Returns the first character of the string passed to it.
*/
public static function stringToCharacter(str:String):String
{
if (str.length == 1) {
return str;
}
return str.slice(0, 1);
}
/**
* Determine the file extension of a file.
* @param file A path to a file.
* @return The file extension.
*
*/
public static function getFileExtension(file:String):String
{
var extensionIndex:Number = file.lastIndexOf(".");
if (extensionIndex == -1) {
//No extension
return "";
} else {
return file.substr(extensionIndex + 1,file.length);
}
}
/**
* Method for flipping a DisplayObject
* @param obj DisplayObject to flip
* @param orientation Which orientation to use: PBUtil.FLIP_HORIZONTAL or PBUtil.FLIP_VERTICAL
*
*/
public static function flipDisplayObject(obj:DisplayObject, orientation:String):void
{
var m:Matrix = obj.transform.matrix;
switch (orientation)
{
case FLIP_HORIZONTAL:
m.a = -1 * m.a;
m.tx = obj.width + obj.x;
break;
case FLIP_VERTICAL:
m.d = -1 * m.d;
m.ty = obj.height + obj.y;
break;
}
obj.transform.matrix = m;
}
/**
* Log an object to the console. Based on http://dev.base86.com/solo/47/actionscript_3_equivalent_of_phps_printr.html
* @param thisObject Object to display for logging.
* @param obj Object to dump.
*/
public static function dumpObjectToLogger(thisObject:*, obj:*, level:int = 0, output:String = ""):String
{
var tabs:String = "";
for(var i:int = 0; i < level; i++) tabs += "\t";
for(var child:* in obj) {
output += tabs +"["+ child +"] => "+ obj[child];
var childOutput:String = dumpObjectToLogger(thisObject, obj[child], level+1);
if(childOutput != '') output += ' {\n'+ childOutput + tabs +'}';
output += "\n";
}
if(level == 0)
{
Logger.print(thisObject, output);
return "";
}
return output;
}
}
}
|
package
{
import flash.display.Sprite;
import net.profusiondev.graphics.SpriteSheetAnimation;
/**
* ...
* @author UnknownGuardian
*/
public class Crystal extends SpriteSheetAnimation
{
private var distanceToTrigger:int = 20;
public function Crystal()
{
super(Content.crystal, 50, 50, 40, true, false);
getChildAt(0).x = -width / 2;
getChildAt(0).y = -height / 2;
}
public function bothOnCrystal(g:Gurin, m:Malon):Boolean
{
return g.hitTestObject(m) && g.hitTestObject(this) && hitTestObject(m);// < distanceToTrigger//(hit(g, m) && hit(m, this) && hit(g, this));
}
public function hit(obj:Sprite, other:Sprite):Boolean
{
trace(Math.abs(obj.x - other.x), Math.abs(obj.y - other.y));
return (Math.abs(obj.x - other.x) < distanceToTrigger && Math.abs(obj.y - other.y) < distanceToTrigger);
}
}
} |
package
{
import net.manaca.itunesGallery.iTunesGallery;
import net.manaca.logging.publishers.Output;
[SWF(width='1200', height='600',frameRate='24', backgroundColor='#000000')]
public class iTunesGalleryDemo extends iTunesGallery
{
public function iTunesGalleryDemo()
{
var output:Output = new Output(150, true);
this.stage.addChild(output);
this.stage.removeChild(output);
super();
}
}
}
|
/*
CASA Lib for ActionScript 3.0
Copyright (c) 2011, Aaron Clinger & Contributors of CASA Lib
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the CASA Lib nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.casalib.util {
import flash.display.Graphics;
import flash.geom.Point;
import flash.geom.Rectangle;
import org.casalib.errors.ArrayContentsError;
import org.casalib.math.geom.Ellipse;
/**
Utilities for drawing shapes.
@author Aaron Clinger
@author Jon Adams
@version 09/22/10
*/
public class DrawUtil {
/**
Draws a path through the defined points.
@param graphics: The location where drawing should occur.
@param points: An Array comprised of at least two <code>Point</code>s to be use to draw a path.
@throws ArrayContentsError if the Array is comprised of elements other than <code>Point</code> objects.
@throws <code>Error</code> if the Array has less than two <code>Point</code>s.
@example
<code>
this.graphics.lineStyle(4, 0x00FF00);
DrawUtil.drawPath(this.graphics, new Array(new Point(50, 25), new Point(25, 50), new Point(50, 75), new Point(25, 100)));
this.graphics.endFill();
</code>
*/
public static function drawPath(graphics:Graphics, points:Array):void {
var i:uint = points.length;
while (i--)
if (!(points[i] is Point))
throw new ArrayContentsError();
if (points.length < 2)
throw new Error('At least two Points are needed to draw a path.');
graphics.moveTo(points[0].x, points[0].y);
i = 0;
while (++i < points.length)
graphics.lineTo(points[i].x, points[i].y);
}
/**
Draws a closed shape with the defined points.
@param graphics: The location where drawing should occur.
@param points: An Array comprised of at least three <code>Point</code>s to be use to draw a shape.
@throws ArrayContentsError if the Array is comprised of elements other than <code>Point</code> objects.
@throws <code>Error</code> if the Array has less than three <code>Point</code>s.
@usageNote This method will automatically connect the last point to the starting point.
@example
<code>
this.graphics.beginFill(0xFF00FF);
DrawUtil.drawShape(this.graphics, new Array(new Point(50, 25), new Point(75, 75), new Point(25, 75)));
this.graphics.endFill();
</code>
*/
public static function drawShape(graphics:Graphics, points:Array):void {
if (points.length < 3)
throw new Error('At least three Points are needed to draw a shape.');
DrawUtil.drawPath(graphics, points);
graphics.lineTo(points[0].x, points[0].y);
}
/**
Draws a circular wedge.
@param graphics: The location where drawing should occur.
@param ellipse: An Ellipse object that contains the size and position of the shape.
@param startAngle: The starting angle of wedge in degrees.
@param arc: The sweep of the wedge in degrees.
@example
<code>
this.graphics.beginFill(0xFF00FF);
DrawUtil.drawWedge(this.graphics, new Ellipse(0, 0, 300, 200), 0, 300);
this.graphics.endFill();
</code>
*/
public static function drawWedge(graphics:Graphics, ellipse:Ellipse, startAngle:Number, arc:Number):void {
if (Math.abs(arc) >= 360) {
graphics.drawEllipse(ellipse.x, ellipse.y, ellipse.width, ellipse.height);
return;
}
startAngle += 90;
var radius:Number = ellipse.width * .5;
var yRadius:Number = ellipse.height * .5;
var x:Number = ellipse.x + radius;
var y:Number = ellipse.y + yRadius;
var segs:Number = Math.ceil(Math.abs(arc) / 45);
var segAngle:Number = -arc / segs;
var theta:Number = -(segAngle / 180) * Math.PI;
var angle:Number = -(startAngle / 180) * Math.PI;
var ax:Number = x + Math.cos(startAngle / 180 * Math.PI) * radius;
var ay:Number = y + Math.sin(-startAngle / 180 * Math.PI) * yRadius;
var angleMid:Number;
graphics.moveTo(x, y);
graphics.lineTo(ax, ay);
var i:Number = -1;
while (++i < segs) {
angle += theta;
angleMid = angle - (theta * .5);
graphics.curveTo(x + Math.cos(angleMid) * (radius / Math.cos(theta * .5)), y + Math.sin(angleMid) * (yRadius / Math.cos(theta * .5)), x + Math.cos(angle) * radius, y + Math.sin(angle) * yRadius);
}
graphics.lineTo(x, y);
}
/**
Draws a rounded rectangle. Act identically to <code>Graphics.drawRoundRect</code> but allows the specification of which corners are rounded.
@param graphics: The location where drawing should occur.
@param x: The horizontal position of the rectangle.
@param y: The vertical position of the rectangle.
@param width: The width of the rectangle.
@param height: The height of the rectangle.
@param ellipseWidth: The width in pixels of the ellipse used to draw the rounded corners.
@param ellipseHeight: The height in pixels of the ellipse used to draw the rounded corners.
@param topLeft: Specifies if the top left corner of the rectangle should be rounded <code>true</code>, or should be square <code>false</code>.
@param topRight:Specifies if the top right corner of the rectangle should be rounded <code>true</code>, or should be square <code>false</code>.
@param bottomRight: Specifies if the bottom right corner of the rectangle should be rounded <code>true</code>, or should be square <code>false</code>.
@param bottomLeft: Specifies if the bottom left corner of the rectangle should be rounded <code>true</code>, or should be square <code>false</code>.
@example
<code>
this.graphics.beginFill(0xFF00FF);
DrawUtil.drawRoundRect(this.graphics, 10, 10, 200, 200, 50, 50, true, false, true, false);
this.graphics.endFill();
</code>
*/
public static function drawRoundRect(graphics:Graphics, x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number, ellipseHeight:Number, topLeft:Boolean = true, topRight:Boolean = true, bottomRight:Boolean = true, bottomLeft:Boolean = true):void {
const radiusWidth:Number = ellipseWidth * 0.5;
const radiusHeight:Number = ellipseHeight * 0.5;
if (topLeft)
graphics.moveTo(x + radiusWidth, y);
else
graphics.moveTo(x, y);
if (topRight) {
graphics.lineTo(x + width - radiusWidth, y);
graphics.curveTo(x + width, y, x + width, y + radiusHeight);
} else
graphics.lineTo(x + width, y);
if (bottomRight) {
graphics.lineTo(x + width, y + height - radiusHeight);
graphics.curveTo(x + width, y + height, x + width - radiusWidth, y + height);
} else
graphics.lineTo(x + width, y + height);
if (bottomLeft) {
graphics.lineTo(x + radiusWidth, y + height);
graphics.curveTo(x, y + height, x, y + height - radiusHeight);
} else
graphics.lineTo(x, y + height);
if (topLeft) {
graphics.lineTo(x, y + radiusHeight);
graphics.curveTo(x, y, x + radiusWidth, y);
} else
graphics.lineTo(x, y);
}
/**
Draws a rectangle using a <code>Rectangle</code> as a convenience.
@param graphics: The location where drawing should occur.
@param rectangle: The <code>Rectangle</code> to draw.
@example
<code>
this.graphics.beginFill(0xFF00FF);
DrawUtil.drawRectangle(this.graphics, new Rectangle(10, 10, 20, 20));
this.graphics.endFill();
</code>
*/
public static function drawRectangle(graphics:Graphics, rectangle:Rectangle):void {
graphics.drawRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
} |
/**
* Manages playback of http streaming flv and mp4.
**/
package com.longtailvideo.jwplayer.media {
import com.longtailvideo.jwplayer.events.MediaEvent;
import com.longtailvideo.jwplayer.model.PlayerConfig;
import com.longtailvideo.jwplayer.model.PlaylistItem;
import com.longtailvideo.jwplayer.player.PlayerState;
import com.longtailvideo.jwplayer.utils.Configger;
import com.longtailvideo.jwplayer.utils.Logger;
import com.longtailvideo.jwplayer.utils.NetClient;
import com.longtailvideo.jwplayer.utils.Strings;
import flash.events.*;
import flash.media.*;
import flash.net.*;
import flash.utils.*;
public class HTTPMediaProvider extends MediaProvider {
/** NetConnection object for setup of the video stream. **/
protected var _connection:NetConnection;
/** NetStream instance that handles the stream IO. **/
protected var _stream:NetStream;
/** Video object to be instantiated. **/
protected var _video:Video;
/** Sound control object. **/
protected var _transformer:SoundTransform;
/** ID for the _position interval. **/
protected var _positionInterval:uint;
/** Save whether metadata has already been sent. **/
protected var _meta:Boolean;
/** Object with keyframe times and positions. **/
protected var _keyframes:Object;
/** Offset in bytes of the last seek. **/
protected var _byteoffset:Number = 0;
/** Offset in seconds of the last seek. **/
protected var _timeoffset:Number = 0;
/** Boolean for mp4 / flv streaming. **/
protected var _mp4:Boolean;
/** Start parameter. **/
private var _startparam:String = 'start';
/** Whether the buffer has filled **/
private var _bufferFull:Boolean;
/** Whether the enitre video has been buffered **/
private var _bufferingComplete:Boolean;
/** Whether we have checked the bandwidth. **/
private var _bandwidthSwitch:Boolean = true;
/** Whether we have checked bandwidth **/
private var _bandwidthChecked:Boolean;
/** Bandwidth check delay **/
private var _bandwidthDelay:Number = 2000;
/** Bandwidth timeout id **/
private var _bandwidthTimeout:uint;
/** Offset for DVR streaming. **/
private var _dvroffset:Number = 0;
/** Loaded amount for DVR streaming. **/
private var _dvrloaded:Number = 0;
/** Framerate of the video. **/
private var _framerate:Number = 30;
/** Number of frames dropped at present. **/
private var _droppedFrames:Array;
/** ID for the framedrop checking interval. **/
private var _droppedFramesInterval:Number;
/** Constructor; sets up the connection and display. **/
public function HTTPMediaProvider() {
super('http');
}
public override function initializeMediaProvider(cfg:PlayerConfig):void {
super.initializeMediaProvider(cfg);
_connection = new NetConnection();
_connection.connect(null);
_stream = new NetStream(_connection);
_stream.checkPolicyFile = true;
_stream.addEventListener(NetStatusEvent.NET_STATUS, statusHandler);
_stream.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
_stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, errorHandler);
_stream.bufferTime = config.bufferlength;
_stream.client = new NetClient(this);
_transformer = new SoundTransform();
_video = new Video(320, 240);
_video.smoothing = config.smoothing;
_video.attachNetStream(_stream);
}
/** Convert seekpoints to keyframes. **/
protected function convertSeekpoints(dat:Object):Object {
var kfr:Object = new Object();
kfr.times = new Array();
kfr.filepositions = new Array();
for (var j:String in dat) {
kfr.times[j] = Number(dat[j]['time']);
kfr.filepositions[j] = Number(dat[j]['offset']);
}
return kfr;
}
/** Catch security errors. **/
protected function errorHandler(evt:ErrorEvent):void {
error(evt.text);
}
/** Bandwidth is checked as long the stream hasn't completed loading. **/
private function checkBandwidth(lastLoaded:Number):void {
var currentLoaded:Number = _stream.bytesLoaded;
var bandwidth:Number = Math.ceil((currentLoaded - lastLoaded) / 1024) * 8 / (_bandwidthDelay / 1000);
if (currentLoaded < _stream.bytesTotal) {
if (bandwidth > 0) {
config.bandwidth = bandwidth;
Configger.saveCookie('bandwidth',bandwidth);
var obj:Object = {bandwidth:bandwidth};
if (item.duration > 0) {
obj.bitrate = Math.ceil(_stream.bytesTotal / 1024 * 8 / item.duration);
}
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata: obj});
}
if (_bandwidthSwitch) {
_bandwidthSwitch = false;
_bandwidthChecked = false;
if (item.currentLevel != item.getLevel(config.bandwidth, config.width)) {
load(item);
return;
}
}
clearTimeout(_bandwidthTimeout);
_bandwidthTimeout = setTimeout(checkBandwidth, _bandwidthDelay, currentLoaded);
}
}
/** Check the number and percentage of dropped frames per playback session. **/
private function checkFramedrop():void {
_droppedFrames.push(_stream.info.droppedFrames);
var len:Number = _droppedFrames.length;
if(len > 5 && state == PlayerState.PLAYING) {
var drp:Number = (_droppedFrames[len-1] - _droppedFrames[len-6])/5;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata: {droppedFrames:drp}});
/*
if(drp > _framerate/4 && item.currentLevel < item.levels.length - 1) {
item.blacklistLevel(item.currentLevel);
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata: {type:'blacklist',level:item.currentLevel}});
load(item);
}
*/
}
};
/** Return a keyframe byteoffset or timeoffset. **/
protected function getOffset(pos:Number, tme:Boolean=false):Number {
if (!_keyframes) {
return 0;
}
for (var i:Number = 0; i < _keyframes.times.length - 1; i++) {
if (_keyframes.times[i] <= pos && _keyframes.times[i + 1] >= pos) {
break;
}
}
if (tme == true) {
return _keyframes.times[i];
} else {
return _keyframes.filepositions[i];
}
}
/** Create the video request URL. **/
protected function getURL():String {
var url:String = Strings.getAbsolutePath(item.file, config['netstreambasepath']);
var off:Number = _byteoffset;
if (getConfigProperty('startparam') as String) {
_startparam = getConfigProperty('startparam');
}
if (item.streamer) {
if (item.streamer.indexOf('/') >= 0) {
url = item.streamer;
url = getURLConcat(url, 'file', item.file);
} else {
_startparam = item.streamer;
}
}
if (_mp4 || _startparam == 'starttime') {
off = Math.ceil(_timeoffset*100)/100;
_mp4 = true;
}
if ((!_mp4 || off > 0) && !getConfigProperty('dvr')) {
url = getURLConcat(url, _startparam, off);
}
if (config['token'] || item['token']) {
url = getURLConcat(url, 'token', item['token'] ? item['token'] : config['token']);
}
return url;
}
/** Concatenate a parameter to the url. **/
private function getURLConcat(url:String, prm:String, val:*):String {
if (url.indexOf('?') > -1) {
return url + '&' + prm + '=' + val;
} else {
return url + '?' + prm + '=' + val;
}
}
private function initDVR(pos:Number):void {
_dvroffset = pos;
_dvrloaded = new Date().valueOf() - config.bufferlength * 1000;
super.resize(_width, _height);
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata: {dvroffset:_dvroffset}});
}
/** Load content. **/
override public function load(itm:PlaylistItem):void {
if (_item != itm) {
_item = itm;
media = _video;
}
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_LOADED);
_bufferFull = false;
_bufferingComplete = false;
if (item.levels.length > 0) { item.setLevel(item.getLevel(config.bandwidth, config.width)); }
_stream.play(getURL());
clearInterval(_positionInterval);
_positionInterval = setInterval(positionInterval, 100);
_droppedFrames = new Array();
clearInterval(_droppedFramesInterval);
_droppedFramesInterval = setInterval(checkFramedrop,1000);
setState(PlayerState.BUFFERING);
sendBufferEvent(0, 0);
streamVolume(config.mute ? 0 : config.volume);
}
/** Get metadata information from netstream class. **/
public function onClientData(dat:Object):void {
if (!dat) return;
if (dat.width) {
_video.width = dat.width;
_video.height = dat.height;
super.resize(_width, _height);
}
if(dat.videoframerate) {
_framerate = Number(dat.videoframerate);
}
if (dat['duration'] && item.duration <= 0) {
item.duration = dat['duration'];
}
if (dat['type'] == 'metadata' && !_meta) {
if (dat['seekpoints']) {
_mp4 = true;
_keyframes = convertSeekpoints(dat['seekpoints']);
} else {
_mp4 = false;
_keyframes = dat['keyframes'];
}
if (!_meta && _item.start) {
seek(_item.start);
}
_meta = true;
}
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata: dat});
}
/** Pause playback. **/
override public function pause():void {
_stream.pause();
super.pause();
}
/** Resume playing. **/
override public function play():void {
if (!_positionInterval) {
_positionInterval = setInterval(positionInterval, 100);
}
if (_bufferFull) {
_stream.resume();
super.play();
} else {
setState(PlayerState.BUFFERING);
}
}
/** Interval for the position progress **/
protected function positionInterval():void {
var pos:Number = Math.round(_stream.time * 100) / 100;
var percentoffset:Number;
if (_mp4) {
pos += _timeoffset;
}
if(getConfigProperty('dvr')) {
if(!_dvroffset && pos) { initDVR(pos); }
pos -= _dvroffset;
if(_dvrloaded) { item.duration = (new Date().valueOf()-_dvrloaded)/1000; }
}
var bufferFill:Number;
if (item.duration > 0 && _stream) {
percentoffset = _timeoffset / item.duration * 100;
var bufferTime:Number = _stream.bufferTime < (item.duration - pos) ? _stream.bufferTime : Math.ceil(item.duration - pos);
bufferFill = _stream.bufferTime ? Math.ceil(Math.ceil(_stream.bufferLength) / bufferTime * 100) : 0;
} else {
percentoffset = 0;
bufferFill = _stream.bufferTime ? _stream.bufferLength/_stream.bufferTime * 100 : 0;
}
var bufferPercent:Number = _stream.bytesTotal ? (_stream.bytesLoaded / _stream.bytesTotal) * (1 - percentoffset/100) * 100 : 0;
if (!_bandwidthChecked && _stream.bytesLoaded > 0 && _stream.bytesLoaded < _stream.bytesTotal) {
_bandwidthChecked = true;
clearTimeout(_bandwidthTimeout);
_bandwidthTimeout = setTimeout(checkBandwidth, _bandwidthDelay, _stream.bytesLoaded);
}
if (bufferFill < 50 && state == PlayerState.PLAYING && item.duration - pos > 5) {
_bufferFull = false;
_stream.pause();
setState(PlayerState.BUFFERING);
} else if (bufferFill > 95 && !_bufferFull) {
_bufferFull = true;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_BUFFER_FULL);
}
if (!_bufferingComplete) {
if ((bufferPercent + percentoffset) == 100 && _bufferingComplete == false) {
_bufferingComplete = true;
}
sendBufferEvent(bufferPercent, _timeoffset,
{loaded:_stream.bytesLoaded, total:_stream.bytesTotal, offset:_timeoffset});
}
if (state != PlayerState.PLAYING) {
return;
}
if (pos < item.duration) {
_position = pos;
if (_position >= 0) {
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_TIME, {position: _position, duration: item.duration, offset: _timeoffset});
}
} else if (item.duration > 0) {
// Playback completed
complete();
}
}
/** Handle a resize event **/
override public function resize(width:Number, height:Number):void {
if (width == _width && _height == height) {
// Dimensions are the same; no need to resize.
return;
}
super.resize(width, height);
if (state != PlayerState.IDLE && item.levels.length > 0 && item.getLevel(config.bandwidth, config.width) != item.currentLevel) {
_byteoffset = getOffset(position);
_timeoffset = _position = getOffset(position,true);
load(item);
}
}
/** Seek to a specific second. **/
override public function seek(pos:Number):void {
var off:Number = getOffset(pos);
super.seek(pos);
clearInterval(_positionInterval);
_positionInterval = undefined;
if (off < _byteoffset || off >= _byteoffset + _stream.bytesLoaded) {
if (_keyframes) {
_timeoffset = _position = getOffset(pos, true);
} else {
/* Keyframes not yet available; queue up the time offset so the seek occurs when the keyframes arrive */
_timeoffset = pos;
}
_byteoffset = off;
load(item);
} else {
if (state == PlayerState.PAUSED) {
_stream.resume();
}
if(getConfigProperty('dvr')) {
_stream.seek(pos + _dvroffset - config.bufferlength);
} else if (_mp4) {
_stream.seek(getOffset(_position - _timeoffset, true));
} else {
_stream.seek(getOffset(_position, true));
}
play();
}
}
/** Receive NetStream status updates. **/
protected function statusHandler(evt:NetStatusEvent):void {
switch (evt.info.code) {
case "NetStream.Play.Stop":
if(state != PlayerState.BUFFERING && !getConfigProperty('dvr')) {
complete();
}
break;
case "NetStream.Play.StreamNotFound":
stop();
error('Video not found: ' + item.file);
break;
case 'NetStream.Buffer.Full':
if (!_bufferFull) {
_bufferFull = true;
sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_BUFFER_FULL);
}
break;
}
// sendMediaEvent(MediaEvent.JWPLAYER_MEDIA_META, {metadata: {status: evt.info.code}});
}
/** Destroy the HTTP stream. **/
override public function stop():void {
if (_stream.bytesLoaded < _stream.bytesTotal || _byteoffset > 0) {
_stream.close();
} else {
_stream.pause();
}
clearInterval(_positionInterval);
clearInterval(_droppedFramesInterval);
_positionInterval = undefined;
_position = _byteoffset = _timeoffset = 0;
_dvroffset = _dvrloaded = 0;
_droppedFrames = new Array();
_keyframes = undefined;
_framerate = 30;
_bandwidthSwitch = true;
_bandwidthChecked = false;
_meta = false;
_timeoffset = 0;
super.stop();
}
override protected function complete():void {
if (state != PlayerState.IDLE) {
stop();
setTimeout(sendMediaEvent,100,MediaEvent.JWPLAYER_MEDIA_COMPLETE);
}
}
/** Set the volume level. **/
override public function setVolume(vol:Number):void {
streamVolume(vol);
super.setVolume(vol);
}
/** Set the stream's volume, without sending a volume event **/
protected function streamVolume(level:Number):void {
_transformer.volume = level / 100;
if (_stream) {
_stream.soundTransform = _transformer;
}
}
}
} |
package flash.events {
import flash.geom.Rectangle;
public class NativeWindowBoundsEvent extends Event {
public function get afterBounds():Rectangle;
public function get beforeBounds():Rectangle;
public function NativeWindowBoundsEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false, beforeBounds:Rectangle = null, afterBounds:Rectangle = null);
public override function clone():Event;
public override function toString():String;
public static const MOVE:String = "move";
public static const MOVING:String = "moving";
public static const RESIZE:String = "resize";
public static const RESIZING:String = "resizing";
}
}
|
/**
* DER
*
* A basic class to parse DER structures.
* It is very incomplete, but sufficient to extract whatever data we need so far.
* Copyright (c) 2007 Henri Torgemane
*
* See LICENSE.txt for full license information.
*/
package com.hurlant.util.der
{
import flash.utils.ByteArray;
import com.hurlant.util.der.Sequence;
// goal 1: to be able to parse an RSA Private Key PEM file.
// goal 2: to parse an X509v3 cert. kinda.
/**
* DER for dummies:
* http://luca.ntop.org/Teaching/Appunti/asn1.html
*
* This class does the bare minimum to get by. if that.
*/
public class DER
{
public static var indent:String = "";
public static function parse(der:ByteArray, structure:*=null):IAsn1Type {
/* if (der.position==0) {
trace("DER.parse: "+Hex.fromArray(der));
}
*/ // type
var type:int = der.readUnsignedByte();
var constructed:Boolean = (type&0x20)!=0;
type &=0x1F;
// length
var len:int = der.readUnsignedByte();
if (len>=0x80) {
// long form of length
var count:int = len & 0x7f;
len = 0;
while (count>0) {
len = (len<<8) | der.readUnsignedByte();
count--;
}
}
// data
var b:ByteArray;
switch (type) {
case 0x00: // WHAT IS THIS THINGY? (seen as 0xa0)
// (note to self: read a spec someday.)
// for now, treat as a sequence.
case 0x10: // SEQUENCE/SEQUENCE OF. whatever
// treat as an array
var p:int = der.position;
var o:Sequence = new Sequence(type, len);
var arrayStruct:Array = structure as Array;
if (arrayStruct!=null) {
// copy the array, as we destroy it later.
arrayStruct = arrayStruct.concat();
}
while (der.position < p+len) {
var tmpStruct:Object = null;
if (arrayStruct!=null) {
tmpStruct = arrayStruct.shift();
}
if (tmpStruct!=null) {
while (tmpStruct && tmpStruct.optional) {
// make sure we have something that looks reasonable. XXX I'm winging it here..
var wantConstructed:Boolean = (tmpStruct.value is Array);
var isConstructed:Boolean = isConstructedType(der);
if (wantConstructed!=isConstructed) {
// not found. put default stuff, or null
o.push(tmpStruct.defaultValue);
o[tmpStruct.name] = tmpStruct.defaultValue;
// try the next thing
tmpStruct = arrayStruct.shift();
} else {
break;
}
}
}
if (tmpStruct!=null) {
var name:String = tmpStruct.name;
var value:* = tmpStruct.value;
if (tmpStruct.extract) {
// we need to keep a binary copy of this element
var size:int = getLengthOfNextElement(der);
var ba:ByteArray = new ByteArray;
ba.writeBytes(der, der.position, size);
o[name+"_bin"] = ba;
}
var obj:IAsn1Type = DER.parse(der, value);
o.push(obj);
o[name] = obj;
} else {
o.push(DER.parse(der));
}
}
return o;
case 0x11: // SET/SET OF
p = der.position;
var s:Set = new Set(type, len);
while (der.position < p+len) {
s.push(DER.parse(der));
}
return s;
case 0x02: // INTEGER
// put in a BigInteger
b = new ByteArray;
der.readBytes(b,0,len);
b.position=0;
return new Integer(type, len, b);
case 0x06: // OBJECT IDENTIFIER:
b = new ByteArray;
der.readBytes(b,0,len);
b.position=0;
return new ObjectIdentifier(type, len, b);
default:
trace("I DONT KNOW HOW TO HANDLE DER stuff of TYPE "+type);
// fall through
case 0x03: // BIT STRING
if (der[der.position]==0) {
//trace("Horrible Bit String pre-padding removal hack."); // I wish I had the patience to find a spec for this.
der.position++;
len--;
}
case 0x04: // OCTET STRING
// stuff in a ByteArray for now.
var bs:ByteString = new ByteString(type, len);
der.readBytes(bs,0,len);
return bs;
case 0x05: // NULL
// if len!=0, something's horribly wrong.
// should I check?
return null;
case 0x13: // PrintableString
var ps:PrintableString = new PrintableString(type, len);
ps.setString(der.readMultiByte(len, "US-ASCII"));
return ps;
case 0x22: // XXX look up what this is. openssl uses this to store my email.
case 0x14: // T61String - an horrible format we don't even pretend to support correctly
ps = new PrintableString(type, len);
ps.setString(der.readMultiByte(len, "latin1"));
return ps;
case 0x17: // UTCTime
var ut:UTCTime = new UTCTime(type, len);
ut.setUTCTime(der.readMultiByte(len, "US-ASCII"));
return ut;
}
}
private static function getLengthOfNextElement(b:ByteArray):int {
var p:uint = b.position;
// length
b.position++;
var len:int = b.readUnsignedByte();
if (len>=0x80) {
// long form of length
var count:int = len & 0x7f;
len = 0;
while (count>0) {
len = (len<<8) | b.readUnsignedByte();
count--;
}
}
len += b.position-p; // length of length
b.position = p;
return len;
}
private static function isConstructedType(b:ByteArray):Boolean {
var type:int = b[b.position];
return (type&0x20)!=0;
}
public static function wrapDER(type:int, data:ByteArray):ByteArray {
var d:ByteArray = new ByteArray;
d.writeByte(type);
var len:int = data.length;
if (len<128) {
d.writeByte(len);
} else if (len<256) {
d.writeByte(1 | 0x80);
d.writeByte(len);
} else if (len<65536) {
d.writeByte(2 | 0x80);
d.writeByte(len>>8);
d.writeByte(len);
} else if (len<65536*256) {
d.writeByte(3 | 0x80);
d.writeByte(len>>16);
d.writeByte(len>>8);
d.writeByte(len);
} else {
d.writeByte(4 | 0x80);
d.writeByte(len>>24);
d.writeByte(len>>16);
d.writeByte(len>>8);
d.writeByte(len);
}
d.writeBytes(data);
d.position=0;
return d;
}
}
} |
package fairygui
{
import flash.geom.Rectangle;
import flash.media.Sound;
import fairygui.display.Frame;
import fairygui.text.BitmapFont;
import starling.textures.Texture;
public class PackageItem
{
public var owner:UIPackage;
public var type:int;
public var id:String;
public var name:String;
public var width:int;
public var height:int;
public var file:String;
public var lastVisitTime:int;
public var callbacks:Array = [];
public var loading:Boolean;
public var loaded:Boolean;
//image
public var scale9Grid:Rectangle;
public var scaleByTile:Boolean;
public var tileGridIndice:int;
public var smoothing:Boolean;
public var texture:Texture;
public var uvRect:Rectangle;
//movieclip
public var interval:Number;
public var repeatDelay:Number;
public var swing:Boolean;
public var frames:Vector.<Frame>;
//componenet
public var componentData:XML;
public var displayList:Vector.<DisplayListItem>;
public var extensionType:Object;
//sound
public var sound:Sound;
//font
public var bitmapFont:BitmapFont;
public function PackageItem()
{
}
public function addCallback(callback:Function):void
{
var i:int = callbacks.indexOf(callback);
if(i==-1)
callbacks.push(callback);
}
public function removeCallback(callback:Function):Function
{
var i:int = callbacks.indexOf(callback);
if(i!=-1)
{
callbacks.splice(i,1);
return callback;
}
else
return null;
}
public function completeLoading():void
{
loading = false;
loaded = true;
var arr:Array = callbacks.slice();
for each(var callback:Function in arr)
callback(this);
callbacks.length = 0;
}
public function onAltasLoaded(source:PackageItem):void
{
owner.notifyImageAtlasReady(this, source);
}
public function toString():String
{
return name;
}
}
} |
/*
Copyright 2012-2013 Renaun Erickson
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.
@author Renaun Erickson / renaun.com / @renaun
*/
package flash.display3D
{
public class Context3DCompareMode
{
public static const ALWAYS:String = "always";
public static const EQUAL:String = "equal";
public static const GREATER:String = "greater";
public static const GREATER_EQUAL:String = "greaterEqual";
public static const LESS:String = "less";
public static const LESS_EQUAL:String = "lessEqual";
public static const NEVER:String = "never";
public static const NOT_EQUAL:String = "notEqual";
public function Context3DCompareMode()
{
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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.royale.test.runners
{
import org.apache.royale.test.runners.notification.IRunNotifier;
public interface ITestRunner
{
/**
* A description of this test runner.
*/
function get description():String;
/**
* Requests that the runner stops running the tests. Phrased politely
* because the test that is currently running may not be interrupted
* before completing.
*/
function pleaseStop():void;
/**
* Runs the tests.
*/
function run(notifier:IRunNotifier):void;
}
} |
/**
* BigBlueButton open source conferencing system - http://www.bigbluebutton.org/
*
* Copyright (c) 2014 BigBlueButton Inc. and by respective authors (see below).
*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation; either version 3.0 of the License, or (at your option) any later
* version.
*
* BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with BigBlueButton; if not, see <http://www.gnu.org/licenses/>.
*
*/
package org.bigbluebutton.clientcheck.view.mainview
{
import flash.events.Event;
import flash.events.MouseEvent;
import mx.collections.ArrayCollection;
import mx.resources.ResourceManager;
import mx.utils.ObjectUtil;
import org.bigbluebutton.clientcheck.command.GetConfigXMLDataSignal;
import org.bigbluebutton.clientcheck.command.RequestBandwidthInfoSignal;
import org.bigbluebutton.clientcheck.command.RequestBrowserInfoSignal;
import org.bigbluebutton.clientcheck.command.RequestPortsSignal;
import org.bigbluebutton.clientcheck.command.RequestRTMPAppsSignal;
import org.bigbluebutton.clientcheck.model.ISystemConfiguration;
import org.bigbluebutton.clientcheck.model.IXMLConfig;
import org.bigbluebutton.clientcheck.model.IDataProvider;
import org.bigbluebutton.clientcheck.model.test.BrowserTest;
import org.bigbluebutton.clientcheck.model.test.CookieEnabledTest;
import org.bigbluebutton.clientcheck.model.test.DownloadBandwidthTest;
import org.bigbluebutton.clientcheck.model.test.FlashVersionTest;
import org.bigbluebutton.clientcheck.model.test.IsPepperFlashTest;
import org.bigbluebutton.clientcheck.model.test.JavaEnabledTest;
import org.bigbluebutton.clientcheck.model.test.LanguageTest;
import org.bigbluebutton.clientcheck.model.test.PingTest;
import org.bigbluebutton.clientcheck.model.test.PortTest;
import org.bigbluebutton.clientcheck.model.test.RTMPAppTest;
import org.bigbluebutton.clientcheck.model.test.ScreenSizeTest;
import org.bigbluebutton.clientcheck.model.test.UploadBandwidthTest;
import org.bigbluebutton.clientcheck.model.test.UserAgentTest;
import org.bigbluebutton.clientcheck.model.test.WebRTCEchoTest;
import org.bigbluebutton.clientcheck.model.test.WebRTCSocketTest;
import org.bigbluebutton.clientcheck.model.test.WebRTCSupportedTest;
import org.bigbluebutton.clientcheck.service.IExternalApiCallbacks;
import robotlegs.bender.bundles.mvcs.Mediator;
public class MainViewMediator extends Mediator
{
[Inject]
public var view:IMainView;
[Inject]
public var systemConfiguration:ISystemConfiguration;
[Inject]
public var externalApiCallbacks:IExternalApiCallbacks;
[Inject]
public var requestBrowserInfoSignal:RequestBrowserInfoSignal;
[Inject]
public var requestRTMPAppsInfoSignal:RequestRTMPAppsSignal;
[Inject]
public var requestPortsInfoSignal:RequestPortsSignal;
[Inject]
public var requestBandwidthInfoSignal:RequestBandwidthInfoSignal;
[Inject]
public var getConfigXMLDataSignal:GetConfigXMLDataSignal;
[Inject]
public var config:IXMLConfig;
[Inject]
public var dp:IDataProvider;
private static var VERSION:String=ResourceManager.getInstance().getString('resources', 'bbbsystemcheck.version');
override public function initialize():void
{
super.initialize();
view.view.addEventListener(Event.ADDED_TO_STAGE, viewAddedToStageHandler);
}
protected function viewAddedToStageHandler(event:Event):void
{
getConfigXMLDataSignal.dispatch();
config.configParsedSignal.add(configParsedHandler);
}
private function configParsedHandler():void
{
initPropertyListeners();
initDataProvider();
view.dataGrid.dataProvider=dp.getData();
requestBrowserInfoSignal.dispatch();
requestRTMPAppsInfoSignal.dispatch();
requestPortsInfoSignal.dispatch();
requestBandwidthInfoSignal.dispatch();
}
private function initPropertyListeners():void
{
systemConfiguration.userAgent.userAgentTestSuccessfullChangedSignal.add(userAgentChangedHandler);
systemConfiguration.browser.browserTestSuccessfullChangedSignal.add(browserChangedHandler);
systemConfiguration.screenSize.screenSizeTestSuccessfullChangedSignal.add(screenSizeChangedHandler);
systemConfiguration.flashVersion.flashVersionTestSuccessfullChangedSignal.add(flashVersionChangedHandler);
systemConfiguration.isPepperFlash.pepperFlashTestSuccessfullChangedSignal.add(isPepperFlashChangedHandler);
systemConfiguration.cookieEnabled.cookieEnabledTestSuccessfullChangedSignal.add(cookieEnabledChangedHandler);
systemConfiguration.language.languageTestSuccessfullChangedSignal.add(languageChangedHandler);
systemConfiguration.javaEnabled.javaEnabledTestSuccessfullChangedSignal.add(javaEnabledChangedHandler);
systemConfiguration.isWebRTCSupported.webRTCSupportedTestSuccessfullChangedSignal.add(isWebRTCSupportedChangedHandler);
systemConfiguration.webRTCEchoTest.webRTCEchoTestSuccessfullChangedSignal.add(webRTCEchoTestChangedHandler);
systemConfiguration.webRTCSocketTest.webRTCSocketTestSuccessfullChangedSignal.add(webRTCSocketTestChangedHandler);
systemConfiguration.downloadBandwidthTest.downloadSpeedTestSuccessfullChangedSignal.add(downloadSpeedTestChangedHandler);
systemConfiguration.uploadBandwidthTest.uploadSpeedTestSuccessfullChangedSignal.add(uploadSpeedTestChangedHandler);
systemConfiguration.pingTest.pingSpeedTestSuccessfullChangedSignal.add(pingSpeedTestChangedHandler);
for (var i:int=0; i < systemConfiguration.rtmpApps.length; i++)
{
systemConfiguration.rtmpApps[i].connectionResultSuccessfullChangedSignal.add(rtmpAppConnectionResultSuccessfullChangedHandler);
}
for (var j:int=0; j < systemConfiguration.ports.length; j++)
{
systemConfiguration.ports[j].tunnelResultSuccessfullChangedSignal.add(tunnelResultSuccessfullChangedHandler);
}
}
/**
* Gather all Item names even before it's tested
*/
private function initDataProvider():void
{
dp.addData({Item: BrowserTest.BROWSER, Result: null}, StatusENUM.LOADING);
dp.addData({Item: CookieEnabledTest.COOKIE_ENABLED, Result: null}, StatusENUM.LOADING);
dp.addData({Item: DownloadBandwidthTest.DOWNLOAD_SPEED, Result: null}, StatusENUM.LOADING);
dp.addData({Item: FlashVersionTest.FLASH_VERSION, Result: null}, StatusENUM.LOADING);
dp.addData({Item: IsPepperFlashTest.PEPPER_FLASH, Result: null}, StatusENUM.LOADING);
dp.addData({Item: JavaEnabledTest.JAVA_ENABLED, Result: null}, StatusENUM.LOADING);
dp.addData({Item: LanguageTest.LANGUAGE, Result: null}, StatusENUM.LOADING);
dp.addData({Item: PingTest.PING, Result: null}, StatusENUM.LOADING);
dp.addData({Item: ScreenSizeTest.SCREEN_SIZE, Result: null}, StatusENUM.LOADING);
// The upload is not working right now
// dp.addData({Item: UploadBandwidthTest.UPLOAD_SPEED, Result: "This is supposed to be failing right now"}, StatusENUM.FAILED);
dp.addData({Item: UserAgentTest.USER_AGENT, Result: null}, StatusENUM.LOADING);
dp.addData({Item: WebRTCEchoTest.WEBRTC_ECHO_TEST, Result: null}, StatusENUM.LOADING);
dp.addData({Item: WebRTCSocketTest.WEBRTC_SOCKET_TEST, Result: null}, StatusENUM.LOADING);
dp.addData({Item: WebRTCSupportedTest.WEBRTC_SUPPORTED, Result: null}, StatusENUM.LOADING);
if (systemConfiguration.rtmpApps)
{
for (var i:int=0; i < systemConfiguration.rtmpApps.length; i++)
{
dp.addData({Item: systemConfiguration.rtmpApps[i].applicationName, Result: null}, StatusENUM.LOADING);
}
}
if (systemConfiguration.ports)
{
for (var j:int=0; j < systemConfiguration.ports.length; j++)
{
dp.addData({Item: systemConfiguration.ports[j].portName, Result: null}, StatusENUM.LOADING);
}
}
dp.addData({Item: VERSION, Result: config.getVersion()}, StatusENUM.SUCCEED);
}
/**
* When RTMPApp item is getting updated we receive notification with 'applicationUri' of updated item
* We need to retrieve this item from the list of the available items and put it inside datagrid
**/
private function getRTMPAppItemByURI(applicationUri:String):RTMPAppTest
{
for (var i:int=0; i < systemConfiguration.rtmpApps.length; i++)
{
if (systemConfiguration.rtmpApps[i].applicationUri == applicationUri)
return systemConfiguration.rtmpApps[i];
}
return null;
}
private function rtmpAppConnectionResultSuccessfullChangedHandler(applicationUri:String):void
{
var appObj:RTMPAppTest=getRTMPAppItemByURI(applicationUri);
if (appObj)
{
var status:Object = (appObj.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: appObj.applicationName, Result: appObj.testResult}, status);
}
else
{
trace("Coudn't find rtmp app by applicationUri, skipping item: " + applicationUri);
}
}
private function getPortItemByPortName(port:String):PortTest
{
for (var i:int=0; i < systemConfiguration.ports.length; i++)
{
if (systemConfiguration.ports[i].portNumber == port)
return systemConfiguration.ports[i];
}
return null;
}
private function tunnelResultSuccessfullChangedHandler(port:String):void
{
var portObj:PortTest=getPortItemByPortName(port);
if (portObj)
{
var status:Object = (portObj.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: portObj.portName, Result: portObj.testResult}, status);
}
else
{
trace("Coudn't find port by port name, skipping item: " + port);
}
}
private function pingSpeedTestChangedHandler():void
{
var status:Object = (systemConfiguration.pingTest.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: PingTest.PING, Result: systemConfiguration.pingTest.testResult}, status);
}
private function downloadSpeedTestChangedHandler():void
{
var status:Object = (systemConfiguration.downloadBandwidthTest.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: DownloadBandwidthTest.DOWNLOAD_SPEED, Result: systemConfiguration.downloadBandwidthTest.testResult}, status);
}
private function uploadSpeedTestChangedHandler():void
{
var status:Object = (systemConfiguration.uploadBandwidthTest.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: UploadBandwidthTest.UPLOAD_SPEED, Result: systemConfiguration.uploadBandwidthTest.testResult}, status);
}
private function webRTCSocketTestChangedHandler():void
{
var status:Object = (systemConfiguration.webRTCSocketTest.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: WebRTCSocketTest.WEBRTC_SOCKET_TEST, Result: systemConfiguration.webRTCSocketTest.testResult}, status);
}
private function webRTCEchoTestChangedHandler():void
{
var status:Object = (systemConfiguration.webRTCEchoTest.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: WebRTCEchoTest.WEBRTC_ECHO_TEST, Result: systemConfiguration.webRTCEchoTest.testResult}, status);
}
private function isPepperFlashChangedHandler():void
{
var status:Object = (systemConfiguration.isPepperFlash.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: IsPepperFlashTest.PEPPER_FLASH, Result: systemConfiguration.isPepperFlash.testResult}, status);
}
private function languageChangedHandler():void
{
var status:Object = (systemConfiguration.language.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: LanguageTest.LANGUAGE, Result: systemConfiguration.language.testResult}, status);
}
private function javaEnabledChangedHandler():void
{
var status:Object = (systemConfiguration.javaEnabled.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.WARNING;
dp.updateData({Item: JavaEnabledTest.JAVA_ENABLED, Result: systemConfiguration.javaEnabled.testResult}, status);
}
private function isWebRTCSupportedChangedHandler():void
{
var status:Object = (systemConfiguration.isWebRTCSupported.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: WebRTCSupportedTest.WEBRTC_SUPPORTED, Result: systemConfiguration.isWebRTCSupported.testResult}, status);
}
private function cookieEnabledChangedHandler():void
{
var status:Object = (systemConfiguration.cookieEnabled.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: CookieEnabledTest.COOKIE_ENABLED, Result: systemConfiguration.cookieEnabled.testResult}, status);
}
private function screenSizeChangedHandler():void
{
var status:Object = (systemConfiguration.screenSize.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: ScreenSizeTest.SCREEN_SIZE, Result: systemConfiguration.screenSize.testResult}, status);
}
private function browserChangedHandler():void
{
var status:Object;
if (systemConfiguration.browser.testSuccessfull == true) {
status = StatusENUM.SUCCEED;
} else {
status = ObjectUtil.clone(StatusENUM.WARNING);
status.StatusMessage = systemConfiguration.browser.testMessage;
}
dp.updateData({Item: BrowserTest.BROWSER, Result: systemConfiguration.browser.testResult}, status);
}
private function userAgentChangedHandler():void
{
var status:Object = (systemConfiguration.userAgent.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: UserAgentTest.USER_AGENT, Result: systemConfiguration.userAgent.testResult}, status);
}
private function flashVersionChangedHandler():void
{
var status:Object = (systemConfiguration.flashVersion.testSuccessfull == true) ? StatusENUM.SUCCEED : StatusENUM.FAILED;
dp.updateData({Item: FlashVersionTest.FLASH_VERSION, Result: systemConfiguration.flashVersion.testResult}, status);
}
override public function destroy():void
{
if (systemConfiguration.rtmpApps)
{
for (var i:int=0; i < systemConfiguration.rtmpApps.length; i++)
{
systemConfiguration.rtmpApps[i].connectionResultSuccessfullChangedSignal.remove(rtmpAppConnectionResultSuccessfullChangedHandler);
}
}
if (systemConfiguration.ports)
{
for (var j:int=0; j < systemConfiguration.ports.length; j++)
{
systemConfiguration.ports[j].tunnelResultSuccessfullChangedSignal.remove(tunnelResultSuccessfullChangedHandler);
}
}
systemConfiguration.screenSize.screenSizeTestSuccessfullChangedSignal.remove(screenSizeChangedHandler);
systemConfiguration.userAgent.userAgentTestSuccessfullChangedSignal.remove(userAgentChangedHandler);
systemConfiguration.browser.browserTestSuccessfullChangedSignal.remove(browserChangedHandler);
systemConfiguration.flashVersion.flashVersionTestSuccessfullChangedSignal.remove(flashVersionChangedHandler);
systemConfiguration.isPepperFlash.pepperFlashTestSuccessfullChangedSignal.remove(isPepperFlashChangedHandler);
systemConfiguration.cookieEnabled.cookieEnabledTestSuccessfullChangedSignal.remove(cookieEnabledChangedHandler);
systemConfiguration.webRTCEchoTest.webRTCEchoTestSuccessfullChangedSignal.remove(webRTCEchoTestChangedHandler);
systemConfiguration.webRTCSocketTest.webRTCSocketTestSuccessfullChangedSignal.remove(webRTCSocketTestChangedHandler);
systemConfiguration.language.languageTestSuccessfullChangedSignal.remove(languageChangedHandler);
systemConfiguration.javaEnabled.javaEnabledTestSuccessfullChangedSignal.remove(javaEnabledChangedHandler);
systemConfiguration.isWebRTCSupported.webRTCSupportedTestSuccessfullChangedSignal.remove(isWebRTCSupportedChangedHandler);
systemConfiguration.downloadBandwidthTest.downloadSpeedTestSuccessfullChangedSignal.remove(downloadSpeedTestChangedHandler);
systemConfiguration.uploadBandwidthTest.uploadSpeedTestSuccessfullChangedSignal.remove(uploadSpeedTestChangedHandler);
systemConfiguration.pingTest.pingSpeedTestSuccessfullChangedSignal.remove(pingSpeedTestChangedHandler);
super.destroy();
}
}
}
|
package we3d.material
{
import we3d.we3d;
import we3d.mesh.Face;
import we3d.mesh.MeshProgram;
import we3d.rasterizer.IRasterizer;
import we3d.rasterizer.NativeFlat;
use namespace we3d;
/**
* Surfaces of polygons
*/
public class Surface
{
public function Surface (_rasterizer:IRasterizer=null, _attributes:ISurfaceAttributes=null, _hideBackfaces:Boolean=true) {
rasterizer = _rasterizer || defaultRasterizer;
attributes = _attributes || defaultAttributes;
hideBackfaces = _hideBackfaces
}
/**
* Hide or display backfaces
*/
public var hideBackfaces:Boolean;
public var rasterizer:IRasterizer;
public var attributes:ISurfaceAttributes;
we3d var program:MeshProgram;
public var programDirty:Boolean=true;
public var shared:Object = {};
public static var defaultRasterizer:IRasterizer = new NativeFlat();
public static var defaultAttributes:ISurfaceAttributes = new FlatAttributes();
public function clone () :Surface {
var r:Surface = new Surface( rasterizer.clone(), attributes.clone() );
r.hideBackfaces = hideBackfaces;
if(shared) {
for(var id:String in shared) {
r.shared[id] = shared[id];
}
}
return r;
}
}
} |
/*
* BetweenAS3
*
* Licensed under the MIT License
*
* Copyright (c) 2009 BeInteractive! (www.be-interactive.org) and
* Spark project (www.libspark.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.libspark.betweenas3.core.easing
{
/**
* Quadratic.easeOutIn.
*
* @author yossy:beinteractive
*/
public class QuadraticEaseOutIn implements IEasing
{
/**
* @inheritDoc
*/
public function calculate(t:Number, b:Number, c:Number, d:Number):Number
{
if (t < d / 2) {
return -(c / 2) * (t = (t * 2 / d)) * (t - 2) + b;
}
return (c / 2) * (t = (t * 2 - d) / d) * t + (b + c / 2);
}
}
} |
package com.adobe.protocols.dict
{
public class Definition
{
private var _definition:String;
private var _database:String;
private var _term:String;
public function set definition(definition:String):void
{
this._definition = definition;
}
public function get definition():String
{
return this._definition;
}
public function set database(database:String):void
{
this._database = database;
}
public function get database():String
{
return this._database;
}
public function set term(term:String):void
{
this._term = term;
}
public function get term():String
{
return this._term;
}
}
} |
package
{
import net.flashpunk.Engine;
import net.flashpunk.FP;
public class Main extends Engine
{
public function Main()
{
super(640, 640, 24, false);
}
override public function init():void
{
FP.world = new IntroWorld;
}
}
} |
// HSV Color Wheel
Window@ colorWheelWindow;
UIElement@ colorCursor = null;
UIElement@ colorWheel = null;
UIElement@ closeButton = null;
UIElement@ okButton = null;
UIElement@ cancelButton = null;
UIElement@ bwGradient = null;
UIElement@ bwCursor = null;
UIElement@ AGradient = null;
UIElement@ ACursor = null;
LineEdit@ rLineEdit = null;
LineEdit@ gLineEdit = null;
LineEdit@ bLineEdit = null;
LineEdit@ hLineEdit = null;
LineEdit@ sLineEdit = null;
LineEdit@ vLineEdit = null;
LineEdit@ aLineEdit = null;
BorderImage@ colorCheck = null;
Array<BorderImage@> colorFastItem;
Array<Color> colorFast;
int colorFastSelectedIndex = -1;
int colorFastHoverIndex = -1;
IntVector2 lastColorWheelWindowPosition;
bool isColorWheelHovering = false;
bool isBWGradientHovering = false;
bool isAGradientHovering = false;
Color wheelIncomingColor = Color(1,1,1,1);
Color wheelColor = Color(1,1,1,1);
float colorHValue = 1;
float colorSValue = 1;
float colorVValue = 1;
float colorAValue = 0.5;
int high = 0;
float aValue = 1;
const int IMAGE_SIZE = 256;
const int HALF_IMAGE_SIZE = 128;
const float MAX_ANGLE = 360;
const float ROUND_VALUE_MAX = 0.99f;
const float ROUND_VALUE_MIN = 0.01f;
// for handlers outside
String eventTypeWheelChangeColor = "WheelChangeColor";
String eventTypeWheelSelectColor = "WheelSelectColor";
String eventTypeWheelDiscardColor ="WheelDiscardColor";
void CreateColorWheel()
{
if (colorWheelWindow !is null)
return;
colorWheelWindow = LoadEditorUI("UI/EditorColorWheel.xml");
ui.root.AddChild(colorWheelWindow);
colorWheelWindow.opacity = uiMaxOpacity;
colorWheel = colorWheelWindow.GetChild("ColorWheel", true);
colorCursor = colorWheelWindow.GetChild("ColorCursor", true);
closeButton = colorWheelWindow.GetChild("CloseButton", true);
okButton = colorWheelWindow.GetChild("okButton", true);
cancelButton = colorWheelWindow.GetChild("cancelButton", true);
colorCheck = colorWheelWindow.GetChild("ColorCheck", true);
bwGradient = colorWheelWindow.GetChild("BWGradient", true);
bwCursor = colorWheelWindow.GetChild("BWCursor", true);
AGradient = colorWheelWindow.GetChild("AGradient", true);
ACursor = colorWheelWindow.GetChild("ACursor", true);
rLineEdit = colorWheelWindow.GetChild("R", true);
gLineEdit = colorWheelWindow.GetChild("G", true);
bLineEdit = colorWheelWindow.GetChild("B", true);
hLineEdit = colorWheelWindow.GetChild("H", true);
sLineEdit = colorWheelWindow.GetChild("S", true);
vLineEdit = colorWheelWindow.GetChild("V", true);
aLineEdit = colorWheelWindow.GetChild("A", true);
colorFastItem.Resize(8);
colorFast.Resize(8);
// Init some gradient for fast colors palette
for (int i=0; i<8; i++)
{
colorFastItem[i] = colorWheelWindow.GetChild("h"+String(i), true);
colorFast[i] = Color(i*0.125,i*0.125,i*0.125);
colorFastItem[i].color = colorFast[i];
}
SubscribeToEvent(closeButton, "Pressed", "HandleWheelButtons");
SubscribeToEvent(okButton, "Pressed", "HandleWheelButtons");
SubscribeToEvent(cancelButton, "Pressed", "HandleWheelButtons");
lastColorWheelWindowPosition = IntVector2(300,400);
HideColorWheel();
}
bool ShowColorWheelWithColor(Color oldColor)
{
wheelIncomingColor = oldColor;
wheelColor = oldColor;
return ShowColorWheel();
}
bool ShowColorWheel()
{
if (ui.focusElement !is null && colorWheelWindow.visible)
return false;
colorFastSelectedIndex = -1;
colorFastHoverIndex = -1;
EstablishColorWheelUIFromColor(wheelColor);
colorWheelWindow.opacity = 1;
colorWheelWindow.position = lastColorWheelWindowPosition;
colorWheelWindow.visible = true;
colorWheelWindow.BringToFront();
return true;
}
void HideColorWheel()
{
if (colorWheelWindow.visible)
{
colorWheelWindow.visible = false;
lastColorWheelWindowPosition = colorWheelWindow.position;
}
}
void HandleWheelButtons(StringHash eventType, VariantMap& eventData)
{
UIElement@ edit = eventData["Element"].GetPtr();
if (edit is null) return;
if (edit is cancelButton)
{
VariantMap vm;
eventData["Color"] = wheelIncomingColor;
SendEvent(eventTypeWheelDiscardColor, vm);
HideColorWheel();
}
if (edit is closeButton)
{
VariantMap vm;
eventData["Color"] = wheelIncomingColor;
SendEvent(eventTypeWheelDiscardColor, vm);
HideColorWheel();
}
if (edit is okButton)
{
VariantMap vm;
eventData["Color"] = wheelColor;
SendEvent(eventTypeWheelSelectColor, vm);
HideColorWheel();
}
}
void HandleColorWheelKeyDown(StringHash eventType, VariantMap& eventData)
{
if (colorWheelWindow.visible == false) return;
int key = eventData["Key"].GetInt();
if (key == KEY_ESCAPE)
{
SendEvent(eventTypeWheelDiscardColor, eventData);
HideColorWheel();
}
}
void HandleColorWheelMouseButtonDown(StringHash eventType, VariantMap& eventData)
{
if (colorWheelWindow.visible == false) return;
int x = eventData["X"].GetInt();
int y = eventData["Y"].GetInt();
int button = eventData["Button"].GetInt();
if (button == 1)
{
// check for select
if (colorFastHoverIndex != -1)
{
colorFastSelectedIndex = colorFastHoverIndex;
EstablishColorWheelUIFromColor(colorFast[colorFastSelectedIndex]);
SendEventChangeColor();
}
}
}
// handler only for BWGradient
void HandleColorWheelMouseWheel(StringHash eventType, VariantMap& eventData)
{
if (colorWheelWindow.visible == false || !isBWGradientHovering ) return;
int multipler = 16;
int wheelValue = eventData["Wheel"].GetInt();
wheelValue = wheelValue * multipler;
if (wheelValue != 0)
{
if (wheelValue > 0)
{
high = high + wheelValue;
high = Min(high, IMAGE_SIZE); // limit BWGradietn by high
}
else if (wheelValue < 0)
{
high = high + wheelValue;
high = Max(high, 0);
}
bwCursor.SetPosition(bwCursor.position.x, high - 7);
colorVValue = float(IMAGE_SIZE - high) / IMAGE_SIZE;
wheelColor.FromHSV(colorHValue, colorSValue, colorVValue, colorAValue);
SendEventChangeColor();
UpdateColorInformation();
}
}
void HandleColorWheelMouseMove(StringHash eventType, VariantMap& eventData)
{
if (colorWheelWindow.visible == false) return;
int x = eventData["X"].GetInt();
int y = eventData["Y"].GetInt();
int button = eventData["Button"].GetInt();
if (colorWheelWindow.IsInside(IntVector2(x,y), true))
colorWheelWindow.opacity = 1.0f;
int cwx = 0;
int cwy = 0;
int cx = 0;
int cy = 0;
IntVector2 i;
bool inWheel = false;
isBWGradientHovering = false;
isColorWheelHovering = false;
// if mouse cursor move on wheel rectangle
if (colorWheel.IsInside(IntVector2(x,y), true))
{
isColorWheelHovering = true;
// get element pos win screen
IntVector2 ep = colorWheel.screenPosition;
// math diff between mouse cursor & element pos = mouse pos on element
cwx = x - ep.x;
cwy = y - ep.y;
// shift mouse pos to center of wheel
cx = cwx - HALF_IMAGE_SIZE;
cy = cwy - HALF_IMAGE_SIZE;
// get direction vector of H on circle
Vector2 d = Vector2(cx, cy);
// if out of circle place colorCurcor back to circle
if (d.length > HALF_IMAGE_SIZE)
{
d.Normalize();
d = d * HALF_IMAGE_SIZE;
i = IntVector2(int(d.x), int(d.y));
inWheel = false;
}
else
{
inWheel = true;
}
if (isColorWheelHovering && inWheel && input.mouseButtonDown[MOUSEB_LEFT] || input.mouseButtonDown[MOUSEB_RIGHT])
{
Vector2 pointOnCircle = Vector2(cx,-cy);
float angle = GetAngle(pointOnCircle);
i = i + IntVector2(cwx,cwy);
colorCursor.position = IntVector2(i.x-7, i.y-7);
colorHValue = GetHueFromWheelDegAngle(angle);
if (colorHValue < ROUND_VALUE_MIN) colorHValue = 0.0;
if (colorHValue > ROUND_VALUE_MAX) colorHValue = 1.0;
colorSValue = d.length / HALF_IMAGE_SIZE;
if (colorSValue < ROUND_VALUE_MIN) colorSValue = 0.0;
if (colorSValue > ROUND_VALUE_MAX) colorSValue = 1.0;
wheelColor.FromHSV(colorHValue, colorSValue, colorVValue, colorAValue);
SendEventChangeColor();
UpdateColorInformation();
}
}
// if mouse cursor move on bwGradient rectangle
else if (bwGradient.IsInside(IntVector2(x,y), true))
{
isBWGradientHovering = true;
IntVector2 ep = bwGradient.screenPosition;
int high = y - ep.y;
if (input.mouseButtonDown[MOUSEB_LEFT] || input.mouseButtonDown[MOUSEB_RIGHT])
{
bwCursor.SetPosition(bwCursor.position.x, high - 7);
colorVValue = float(IMAGE_SIZE - high) / IMAGE_SIZE;
if (colorVValue < 0.01) colorVValue = 0.0;
if (colorVValue > 0.99) colorVValue = 1.0;
wheelColor.FromHSV(colorHValue, colorSValue, colorVValue, colorAValue);
SendEventChangeColor();
}
UpdateColorInformation();
}
// if mouse cursor move on AlphaGradient rectangle
else if (AGradient.IsInside(IntVector2(x,y), true))
{
IntVector2 ep = AGradient.screenPosition;
int aValue = x - ep.x;
if (input.mouseButtonDown[MOUSEB_LEFT] || input.mouseButtonDown[MOUSEB_RIGHT])
{
ACursor.SetPosition(aValue - 7, ACursor.position.y);
colorAValue = float((aValue) / 200); // 200pix image
// round values for min or max
if (colorAValue < 0.01) colorAValue = 0.0;
if (colorAValue > 0.99) colorAValue = 1.0;
wheelColor.FromHSV(colorHValue, colorSValue, colorVValue, colorAValue);
SendEventChangeColor();
}
UpdateColorInformation();
}
// cheking for history select
for (int j=0; j<8; j++)
{
if (colorFastItem[j].IsInside(IntVector2(x,y), true))
colorFastHoverIndex = j;
}
}
void UpdateColorInformation()
{
// fill UI from current color
hLineEdit.text = String(colorHValue).Substring(0,5);
sLineEdit.text = String(colorSValue).Substring(0,5);
vLineEdit.text = String(colorVValue).Substring(0,5);
rLineEdit.text = String(wheelColor.r).Substring(0,5);
gLineEdit.text = String(wheelColor.g).Substring(0,5);
bLineEdit.text = String(wheelColor.b).Substring(0,5);
aLineEdit.text = String(colorAValue).Substring(0,5);
colorCheck.color = wheelColor;
colorWheel.color = Color(colorVValue,colorVValue,colorVValue);
AGradient.color = Color(wheelColor.r, wheelColor.g, wheelColor.b);
// update selected fast-colors
if (colorFastSelectedIndex != -1)
{
colorFastItem[colorFastSelectedIndex].color = wheelColor;
colorFast[colorFastSelectedIndex] = wheelColor;
}
}
void SendEventChangeColor()
{
VariantMap eventData;
eventData["Color"] = wheelColor;
SendEvent("WheelChangeColor", eventData);
}
void EstablishColorWheelUIFromColor(Color c)
{
wheelColor = c;
colorHValue = c.Hue();
colorSValue = c.SaturationHSV();
colorVValue = c.Value();
colorAValue = c.a;
// convert color value to BWGradient high
high = int(IMAGE_SIZE - colorVValue * IMAGE_SIZE);
bwCursor.SetPosition(bwCursor.position.x, high - 7);
// convert color alpha to shift on x-axis for ACursor
aValue = 200 * colorAValue;
ACursor.SetPosition(int(aValue - 7), ACursor.position.y);
// rotate vector to H-angle with scale(shifting) by S to calculate final point position
Quaternion q(colorHValue * -MAX_ANGLE);
Vector3 pos = Vector3(1, 0, 0);
pos = q * pos;
pos = pos * (colorSValue * HALF_IMAGE_SIZE);
pos = pos + Vector3(HALF_IMAGE_SIZE, HALF_IMAGE_SIZE);
colorCursor.position = IntVector2(int(pos.x) - 7, int(pos.y) - 7);
// Update information on UI about color
UpdateColorInformation();
}
float GetHueFromWheelDegAngle(float angle)
{
return angle / MAX_ANGLE;
}
float GetAngle(Vector2 point)
{
float angle = Atan2( point.y, point.x );
if (angle < 0)
angle += MAX_ANGLE;
return angle;
} |
package de.dittner.siegmar.view.common.input {
import flash.events.Event;
[Style(name="borderColor", type="uint", format="Color", inherit="no")]
public class TextInputForm extends HistoryTextInput {
public function TextInputForm() {
super();
}
//--------------------------------------
// title
//--------------------------------------
private var _title:String = "";
[Bindable("titleChanged")]
public function get title():String {return _title;}
public function set title(value:String):void {
if (_title != value) {
_title = value;
if (skin) skin.invalidateDisplayList();
dispatchEvent(new Event("titleChanged"));
}
}
//--------------------------------------
// showTitle
//--------------------------------------
private var _showTitle:Boolean = true;
[Bindable("showTitleChanged")]
public function get showTitle():Boolean {return _showTitle;}
public function set showTitle(value:Boolean):void {
if (_showTitle != value) {
_showTitle = value;
if (skin) {
skin.invalidateSize();
skin.invalidateDisplayList();
}
dispatchEvent(new Event("showTitleChanged"));
}
}
//--------------------------------------
// isValidInput
//--------------------------------------
private var _isValidInput:Boolean = true;
[Bindable("isValidInputChanged")]
public function get isValidInput():Boolean {return _isValidInput;}
public function set isValidInput(value:Boolean):void {
if (_isValidInput != value) {
_isValidInput = value;
dispatchEvent(new Event("isValidInputChanged"));
if (skin) skin.invalidateDisplayList();
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 flashx.textLayout.elements
{
import flashx.textLayout.tlf_internal;
use namespace tlf_internal;
/**
* A read only class that describes a range of contiguous text. Such a range occurs when you select a
* section of text. The range consists of the anchor point of the selection, <code>anchorPosition</code>,
* and the point that is to be modified by actions, <code>activePosition</code>. As block selections are
* modified and extended <code>anchorPosition</code> remains fixed and <code>activePosition</code> is modified.
* The anchor position may be placed in the text before or after the active position.
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*
* @see flashx.textLayout.elements.TextFlow TextFlow
* @see flashx.textLayout.edit.SelectionState SelectionState
*/
public class TextRange
{
/** The TextFlow of the selection.
*/
private var _textFlow:TextFlow;
// current range of selection
/** Anchor point of the current selection, as an absolute position in the TextFlow. */
private var _anchorPosition:int;
/** Active end of the current selection, as an absolute position in the TextFlow. */
private var _activePosition:int;
private function clampToRange(index:int):int
{
if (index < 0)
return 0;
if (index > _textFlow.textLength)
return _textFlow.textLength;
return index;
}
/** Constructor - creates a new TextRange instance. A TextRange can be (-1,-1), indicating no range, or a pair of
* values from 0 to <code>TextFlow.textLength</code>.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
* @param root the TextFlow associated with the selection.
* @param anchorIndex the index position of the anchor in the selection. The first position in the text is position 0.
* @param activeIndex the index position of the active location in the selection. The first position in the text is position 0.
*
* @see FlowElement#textLength
*/
public function TextRange(root:TextFlow,anchorIndex:int,activeIndex:int)
{
_textFlow = root;
if (anchorIndex != -1 || activeIndex != -1)
{
anchorIndex = clampToRange(anchorIndex);
activeIndex = clampToRange(activeIndex);
}
_anchorPosition = anchorIndex;
_activePosition = activeIndex;
}
/** Update the range with new anchor or active position values.
*
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
* @param newAnchorPosition the anchor index of the selection.
* @param newActivePosition the active index of the selection.
* @return true if selection is changed.
*/
public function updateRange(newAnchorPosition:int,newActivePosition:int):Boolean
{
if (newAnchorPosition != -1 || newActivePosition != -1)
{
newAnchorPosition = clampToRange(newAnchorPosition);
newActivePosition = clampToRange(newActivePosition);
}
if (_anchorPosition != newAnchorPosition || _activePosition != newActivePosition)
{
_anchorPosition = newAnchorPosition;
_activePosition = newActivePosition;
return true;
}
return false;
}
/** Returns the TextFlow associated with the selection.
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public function get textFlow():TextFlow
{ return _textFlow; }
public function set textFlow(value:TextFlow):void
{ _textFlow = value; }
/** Anchor position of the selection, as an absolute position in the TextFlow.
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public function get anchorPosition():int
{ return _anchorPosition; }
public function set anchorPosition(value:int):void
{ _anchorPosition = value; }
/** Active position of the selection, as an absolute position in the TextFlow.
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public function get activePosition():int
{ return _activePosition; }
public function set activePosition(value:int):void
{ _activePosition = value; }
/** Start of the selection, as an absolute position in the TextFlow.
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public function get absoluteStart():int
{ return _activePosition < _anchorPosition ? _activePosition : _anchorPosition; }
public function set absoluteStart(value:int):void
{
if (_activePosition < _anchorPosition)
_activePosition = value;
else
_anchorPosition = value;
}
/** End of the selection, as an absolute position in the TextFlow.
* @playerversion Flash 10
* @playerversion AIR 1.5
* @langversion 3.0
*/
public function get absoluteEnd():int
{ return _activePosition > _anchorPosition ? _activePosition : _anchorPosition; }
public function set absoluteEnd(value:int):void
{
if (_activePosition > _anchorPosition)
_activePosition = value;
else
_anchorPosition = value;
}
}
} |
package ru.nacid.base.services.windows.commands
{
import ru.nacid.base.services.windows.policy.WindowPolicy;
import ru.nacid.base.services.windows.WindowParam;
/**
* RegWindow.as
* Created On: 5.8 20:22
*
* @author Nikolay nacid Bondarev
* @url https://github.com/nacid/nCore
*
*
* Copyright 2012 Nikolay nacid Bondarev
*
* 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.
*
*/
public class RegWindow extends WindowCommand
{
private var render:Class;
private var policy:WindowPolicy;
private var cached:Boolean;
private var modal:Boolean;
private var skinName:String;
public function RegWindow($id:String, $render:Class, $policy:WindowPolicy, $cached:Boolean=false, $modal:Boolean=false, $skinName:String=null)
{
super('regWindow', $id);
render=$render;
policy=$policy;
cached=$cached;
modal=$modal;
skinName=$skinName;
}
override protected function execInternal():void
{
navigator.regWindow(new WindowParam(windowId, render, policy, cached, modal, skinName));
notifyComplete();
}
}
}
|
package goplayer
{
import flash.display.DisplayObject
import flash.display.InteractiveObject
import flash.display.Sprite
import flash.events.Event
import flash.events.MouseEvent
import flash.geom.Point
import flash.geom.Rectangle
import flash.text.TextField
public class AbstractStandardSkin extends AbstractSkin
{
private var chromeFader : Fader
private var largePlayButtonFader : Fader
private var bufferingIndicatorFader : Fader
private var hoveringChrome : Boolean = false
private var showRemainingTime : Boolean = false
private var changingVolume : Boolean = false
private var volumeSliderFillMaxHeight : Number
private var volumeSliderFillMinY : Number
override protected function initialize() : void
{
super.initialize()
chromeFader = new Fader(chrome, Duration.seconds(.3))
largePlayButtonFader = new Fader
(largePlayButton, Duration.seconds(1))
bufferingIndicatorFader = new Fader
(bufferingIndicator, Duration.seconds(.3))
seekBarTooltip.visible = false
seekBar.mouseChildren = false
seekBar.buttonMode = true
volumeSliderFillMaxHeight = volumeSliderFill.height
volumeSliderFillMinY = volumeSliderFill.y
volumeSlider.mouseChildren = false
volumeSlider.buttonMode = true
volumeSliderThumbGuide.visible = false
volumeSlider.visible = false
chrome.visible = enableChrome
hidePopups()
addEventListeners()
}
override public function update() : void
{
super.update()
chromeFader.targetAlpha = showChrome ? 1 : 0
titleField.text = titleText
shareLinkField.text = shareLinkText
embedCodeField.text = embedCodeText
if (!changingVolume && !hoveringVolumeControl)
volumeSlider.visible = false
playButton.visible = !playing
pauseButton.visible = playing
muteButton.visible = !muted
unmuteButton.visible = muted
volumeSliderThumb.y = volumeSliderThumbY
volumeSliderFill.height = volumeSliderFillMaxHeight * volume
volumeSliderFill.y = volumeSliderFillMinY
+ volumeSliderFillMaxHeight * (1 - volume)
leftTimeField.text = elapsedTimeText
rightTimeField.text = showRemainingTime
? remainingTimeText : totalTimeText
seekBarBackground.width = seekBarWidth
seekBarGroove.width = seekBarWidth
seekBarBuffer.width = seekBarWidth * bufferRatio
seekBarPlayhead.width = seekBarWidth * playheadRatio
seekBarTooltip.x = seekBar.mouseX
seekBarTooltipField.text = seekTooltipText
largePlayButtonFader.targetAlpha = showLargePlayButton ? 1 : 0
largePlayButton.mouseEnabled = showLargePlayButton
bufferingIndicatorFader.targetAlpha = bufferingUnexpectedly ? 1 : 0
}
private function get showLargePlayButton() : Boolean
{ return !running }
override protected function get showChrome() : Boolean
{ return super.showChrome || hoveringChrome }
private function hidePopups() : void
{
popupBackground.visible = false
sharePopup.visible = false
embedPopup.visible = false
}
private function showPopup(popup : DisplayObject) : void
{
popupBackground.visible = true
popup.visible = true
}
private function get volumeSliderMouseVolume() : Number
{
return 1 - (volumeSlider.mouseY - volumeSliderThumbGuide.y)
/ volumeSliderThumbGuide.height
}
private function get volumeSliderThumbY() : Number
{
return volumeSliderThumbGuide.y
+ volumeSliderThumbGuide.height * (1 - volume)
}
private function get seekTooltipText() : String
{ return getDurationByRatio(seekBarMouseRatio).mss }
private function get seekBarMouseRatio() : Number
{ return seekBar.mouseX / seekBarWidth }
private function get hoveringVolumeControl() : Boolean
{ return volumeControlBounds.contains(mouseX, mouseY) }
private function get volumeControlBounds() : Rectangle
{
const result : Rectangle = $volumeControlBounds
result.inflate(10, 20)
return result
}
private function get $volumeControlBounds() : Rectangle
{
return muteButton.getBounds(this)
.union(volumeSlider.getBounds(this))
}
// -----------------------------------------------------
private function addEventListeners() : void
{
onclick(largePlayButton, handlePlayButtonClicked)
onclick(popupBackground, handlePopupBackgroundClicked)
onclick(copyShareLinkButton, handleCopyShareLinkButtonClicked)
onclick(twitterButton, handleTwitterButtonClicked)
onclick(facebookButton, handleFacebookButtonClicked)
onclick(copyEmbedCodeButton, handleCopyEmbedCodeButtonClicked)
onrollover(chrome, handleChromeRollOver)
onrollout(chrome, handleChromeRollOut)
onclick(shareButton, handleShareButtonClicked)
onclick(embedButton, handleEmbedButtonClicked)
onclick(playButton, handlePlayButtonClicked)
onclick(pauseButton, handlePauseButtonClicked)
onmousemove(seekBar, handleSeekBarMouseMove)
onrollover(seekBar, handleSeekBarRollOver)
onrollout(seekBar, handleSeekBarRollOut)
onclick(seekBar, handleSeekBarClicked)
onclick(rightTimeField, handleRightTimeFieldClicked)
onclick(muteButton, handleMuteButtonClicked)
onclick(unmuteButton, handleUnmuteButtonClicked)
onrollover(muteButton, handleVolumeButtonRollOver)
onrollover(unmuteButton, handleVolumeButtonRollOver)
onmousedown(volumeSlider, handleVolumeSliderMouseDown)
onclick(enableFullscreenButton, handleEnableFullscreenButtonClicked)
}
private function handlePopupBackgroundClicked() : void
{ hidePopups() }
private function handleChromeRollOver() : void
{ hoveringChrome = true, update() }
private function handleChromeRollOut() : void
{ hoveringChrome = false, update() }
// -----------------------------------------------------
private function handleShareButtonClicked() : void
{ shareLinkCopiedMessage.visible = false, showPopup(sharePopup) }
private function handleEmbedButtonClicked() : void
{ embedCodeCopiedMessage.visible = false, showPopup(embedPopup) }
private function handleCopyShareLinkButtonClicked() : void
{
selectTextField(shareLinkField)
backend.handleUserCopyShareURL()
shareLinkCopiedMessage.visible = true
}
private function handleCopyEmbedCodeButtonClicked() : void
{
selectTextField(embedCodeField)
backend.handleUserCopyEmbedCode()
embedCodeCopiedMessage.visible = true
}
private function selectTextField(field : TextField) : void
{
stage.focus = field
field.setSelection(0, field.length)
}
private function handleTwitterButtonClicked() : void
{ backend.handleUserShareViaTwitter() }
private function handleFacebookButtonClicked() : void
{ backend.handleUserShareViaFacebook() }
// -----------------------------------------------------
private function handlePlayButtonClicked() : void
{ backend.handleUserPlay() }
private function handlePauseButtonClicked() : void
{ backend.handleUserPause() }
// -----------------------------------------------------
private function handleSeekBarMouseMove() : void
{ update() }
private function handleSeekBarRollOver() : void
{ seekBarTooltip.visible = true }
private function handleSeekBarRollOut() : void
{ seekBarTooltip.visible = false }
private function handleSeekBarClicked() : void
{ backend.handleUserSeek(seekBarMouseRatio) }
private function handleRightTimeFieldClicked() : void
{ showRemainingTime = !showRemainingTime }
// -----------------------------------------------------
private function handleMuteButtonClicked() : void
{ backend.handleUserMute() }
private function handleUnmuteButtonClicked() : void
{ backend.handleUserUnmute() }
private function handleVolumeButtonRollOver() : void
{ volumeSlider.visible = true }
private function handleVolumeSliderMouseDown() : void
{
changingVolume = true
backend.handleUserSetVolume(volumeSliderMouseVolume)
stage.addEventListener
(MouseEvent.MOUSE_MOVE, handleVolumeSliderMouseMove);
stage.addEventListener
(MouseEvent.MOUSE_UP, handleVolumeSliderMouseUp);
stage.addEventListener
(Event.MOUSE_LEAVE, handleVolumeSliderMouseLeftStage);
}
private function handleVolumeSliderMouseMove(event : MouseEvent) : void
{ backend.handleUserSetVolume(volumeSliderMouseVolume) }
private function handleVolumeSliderMouseUp(event : MouseEvent) : void
{ removeVolumeSliderEventListeners() }
private function handleVolumeSliderMouseLeftStage(event : Event) : void
{ removeVolumeSliderEventListeners() }
// -----------------------------------------------------
private function removeVolumeSliderEventListeners() : void
{
stage.removeEventListener
(MouseEvent.MOUSE_MOVE, handleVolumeSliderMouseMove);
stage.removeEventListener
(MouseEvent.MOUSE_UP, handleVolumeSliderMouseUp);
stage.removeEventListener
(Event.MOUSE_LEAVE, handleVolumeSliderMouseLeftStage);
changingVolume = false
}
// -----------------------------------------------------
private function handleEnableFullscreenButtonClicked() : void
{ backend.handleUserToggleFullscreen() }
// -----------------------------------------------------
protected function get seekBarWidth() : Number
{ throw new Error }
protected function get largePlayButton() : InteractiveObject
{ return undefinedPart("largePlayButton") }
protected function get bufferingIndicator() : InteractiveObject
{ return undefinedPart("bufferingIndicator") }
protected function get popupBackground() : InteractiveObject
{ return undefinedPart("popupBackground") }
protected function get sharePopup() : InteractiveObject
{ return undefinedPart("sharePopup") }
protected function get shareLinkField() : TextField
{ return undefinedPart("shareLinkField") }
protected function get copyShareLinkButton() : DisplayObject
{ return undefinedPart("copyShareLinkButton") }
protected function get shareLinkCopiedMessage() : DisplayObject
{ return undefinedPart("shareLinkCopiedMessage") }
protected function get twitterButton() : DisplayObject
{ return undefinedPart("twitterButton") }
protected function get facebookButton() : DisplayObject
{ return undefinedPart("facebookButton") }
protected function get embedPopup() : InteractiveObject
{ return undefinedPart("embedPopup") }
protected function get embedCodeField() : TextField
{ return undefinedPart("embedCodeField") }
protected function get copyEmbedCodeButton() : DisplayObject
{ return undefinedPart("copyEmbedCodeButton") }
protected function get embedCodeCopiedMessage() : DisplayObject
{ return undefinedPart("embedCodeCopiedMessage") }
protected function get chrome() : Sprite
{ return undefinedPart("chrome") }
protected function get titleField() : TextField
{ return undefinedPart("titleField") }
protected function get shareButton() : DisplayObject
{ return undefinedPart("shareButton") }
protected function get embedButton() : DisplayObject
{ return undefinedPart("embedButton") }
protected function get leftTimeField() : TextField
{ return undefinedPart("leftTimeField") }
protected function get playButton() : DisplayObject
{ return undefinedPart("playButton") }
protected function get pauseButton() : DisplayObject
{ return undefinedPart("pauseButton") }
protected function get seekBarBackground() : DisplayObject
{ return undefinedPart("seekBarBackground") }
protected function get seekBar() : Sprite
{ return undefinedPart("seekBar") }
protected function get seekBarGroove() : DisplayObject
{ return undefinedPart("seekBarGroove") }
protected function get seekBarBuffer() : DisplayObject
{ return undefinedPart("seekBarBuffer") }
protected function get seekBarPlayhead() : DisplayObject
{ return undefinedPart("seekBarPlayhead") }
protected function get seekBarTooltip() : DisplayObject
{ return undefinedPart("seekBarTooltip") }
protected function get seekBarTooltipField() : TextField
{ return undefinedPart("seekBarTooltipField") }
protected function get rightTimeField() : TextField
{ return undefinedPart("rightTimeField") }
protected function get muteButton() : DisplayObject
{ return undefinedPart("muteButton") }
protected function get unmuteButton() : DisplayObject
{ return undefinedPart("unmuteButton") }
protected function get enableFullscreenButton() : DisplayObject
{ return undefinedPart("enableFullscreenButton") }
protected function get volumeSlider() : Sprite
{ return undefinedPart("volumeSlider") }
protected function get volumeSliderThumb() : DisplayObject
{ return undefinedPart("volumeSliderThumb") }
protected function get volumeSliderThumbGuide() : DisplayObject
{ return undefinedPart("volumeSliderThumbGuide") }
protected function get volumeSliderFill() : DisplayObject
{ return undefinedPart("volumeSliderFill") }
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import ThreeOptArgFunction.*
import com.adobe.test.Assert;
class ThreeOptArgFunctionClass {
function returnArguments(s:String = "Str3", b:Boolean = true, n:Number = 30) {
str = s;
bool = b;
num = n;
}
}
function returnArgumentsNoPackage(s:String = "Str4", b:Boolean = false, n:Number = 40) {
str = s;
bool = b;
num = n;
}
// TODO: Review AS4 Conversion
// These classes used to be external, but are now inside classes because of the change from include to import
class TestObjInner{
function returnArgumentsInner(s:String = "Str1", b:Boolean = true, n:Number = 10, ... rest) {
str = s;
bool = b;
num = n;
}
}
class TestObj extends TestObjInner {
function returnArguments() { returnArgumentsInner("Str1", true, 10, 12); }
}
function returnArgumentsInner(s:String = "Str2", b:Boolean = false, n:Number = 20, ... rest) {
str = s;
bool = b;
num = n;
}
function returnArguments() { returnArgumentsInner("Str2",false,20,true); }
// END TODO
// var SECTION = "Definitions"; // provide a document reference (ie, ECMA section)
// var VERSION = "AS3"; // Version of JavaScript or ECMA
// var TITLE = "Function Body Parameter/Result Type"; // Provide ECMA section title or a description
var BUGNUMBER = "";
var TESTOBJ = new TestObj();
var TESTOBJ1 = new ThreeOptArgFunctionClass();
var success = false;
TESTOBJ.returnArguments();
if(str == "Str1" && bool == true && num == 10)
{ success = true;}
else
{ success = false;}
Assert.expectEq( "TESTOBJ.returnArguments();", true, success );
success = false;
returnArguments();
if(str == "Str2" && bool == false && num == 20)
{ success = true;}
else
{ success = false;}
Assert.expectEq( "returnArguments();", true, success );
success = false;
TESTOBJ1.returnArguments();
if(str == "Str3" && bool == true && num == 30)
{ success = true;}
else
{ success = false;}
Assert.expectEq( "TESTOBJ1.returnArguments();", true, success );
success = false;
returnArgumentsNoPackage();
if(str == "Str4" && bool == false && num == 40)
{ success = true;}
else
{ success = false;}
Assert.expectEq( "returnArgumentsNoPackage();", true, success );
// displays results.
|
package com.company.assembleegameclient.ui.tooltip.slotcomparisons {
public class GenericArmorComparison extends SlotComparison {
private static const DEFENSE_STAT:String = "21";
public function GenericArmorComparison() {
super();
comparisonText = "";
}
private var defTags:XMLList;
private var otherDefTags:XMLList;
override protected function compareSlots(itemXML:XML, curItemXML:XML):void {
var defense:int = 0;
var otherDefense:int = 0;
this.defTags = itemXML.ActivateOnEquip.(@stat == DEFENSE_STAT);
this.otherDefTags = curItemXML.ActivateOnEquip.(@stat == DEFENSE_STAT);
if (this.defTags.length() == 1 && this.otherDefTags.length() == 1) {
defense = int(this.defTags.@amount);
otherDefense = int(this.otherDefTags.@amount);
processedActivateOnEquipTags[this.defTags[0].toXMLString()] = this.compareDefense(defense, otherDefense);
}
}
private function compareDefense(defense:int, otherDefense:int):String {
var textColor:String = getTextColor(defense - otherDefense);
return wrapInColoredFont("+" + defense + " Defense", textColor);
}
}
}
|
package com.ankamagames.dofus.network.types.game.character
{
import com.ankamagames.jerakine.network.ICustomDataInput;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.INetworkType;
import com.ankamagames.jerakine.network.utils.FuncTree;
public class CharacterMinimalGuildPublicInformations extends CharacterMinimalInformations implements INetworkType
{
public static const protocolId:uint = 3496;
public var rank:uint = 0;
public function CharacterMinimalGuildPublicInformations()
{
super();
}
override public function getTypeId() : uint
{
return 3496;
}
public function initCharacterMinimalGuildPublicInformations(id:Number = 0, name:String = "", level:uint = 0, rank:uint = 0) : CharacterMinimalGuildPublicInformations
{
super.initCharacterMinimalInformations(id,name,level);
this.rank = rank;
return this;
}
override public function reset() : void
{
super.reset();
this.rank = 0;
}
override public function serialize(output:ICustomDataOutput) : void
{
this.serializeAs_CharacterMinimalGuildPublicInformations(output);
}
public function serializeAs_CharacterMinimalGuildPublicInformations(output:ICustomDataOutput) : void
{
super.serializeAs_CharacterMinimalInformations(output);
if(this.rank < 0)
{
throw new Error("Forbidden value (" + this.rank + ") on element rank.");
}
output.writeVarInt(this.rank);
}
override public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_CharacterMinimalGuildPublicInformations(input);
}
public function deserializeAs_CharacterMinimalGuildPublicInformations(input:ICustomDataInput) : void
{
super.deserialize(input);
this._rankFunc(input);
}
override public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_CharacterMinimalGuildPublicInformations(tree);
}
public function deserializeAsyncAs_CharacterMinimalGuildPublicInformations(tree:FuncTree) : void
{
super.deserializeAsync(tree);
tree.addChild(this._rankFunc);
}
private function _rankFunc(input:ICustomDataInput) : void
{
this.rank = input.readVarUhInt();
if(this.rank < 0)
{
throw new Error("Forbidden value (" + this.rank + ") on element of CharacterMinimalGuildPublicInformations.rank.");
}
}
}
}
|
/*
* Servebox ActionScript Foundry / $Id: ServiceLocator.as 81 2007-03-23 16:58:10Z J.F.Mathiot $
*
* Copyright 2006 ServeBox 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.
*/
package org.servebox.cafe.net
{
import mx.logging.ILogger;
import mx.logging.Log;
import mx.rpc.AbstractService;
import org.servebox.cafe.core.util.ClassUtils;
/**
* ServiceLocator holds a reference to services of the application.
*/
public class ServiceLocator
{
/**
* The class logger.
*/
protected static var logger : ILogger = Log.getLogger( ClassUtils.getStandardFullyQualifiedClassName( ServiceLocator ) );
private var servicesAssociativeMap:Object;
/**
* Registers a reference to the service with an id.
* @param id give an id to the service
* @param service instance of the service
*/
public function registerService( id:String, service:AbstractService ) : void
{
if( servicesAssociativeMap[ id ] != undefined )
{
throw new ServiceAlreadyRegisteredError("Service with id "+ id +" has already been registered");
}
servicesAssociativeMap[ id ] = service;
logger.debug( "Service with id " + id + " registered." );
}
/**
* Retrieves the reference to a service.
* @param id give id of the required service
*/
public function getService( id:String ): AbstractService
{
if( servicesAssociativeMap[ id ]==undefined )
{
throw new ServiceNotFoundError("Service with id "+id+" not found.");
}
return servicesAssociativeMap[ id ];
}
///////////////////////////////////////////////////
// Singleton implementation
///////////////////////////////////////////////////
private static var instance : ServiceLocator;
private static var allowInstantiation:Boolean;
public static function getInstance() : ServiceLocator
{
if (instance == null)
{
allowInstantiation = true;
instance = new ServiceLocator();
allowInstantiation = false;
}
return instance;
}
/**
* Creates a new SimpleNotification object.
*/
public function ServiceLocator()
{
if (!allowInstantiation)
{
throw new Error( "allowInstantiation == false this is a singleton ");
}
servicesAssociativeMap = new Object();
}
}
} |
package com.ankamagames.dofus.network.types.game.idol
{
import com.ankamagames.jerakine.network.ICustomDataInput;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.INetworkType;
import com.ankamagames.jerakine.network.utils.FuncTree;
public class PartyIdol extends Idol implements INetworkType
{
public static const protocolId:uint = 563;
public var ownersIds:Vector.<Number>;
private var _ownersIdstree:FuncTree;
public function PartyIdol()
{
this.ownersIds = new Vector.<Number>();
super();
}
override public function getTypeId() : uint
{
return 563;
}
public function initPartyIdol(id:uint = 0, xpBonusPercent:uint = 0, dropBonusPercent:uint = 0, ownersIds:Vector.<Number> = null) : PartyIdol
{
super.initIdol(id,xpBonusPercent,dropBonusPercent);
this.ownersIds = ownersIds;
return this;
}
override public function reset() : void
{
super.reset();
this.ownersIds = new Vector.<Number>();
}
override public function serialize(output:ICustomDataOutput) : void
{
this.serializeAs_PartyIdol(output);
}
public function serializeAs_PartyIdol(output:ICustomDataOutput) : void
{
super.serializeAs_Idol(output);
output.writeShort(this.ownersIds.length);
for(var _i1:uint = 0; _i1 < this.ownersIds.length; _i1++)
{
if(this.ownersIds[_i1] < 0 || this.ownersIds[_i1] > 9007199254740992)
{
throw new Error("Forbidden value (" + this.ownersIds[_i1] + ") on element 1 (starting at 1) of ownersIds.");
}
output.writeVarLong(this.ownersIds[_i1]);
}
}
override public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_PartyIdol(input);
}
public function deserializeAs_PartyIdol(input:ICustomDataInput) : void
{
var _val1:Number = NaN;
super.deserialize(input);
var _ownersIdsLen:uint = input.readUnsignedShort();
for(var _i1:uint = 0; _i1 < _ownersIdsLen; _i1++)
{
_val1 = input.readVarUhLong();
if(_val1 < 0 || _val1 > 9007199254740992)
{
throw new Error("Forbidden value (" + _val1 + ") on elements of ownersIds.");
}
this.ownersIds.push(_val1);
}
}
override public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_PartyIdol(tree);
}
public function deserializeAsyncAs_PartyIdol(tree:FuncTree) : void
{
super.deserializeAsync(tree);
this._ownersIdstree = tree.addChild(this._ownersIdstreeFunc);
}
private function _ownersIdstreeFunc(input:ICustomDataInput) : void
{
var length:uint = input.readUnsignedShort();
for(var i:uint = 0; i < length; i++)
{
this._ownersIdstree.addChild(this._ownersIdsFunc);
}
}
private function _ownersIdsFunc(input:ICustomDataInput) : void
{
var _val:Number = input.readVarUhLong();
if(_val < 0 || _val > 9007199254740992)
{
throw new Error("Forbidden value (" + _val + ") on elements of ownersIds.");
}
this.ownersIds.push(_val);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 mx.messaging.channels.amfx
{
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.IExternalizable;
import flash.utils.describeType;
import flash.xml.XMLDocument;
import mx.logging.Log;
import mx.utils.HexEncoder;
import mx.utils.ObjectProxy;
import mx.utils.ObjectUtil;
[ExcludeClass]
/**
* Serializes an arbitrary ActionScript object graph to an XML
* representation that is based on Action Message Format (AMF)
* version 3.
* @private
*/
public class AMFXEncoder
{
public function AMFXEncoder()
{
super();
settings = {};
settings.prettyPrinting = false;
}
public function encode(obj:Object, headers:Array = null):XML
{
XML.setSettings(settings);
var xml:XML = new XML("<amfx />");
xml.setNamespace(NAMESPACE);
xml.@["ver"] = CURRENT_VERSION;
var context:AMFXContext = new AMFXContext();
context.log = Log.getLogger("mx.messaging.channels.amfx.AMFXEncoder");
encodePacket(xml, obj, headers, context);
return xml;
}
private static function encodePacket(xml:XML, obj:Object, headers:Array = null, context:AMFXContext = null):void
{
if (headers)
encodeHeaders(xml, headers, context);
encodeBody(xml, obj, context);
}
private static function encodeHeaders(xml:XML, headers:Array, context:AMFXContext):void
{
for (var i:uint = 0; i < headers.length; i++)
{
var header:Object = headers[i];
var element:XML = <header />;
element.@["name"] = header.name;
element.@["mustUnderstand"] = (header.mustUnderstand == true);
encodeValue(element, header.content, context);
xml.appendChild(element);
}
}
private static function encodeBody(xml:XML, obj:*, context:AMFXContext):void
{
var element:XML = <body />;
//element.@["targetURI"] = ""; //TODO: Support this attribute
encodeValue(element, obj, context);
xml.appendChild(element);
}
public static function encodeValue(xml:XML, obj:*, context:AMFXContext):void
{
if (obj != null)
{
if (obj is String)
{
encodeString(xml, String(obj), context);
}
else if (obj is Number)
{
encodeNumber(xml, Number(obj));
}
else if (obj is Boolean)
{
encodeBoolean(xml, Boolean(obj));
}
else if (obj is ByteArray)
{
encodeByteArray(xml, ByteArray(obj));
}
else if (obj is Array)
{
encodeArray(xml, obj as Array, context);
}
else if (obj is XML || obj is XMLDocument)
{
encodeXML(xml, obj);
}
else if (obj is Date)
{
encodeDate(xml, obj as Date, context);
}
else if (obj is Class)
{
//TODO: Throw errors for unsupported types?
if (context.log)
context.log.warn("Cannot serialize type Class");
}
else if (obj is Dictionary)
{
encodeDictionary(xml, obj as Dictionary, context);
}
else
{
encodeObject(xml, obj, context);
}
}
else if (obj === undefined)
{
xml.appendChild(X_UNDEFINED.copy());
}
else
{
xml.appendChild(X_NULL.copy());
}
}
private static function encodeArray(xml:XML, array:Array, context:AMFXContext):void
{
var ref:int = context.findObject(array);
var element:XML;
if (ref >= 0)
{
element = <ref />
element.@["id"] = String(ref);
}
else
{
rememberObject(context, array);
element = <array />;
var named:Object = {};
var ordinal:Array = [];
var isECMAArray:Boolean = false;
// Separate named and ordinal array members
for (var member:String in array)
{
if (isNaN(Number(member)))
{
named[member] = array[member];
isECMAArray = true;
}
else
{
var num:int = parseInt(member);
ordinal[num] = array[num];
}
}
// Encode named items as early as possible
for (var n:String in named)
{
encodeArrayItem(element, n, named[n], context);
}
var ordinalLength:uint = 0;
var dense:Boolean = true;
for (var i:uint = 0; i < ordinal.length; i++)
{
var o:* = ordinal[i];
// If we have an undefined slot remaining ordinal
// keys will be converted to named keys to preserve dense set
if (o !== undefined)
{
if (dense)
{
encodeValue(element, o, context);
ordinalLength++;
}
else
{
isECMAArray = true;
encodeArrayItem(element, String(i), o, context);
}
}
else
{
dense = false;
}
}
element.@["length"] = String(ordinalLength);
if (isECMAArray)
{
element.@["ecma"] = "true";
}
}
xml.appendChild(element);
}
private static function encodeArrayItem(xml:XML, name:String, value:*, context:AMFXContext):void
{
var item:XML = <item />;
item.@["name"] = name;
encodeValue(item, value, context);
xml.appendChild(item);
}
private static function encodeBoolean(xml:XML, bool:Boolean):void
{
if (bool)
xml.appendChild(X_TRUE.copy());
else
xml.appendChild(X_FALSE.copy());
}
private static function encodeByteArray(xml:XML, obj:ByteArray):void
{
var element:XML = <bytearray/>;
var encoder:HexEncoder = new HexEncoder();
encoder.encode(obj);
var encoded:String = encoder.flush();
element.appendChild(encoded);
xml.appendChild(element);
}
private static function encodeDate(xml:XML, date:Date, context:AMFXContext):void
{
var ref:int = context.findObject(date);
var element:XML;
if (ref >= 0)
{
element = <ref />
element.@["id"] = String(ref);
}
else
{
rememberObject(context, date);
element = <date />;
element.appendChild(new XML(date.getTime().toString()));
}
xml.appendChild(element);
}
private static function encodeNumber(xml:XML, num:Number):void
{
var element:XML = null;
if (num is int || num is uint)
{
element = <int />;
}
else
{
element = <double />;
}
element.appendChild(new XML(num.toString()));
xml.appendChild(element);
}
private static function encodeDictionary(xml:XML, dict:Dictionary, context:AMFXContext):void
{
var ref:int = context.findObject(dict);
var element:XML;
if (ref >= 0)
{
element = <ref />;
element.@["id"] = String(ref);
}
else
{
rememberObject(context, dict);
element = <dictionary />;
var classInfo:Object = ObjectUtil.getClassInfo(dict, null, CLASS_INFO_OPTIONS);
var properties:Array = classInfo.properties;
var count:uint = properties.length;
for (var i:uint = 0; i < count; i++)
{
var prop:Object = properties[i];
encodeValue(element, prop, context);
encodeValue(element, dict[prop], context);
}
}
element.@["length"] = String(count);
xml.appendChild(element);
}
private static function rememberObject(context:AMFXContext, obj:*):void
{
context.addObject(obj);
}
private static function encodeObject(xml:XML, obj:*, context:AMFXContext):void
{
var ref:int = context.findObject(obj);
var element:XML;
if (ref >= 0)
{
element = <ref />
element.@["id"] = String(ref);
}
else
{
rememberObject(context, obj);
element = <object />;
var classInfo:Object = ObjectUtil.getClassInfo(obj, null, CLASS_INFO_OPTIONS);
var className:String = classInfo.name;
var classAlias:String = classInfo.alias;
var properties:Array = classInfo.properties;
var count:uint = properties.length;
// We need to special case ObjectProxy as for serialization we actually need the
// remote alias of ObjectProxy, not the wrapped object.
if (obj is ObjectProxy)
{
var cinfo:XML = describeType(obj);
className = cinfo.@name.toString();
classAlias = cinfo.@alias.toString();
}
var remoteClassName:String = ((classAlias != null) ? classAlias : className);
if (remoteClassName && remoteClassName != "Object" && remoteClassName != "Array")
{
element.@["type"] = remoteClassName.replace(REGEX_CLASSNAME, ".");
}
if (obj is IExternalizable)
{
classInfo.externalizable = true;
encodeTraits(element, classInfo, context);
var ext:IExternalizable = IExternalizable(obj);
var ba:ByteArray = new ByteArray();
ext.writeExternal(ba);
encodeByteArray(element, ba);
}
else
{
classInfo.externalizable = false;
encodeTraits(element, classInfo, context);
for (var i:uint = 0; i < count; i++)
{
var prop:String = properties[i];
encodeValue(element, obj[prop], context);
}
}
}
xml.appendChild(element);
}
private static function encodeString(xml:XML, str:String, context:AMFXContext, isTrait:Boolean = false):void
{
var ref:int = context.findString(str);
var element:XML = <string />;
if (ref >= 0)
{
element.@["id"] = String(ref);
}
else
{
//Remember string
context.addString(str);
if (str.length > 0)
{
// Traits won't contain chars that need escaping
if (!isTrait)
str = escapeXMLString(str);
var x:XML = new XML(str);
element.appendChild(x);
}
}
xml.appendChild(element);
}
private static function encodeTraits(xml:XML, classInfo:Object, context:AMFXContext):void
{
var element:XML = <traits />;
var ref:int = context.findTraitInfo(classInfo);
if (ref >= 0)
{
element.@["id"] = String(ref);
}
else
{
//Remember trait info
context.addTraitInfo(classInfo)
if (classInfo.externalizable)
{
element.@["externalizable"] = "true";
}
else
{
var properties:Array = classInfo.properties;
if (properties != null)
{
var count:uint = properties.length;
for (var i:uint = 0; i < count; i++)
{
var prop:String = properties[i];
encodeString(element, prop, context, true);
}
}
}
}
xml.appendChild(element);
}
private static function encodeXML(xml:XML, xmlObject:Object):void
{
var element:XML = <xml />;
var str:String;
if (xmlObject is XML)
str = XML(xmlObject).toXMLString();
else
str = xmlObject.toString();
if (str.length > 0)
{
str = escapeXMLString(str);
var x:XML = new XML(str);
element.appendChild(x);
}
xml.appendChild(element);
}
private static function escapeXMLString(str:String):String
{
if (str.length > 0)
{
if ((str.indexOf("<") != -1) || (str.indexOf("&") != -1))
{
if (str.indexOf("]]>") != -1)
{
str = str.replace(REGEX_CLOSE_CDATA, "]]>");
}
str = "<![CDATA[" + str + "]]>";
}
}
return str;
}
private var settings:Object;
public static const CURRENT_VERSION:uint = 3;
public static const NAMESPACE_URI:String = "http://www.macromedia.com/2005/amfx";
public static const NAMESPACE:Namespace = new Namespace("", NAMESPACE_URI);
private static const REGEX_CLASSNAME:RegExp = new RegExp("\\:\\:", "g");
private static const REGEX_CLOSE_CDATA:RegExp = new RegExp("]]>", "g");
private static const CLASS_INFO_OPTIONS:Object = {includeReadOnly:false, includeTransient:false};
private static const X_FALSE:XML = <false />;
private static const X_NULL:XML = <null />;
private static const X_TRUE:XML = <true />;
private static const X_UNDEFINED:XML = <undefined />;
}
}
|
package kabam.rotmg.ui {
import flash.display.Sprite;
public class UIUtils {
private static const NOTIFICATION_BACKGROUND_WIDTH:Number = 95;
private static const NOTIFICATION_BACKGROUND_HEIGHT:Number = 25;
private static const NOTIFICATION_BACKGROUND_ALPHA:Number = 0.4;
private static const NOTIFICATION_BACKGROUND_COLOR:Number = 0;
public static const NOTIFICATION_SPACE:uint = 28;
public static function returnHudNotificationBackground():Sprite {
var background:Sprite = new Sprite();
background.graphics.beginFill(NOTIFICATION_BACKGROUND_COLOR, NOTIFICATION_BACKGROUND_ALPHA);
background.graphics.drawRoundRect(0, 0, NOTIFICATION_BACKGROUND_WIDTH, NOTIFICATION_BACKGROUND_HEIGHT, 12, 12);
background.graphics.endFill();
return background;
}
public function UIUtils() {
super();
}
}
}
|
package com.google.zxing.client.result.optional
{
/*
* Copyright 2008 ZXing authors
*
* 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.
*/
import com.google.zxing.Result;
/**
* <p>Recognizes an NDEF message that encodes information according to the
* "Smart Poster Record Type Definition" specification.</p>
*
* <p>This actually only supports some parts of the Smart Poster format: title,
* URI, and action records. Icon records are not supported because the size
* of these records are infeasibly large for barcodes. Size and type records
* are not supported. Multiple titles are not supported.</p>
*
* @author Sean Owen
*/
public final class NDEFSmartPosterResultParser extends AbstractNDEFResultParser {
public static function parse(result:Result):NDEFSmartPosterParsedResult {
var bytes:Array = result.getRawBytes();
if (bytes == null) {
return null;
}
var headerRecord:NDEFRecord = NDEFRecord.readRecord(bytes, 0);
// Yes, header record starts and ends a message
if (headerRecord == null || !headerRecord.isMessageBegin() || !headerRecord.isMessageEnd()) {
return null;
}
if (headerRecord.getType() != NDEFRecord.SMART_POSTER_WELL_KNOWN_TYPE) {
return null;
}
var offset:int = 0;
var recordNumber:int = 0;
var ndefRecord:NDEFRecord = null;
var payload:Array = headerRecord.getPayload();
var action:int = NDEFSmartPosterParsedResult.ACTION_UNSPECIFIED;
var title:String = null;
var uri:String = null;
while (offset < payload.length && (ndefRecord = NDEFRecord.readRecord(payload, offset)) != null) {
if (recordNumber == 0 && !ndefRecord.isMessageBegin()) {
return null;
}
var type:String = ndefRecord.getType();
if (NDEFRecord.TEXT_WELL_KNOWN_TYPE == type) {
var languageText:Array = NDEFTextResultParser.decodeTextPayload(ndefRecord.getPayload());
title = languageText[1];
} else if (NDEFRecord.URI_WELL_KNOWN_TYPE == type) {
uri = NDEFURIResultParser.decodeURIPayload(ndefRecord.getPayload());
} else if (NDEFRecord.ACTION_WELL_KNOWN_TYPE == type) {
action = ndefRecord.getPayload()[0];
}
recordNumber++;
offset += ndefRecord.getTotalRecordLength();
}
if (recordNumber == 0 || (ndefRecord != null && !ndefRecord.isMessageEnd())) {
return null;
}
return new NDEFSmartPosterParsedResult(action, uri, title);
}
}
} |
/*
Copyright (c) 2011 Jonnie Hallman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.destroytoday.hotkey
{
import org.osflash.signals.Signal;
public interface IHotkey
{
function get executed():Signal;
function set executed(value:Signal):void;
function get enabled():Boolean;
function set enabled(value:Boolean):void;
function get combination():String;
function set combination(value:String):void;
function execute():void;
}
} |
package asunit.runner {
public class Version {
private static var version:String = "3.0";
public static function id():String {
return version.toString();
}
}
} |
package de.viaboxx.flexboxx {
import org.flexunit.assertThat;
import org.hamcrest.object.equalTo;
[RunWith("org.flexunit.runners.Parameterized")]
public class FormatHexTest {
public function FormatHexTest() {
//empty constructor
}
public static function colors():Array {
return [
[0, "0x000000"],
[0xFF0000, "0xFF0000"],
[0xFF2300, "0xFF2300"],
[0x000001, "0x000001"],
[0x0000FF, "0x0000FF"]
];
}
[Test(dataProvider="colors")]
public function colorString(color:uint, expected:String):void {
assertThat(formatHex(color), equalTo(expected));
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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 mx.charts
{
import mx.charts.chartClasses.CartesianChart;
import mx.charts.chartClasses.DataTip;
import mx.charts.chartClasses.DataTransform;
import mx.charts.chartClasses.IAxis;
import mx.charts.chartClasses.Series;
import mx.charts.series.AreaSeries;
import mx.charts.series.AreaSet;
import mx.charts.styles.HaloDefaults;
import mx.core.IFlexModuleFactory;
import mx.core.mx_internal;
import mx.graphics.IFill;
import mx.graphics.SolidColor;
import mx.graphics.SolidColorStroke;
import mx.graphics.Stroke;
import mx.styles.CSSStyleDeclaration;
use namespace mx_internal;
[DefaultBindingProperty(destination="dataProvider")]
[DefaultTriggerEvent("itemClick")]
//[IconFile("AreaChart.png")]
/**
* The AreaChart control represents data as an area
* bounded by a line connecting the values in the data.
* The AreaChart control can be used to represent different variations,
* including simple areas, stacked, 100% stacked, and high/low.
*
* <p>The AreaChart control expects its <code>series</code> property
* to contain an Array of AreaSeries objects.</p>
*
* <p>Stacked and 100% area charts override the <code>minField</code>
* property of their AreaSeries objects.</p>
*
* @mxml
*
* <p>The <code><mx:AreaChart></code> tag inherits all the properties
* of its parent classes, and adds the following properties:</p>
*
* <pre>
* <mx:AreaChart
* <strong>Properties</strong>
* type="<i>overlaid|stacked|100%</i>"
* />
* </pre>
*
* @includeExample examples/Line_AreaChartExample.mxml
*
* @see mx.charts.series.AreaSeries
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class AreaChart extends CartesianChart
{
// include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class initialization
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function AreaChart()
{
super();
LinearAxis(horizontalAxis).autoAdjust = false;
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
// private static var _moduleFactoryInitialized:Dictionary = new Dictionary(true);
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// horizontalAxis
//----------------------------------
[Inspectable(category="Data")]
/**
* @private
*/
override public function set horizontalAxis(value:IAxis):void
{
if (value is CategoryAxis)
CategoryAxis(value).padding = 0;
super.horizontalAxis = value;
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// type
//----------------------------------
/**
* @private
* Storage for the type property.
*/
private var _type:String = "overlaid";
[Inspectable(category="General", enumeration="overlaid,stacked,100%", defaultValue="overlaid")]
/**
* Type of area chart to render.
*
* <p>Possible values are:</p>
* <ul>
* <li><code>"overlaid"</code>:
* Multiple areas are rendered on top of each other,
* with the last series specified on top.
* This is the default value.</li>
* <li><code>"stacked"</code>:
* Areas are stacked on top of each other and grouped by category.
* Each area represents the cumulative value
* of the areas beneath it.</li>
* <li><code>"100%"</code>:
* Areas are stacked on top of each other, adding up to 100%.
* Each area represents the percent that series contributes
* to the sum of the whole.</li>
* </ul>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get type():String
{
return _type;
}
/**
* @private
*/
public function set type(value:String):void
{
_type = value;
invalidateSeries();
invalidateData();
}
//--------------------------------------------------------------------------
//
// Overridden methods: UIComponent
//
//--------------------------------------------------------------------------
/**
* @private
*/
private function initStyles():Boolean
{
HaloDefaults.init(styleManager);
var areaChartSeriesStyles:Array /* of Object */ = [];
var n:int = HaloDefaults.defaultFills.length;
for (var i:int = 0; i < n; i++)
{
var styleName:String = "haloAreaSeries" + i;
areaChartSeriesStyles[i] = styleName;
var o:CSSStyleDeclaration =
HaloDefaults.createSelector("." + styleName, styleManager);
var f:Function = function(o:CSSStyleDeclaration, stroke:Stroke,
fill:IFill):void
{
o.defaultFactory = function():void
{
this.areaFill = fill;
this.fill = fill;
}
}
f(o, null, HaloDefaults.defaultFills[i]);
}
var areaChartStyle:CSSStyleDeclaration = HaloDefaults.findStyleDeclaration(styleManager, "mx.charts.AreaChart");
if (areaChartStyle)
{
areaChartStyle.setStyle("chartSeriesStyles", areaChartSeriesStyles);
areaChartStyle.setStyle("fill", new SolidColor(0xFFFFFF, 0));
areaChartStyle.setStyle("calloutStroke", new SolidColorStroke(0x888888,2));
areaChartStyle.setStyle("horizontalAxisStyleNames", ["hangingCategoryAxis"]);
areaChartStyle.setStyle("verticalAxisStyleNames", ["blockNumericAxis"]);
}
return true;
}
/**
* A module factory is used as context for using embedded fonts and for finding the style manager that controls the styles for this component.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function set moduleFactory(factory:IFlexModuleFactory):void
{
super.moduleFactory = factory;
/*
if (_moduleFactoryInitialized[factory])
return;
_moduleFactoryInitialized[factory] = true;
*/
// our style settings
initStyles();
}
//--------------------------------------------------------------------------
//
// Overridden methods: ChartBase
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function customizeSeries(seriesGlyph:Series,
i:uint):void
{
var aSeries:AreaSeries = seriesGlyph as AreaSeries;
if (aSeries)
{
aSeries.stacker = null;
aSeries.stackTotals = null;
}
}
/**
* @private
*/
override protected function applySeriesSet(seriesSet:Array /* of Series */,
transform:DataTransform):Array /* of Series */
{
switch (_type)
{
case "stacked":
case "100%":
{
var newSeriesGlyph:AreaSet = new AreaSet();
newSeriesGlyph.series = seriesSet;
newSeriesGlyph.type = _type;
return [ newSeriesGlyph ];
}
case "overlaid":
default:
{
return super.applySeriesSet(seriesSet, transform);
}
}
}
}
}
|
package
{
public class MainClass
{
public static function Main():void
{
trace("Hello World from ActionScript!");
}
}
}
|
// makeswf -v 7 -s 200x150 -r 1 -o BlurFilter-construct.swf BlurFilter-construct.as
#include "values.as"
trace_filter = function (filter, name) {
trace (name + ": " + filter.blurX + " / " + filter.blurY + " / " + filter.quality);
};
check = function (val, name) {
if (arguments.length < 2)
name = val;
var filter = new flash.filters.BlurFilter (val, val, val);
trace_filter (filter, name);
};
trace_filter (new flash.filters.BlurFilter (), "0 args");
trace_filter (new flash.filters.BlurFilter (1), "1 arg");
trace_filter (new flash.filters.BlurFilter (1, 2), "2 args");
trace_filter (new flash.filters.BlurFilter (1, 2, 3), "3 args");
trace_filter (flash.filters.BlurFilter (1, 2, 3), "no new");
for (i = 0; i < values.length; i++) {
check (values[i], names[i]);
};
check (-0.2);
check (255.125);
check (15.125);
trace (flash.filters.BlurFilter (1, 2, 3));
filter = new flash.filters.BlurFilter (1, 2, 3);
trace_filter (filter);
flash.filters.BlurFilter.apply (filter);
trace_filter (filter);
getURL ("fscommand:quit", "");
|
package org.papervision3d.core.animation.channel.geometry
{
import org.papervision3d.core.animation.channel.Channel3D;
import org.papervision3d.core.geom.renderables.Vertex3D;
import org.papervision3d.core.proto.GeometryObject3D;
/**
* The VertexChannel3D class animates a single vertex in a GeometryObject3D.
*
* <p>You can animate a single property of the vertex ("x", "y" or "z"), or alternatively
* you can animate all 3 properties of the vertex.</p>
*
* @see org.papervision3d.core.animation.channel.Channel3D
* @see org.papervision3d.core.proto.GeometryObject3D
* @see org.papervision3d.core.geom.renderables.Vertex3D
*
* @author Tim Knip / floorplanner.com
*/
public class VertexChannel3D extends GeometryChannel3D
{
public static const TARGET_X : int = 0;
public static const TARGET_Y : int = 1;
public static const TARGET_Z : int = 2;
public static const TARGET_XYZ : int = -1;
/**
* The index of the targeted vertex.
*/
public var vertexIndex : uint;
/**
* The targeted property of the targeted vertex.
* Possible values are #TARGET_X, #TARGET_Y, #TARGET_Z or #TARGET_XYZ
*/
public var vertexProperty : int;
/**
*
*/
protected var _clone : GeometryObject3D;
/**
* Constructor
*/
public function VertexChannel3D(geometry : GeometryObject3D, vertexIndex : uint, vertexProperty : int = -1)
{
super(geometry);
this.vertexIndex = vertexIndex;
this.vertexProperty = vertexProperty;
}
/**
*
*/
override public function update(time : Number) : void
{
if(!_curves || !_geometry || !_clone)
{
return;
}
super.update(time);
var o : Vertex3D = _clone.vertices[vertexIndex];
var t : Vertex3D = _geometry.vertices[vertexIndex];
var numCurves : int = _curves.length;
if(vertexProperty == TARGET_XYZ && numCurves == 3)
{
t.x = o.x + output[0];
t.y = o.y + output[1];
t.z = o.z + output[2];
}
else if(numCurves == 1)
{
var prop : String = vertexProperty == 0 ? "x" : (vertexProperty == 1 ? "y" : "z");
t[prop] = o[prop] + output[0];
}
}
/**
*
*/
override public function set geometry(value : GeometryObject3D) : void
{
super.geometry = value;
if(_geometry && _geometry.vertices && _geometry.vertices.length)
{
_clone = _geometry.clone();
}
}
}
}
|
/*
* Copyright(c) 2007 the Spark project.
*
* 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.
*/
package org.libspark.swfassist.swf.tags
{
import flash.utils.ByteArray;
public class DefineBinaryData extends AbstractTag
{
public function DefineBinaryData(code:uint = 0)
{
super(code != 0 ? code : TagCodeConstants.TAG_DEFINE_BINARY_DATA);
}
private var _characterId:uint = 0;
private var _data:ByteArray = new ByteArray();
public function get characterId():uint
{
return _characterId;
}
public function set characterId(value:uint):void
{
_characterId = value;
}
public function get data():ByteArray
{
return _data;
}
public function set data(value:ByteArray):void
{
_data = value;
}
public override function visit(visitor:TagVisitor):void
{
visitor.visitDefineBinaryData(this);
}
}
} |
package laya.ui {
import laya.events.Event;
import laya.net.Loader;
import laya.resource.Texture;
import laya.ui.AutoBitmap;
import laya.ui.Component;
import laya.ui.UIUtils;
import laya.utils.Handler;
/**
* 资源加载完成后调度。
* @eventType Event.LOADED
*/
[Event(name = "loaded", type = "laya.events.Event")]
/**
* <code>Image</code> 类是用于表示位图图像或绘制图形的显示对象。
* Image和Clip组件是唯一支持异步加载的两个组件,比如img.skin = "abc/xxx.png",其他UI组件均不支持异步加载。
*
* @example <caption>以下示例代码,创建了一个新的 <code>Image</code> 实例,设置了它的皮肤、位置信息,并添加到舞台上。</caption>
* package
* {
* import laya.ui.Image;
* public class Image_Example
* {
* public function Image_Example()
* {
* Laya.init(640, 800);//设置游戏画布宽高。
* Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。
* onInit();
* }
* private function onInit():void
* {
* var bg:Image = new Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。
* bg.x = 100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。
* bg.y = 100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。
* bg.sizeGrid = "40,10,5,10";//设置 bg 对象的网格信息。
* bg.width = 150;//设置 bg 对象的宽度。
* bg.height = 250;//设置 bg 对象的高度。
* Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。
* var image:Image = new Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。
* image.x = 100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。
* image.y = 100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。
* Laya.stage.addChild(image);//将此 image 对象添加到显示列表。
* }
* }
* }
* @example
* Laya.init(640, 800);//设置游戏画布宽高
* Laya.stage.bgColor = "#efefef";//设置画布的背景颜色
* onInit();
* function onInit() {
* var bg = new laya.ui.Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。
* bg.x = 100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。
* bg.y = 100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。
* bg.sizeGrid = "40,10,5,10";//设置 bg 对象的网格信息。
* bg.width = 150;//设置 bg 对象的宽度。
* bg.height = 250;//设置 bg 对象的高度。
* Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。
* var image = new laya.ui.Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。
* image.x = 100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。
* image.y = 100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。
* Laya.stage.addChild(image);//将此 image 对象添加到显示列表。
* }
* @example
* class Image_Example {
* constructor() {
* Laya.init(640, 800);//设置游戏画布宽高。
* Laya.stage.bgColor = "#efefef";//设置画布的背景颜色。
* this.onInit();
* }
* private onInit(): void {
* var bg: laya.ui.Image = new laya.ui.Image("resource/ui/bg.png");//创建一个 Image 类的实例对象 bg ,并传入它的皮肤。
* bg.x = 100;//设置 bg 对象的属性 x 的值,用于控制 bg 对象的显示位置。
* bg.y = 100;//设置 bg 对象的属性 y 的值,用于控制 bg 对象的显示位置。
* bg.sizeGrid = "40,10,5,10";//设置 bg 对象的网格信息。
* bg.width = 150;//设置 bg 对象的宽度。
* bg.height = 250;//设置 bg 对象的高度。
* Laya.stage.addChild(bg);//将此 bg 对象添加到显示列表。
* var image: laya.ui.Image = new laya.ui.Image("resource/ui/image.png");//创建一个 Image 类的实例对象 image ,并传入它的皮肤。
* image.x = 100;//设置 image 对象的属性 x 的值,用于控制 image 对象的显示位置。
* image.y = 100;//设置 image 对象的属性 y 的值,用于控制 image 对象的显示位置。
* Laya.stage.addChild(image);//将此 image 对象添加到显示列表。
* }
* }
* @see laya.ui.AutoBitmap
*/
public class Image extends Component {
/**@private */
public var _bitmap:AutoBitmap;
/**@private */
protected var _skin:String;
/**@private */
protected var _group:String;
/**
* 创建一个 <code>Image</code> 实例。
* @param skin 皮肤资源地址。
*/
public function Image(skin:String = null) {
this.skin = skin;
}
/**@inheritDoc */
override public function destroy(destroyChild:Boolean = true):void {
super.destroy(true);
_bitmap && _bitmap.destroy();
_bitmap = null;
}
/**
* 销毁对象并释放加载的皮肤资源。
*/
public function dispose():void {
destroy(true);
Laya.loader.clearRes(_skin);
}
/**@inheritDoc */
override protected function createChildren():void {
graphics = _bitmap = new AutoBitmap();
_bitmap.autoCacheCmd = false;
}
/**
* <p>对象的皮肤地址,以字符串表示。</p>
* <p>如果资源未加载,则先加载资源,加载完成后应用于此对象。</p>
* <b>注意:</b>资源加载完成后,会自动缓存至资源库中。
*/
public function get skin():String {
return _skin;
}
public function set skin(value:String):void {
if (_skin != value) {
_skin = value;
if (value) {
var source:Texture = Loader.getRes(value);
if (source) {
this.source = source;
onCompResize();
} else Laya.loader.load(_skin, Handler.create(this, setSource, [_skin]), null, Loader.IMAGE,1,true,_group);
} else {
this.source = null;
}
}
}
/**
* @copy laya.ui.AutoBitmap#source
*/
public function get source():Texture {
return _bitmap.source;
}
public function set source(value:*):void {
if (!_bitmap) return;
_bitmap.source = value;
event(Event.LOADED);
repaint();
}
/**
* 资源分组。
*/
public function get group():String
{
return _group;
}
public function set group(value:String):void
{
if (value && _skin) Loader.setGroup(_skin, value);
_group = value;
}
/**
* @private
* 设置皮肤资源。
*/
protected function setSource(url:String, img:*=null):void {
if (url === _skin && img) {
this.source = img
onCompResize();
}
}
/**@inheritDoc */
override protected function get measureWidth():Number {
return _bitmap.width;
}
/**@inheritDoc */
override protected function get measureHeight():Number {
return _bitmap.height;
}
/**@inheritDoc */
override public function set width(value:Number):void {
super.width = value;
_bitmap.width = value == 0 ? 0.0000001 : value;
}
/**@inheritDoc */
override public function set height(value:Number):void {
super.height = value;
_bitmap.height = value == 0 ? 0.0000001 : value;
}
/**
* <p>当前实例的位图 <code>AutoImage</code> 实例的有效缩放网格数据。</p>
* <p>数据格式:"上边距,右边距,下边距,左边距,是否重复填充(值为0:不重复填充,1:重复填充)",以逗号分隔。
* <ul><li>例如:"4,4,4,4,1"。</li></ul></p>
* @see laya.ui.AutoBitmap#sizeGrid
*/
public function get sizeGrid():String {
if (_bitmap.sizeGrid) return _bitmap.sizeGrid.join(",");
return null;
}
public function set sizeGrid(value:String):void {
_bitmap.sizeGrid = UIUtils.fillArray(Styles.defaultSizeGrid, value, Number);
}
/**@inheritDoc */
override public function set dataSource(value:*):void {
_dataSource = value;
if (value is String) skin = value;
else super.dataSource = value;
}
}
} |
package com.playfab.AdminModels
{
public class RevokeInventoryItemsRequest
{
public var Items:Vector.<RevokeInventoryItem>;
public function RevokeInventoryItemsRequest(data:Object=null)
{
if(data == null)
return;
if(data.Items) { Items = new Vector.<RevokeInventoryItem>(); for(var Items_iter:int = 0; Items_iter < data.Items.length; Items_iter++) { Items[Items_iter] = new RevokeInventoryItem(data.Items[Items_iter]); }}
}
}
}
|
package vzw.controls.Alert {
import mx.controls.Alert;
public class AlertPopUp extends Alert {
private static const chars_per_line:int = 32;
[Embed(source="alert_error.gif")]
private static var iconError:Class;
[Embed(source="alert_info.gif")]
private static var iconInfo:Class;
[Embed(source="alert_confirm.gif")]
private static var iconConfirm:Class;
private static var spaces:String = " ";
private static function formatText(s:String):String {
var t:String = "";
var tx:String = "";
var i:int;
var ch:String;
var _ch:uint;
return s; // come back to this later - turn the string into an array and then walk the array inserting "\n" where appropriate...
for (i = 0; i < s.length; i++) {
ch = s.charAt(i);
_ch = s.charCodeAt(i);
if (_ch < 32) {
t += " ";
continue;
}
if (t.length >= chars_per_line) {
_ch = s.charCodeAt(t.length - 1);
if ( (_ch > 32) && (_ch < 127) ) {
_ch = t.charCodeAt(t.length - 1);
for (; ( (i > 0) && ( (_ch > 32) && (_ch < 127) ) ); i--) {
ch = s.charAt(t.length - 1);
_ch = t.charCodeAt(t.length - 1);
t = t.substring(0,t.length - 1)
}
t += "\n";
tx += t;
t = "";
}
}
t += ch;
}
return "\n" + tx;
}
public static function infoNoOkay(message:String, title:String = "Information", closehandler:Function=null):Alert {
var popup:Alert = show("\n\n" + formatText(message), spaces + title, 0, null, closehandler, iconInfo);
return popup;
}
public static function info(message:String, title:String = "Information", closehandler:Function=null):Alert {
var popup:Alert = show("\n\n" + formatText(message), spaces + title, Alert.OK, null, closehandler, iconInfo);
return popup;
}
public static function errorNoOkay(message:String, title:String = "Error", parent:*=null, closehandler:Function=null):Alert {
var popup:Alert = show("\n\n" + formatText(message), spaces + title, 0, parent, closehandler, iconError);
return popup;
}
public static function error(message:String, title:String = "Error", closehandler:Function=null):Alert {
var popup:Alert = show("\n\n" + formatText(message), spaces + title, Alert.OK, null, closehandler, iconError);
return popup;
}
public static function confirm(message:String, title:String = "Confirmation", closehandler:Function=null, okLabel:String=null, cancelLabel:String=null):Alert {
var isOkayUsed:Boolean = false;
if ( (okLabel is String) && (okLabel.length > 0) ) {
isOkayUsed = true;
Alert.okLabel = okLabel;
}
var isCancelUsed:Boolean = false;
if ( (cancelLabel is String) && (cancelLabel.length > 0) ) {
isCancelUsed = true;
Alert.cancelLabel = cancelLabel;
}
var popup:Alert = show("\n\n" + formatText(message), spaces + title, ((isOkayUsed) ? Alert.OK : Alert.YES) | ((isCancelUsed) ? Alert.CANCEL : Alert.NO), null, closehandler, iconConfirm);
return popup;
}
public function AlertPopUp() {
super();
}
}
} |
# Declare a degenerate enumerations.
enum Suit { Clubs, Diamonds, Hearts, Spades }
# Declare a degenerate enumeration where we specify the
# discriminator value manually.
enum Chemical { Hydrogen = 1, Oxygen = 2, Water = 3 }
# Declare a degenerate enumeration where we specify the
# discriminator type manually (it would normally default to
# an integral type large enough to fit all values).
enum Color: int128 { Red, Green, Blue }
# Declare some tagged unions.
enum Option { Some(int), None }
enum Result { Ok(int), Error(int) }
enum List { Nil, Cons(int, List = Nil) }
enum Tree { Leaf, Node(int, Tree = Leaf, Tree = Leaf) }
# Declare some unions with type parameters.
enum Option<T> { Some(T), None }
enum Result<T, E> { Ok(T), Error(E) }
|
package raix.reactive
{
import raix.reactive.ICancelable;
internal class ClosureCancelable implements ICancelable
{
private var _unsubscribeFunc : Function;
private var _isUnsubscribed : Boolean = false;
public function ClosureCancelable(unsubscribeFunc : Function)
{
_unsubscribeFunc = unsubscribeFunc;
}
public function cancel() : void
{
if (!_isUnsubscribed)
{
_isUnsubscribed = true;
_unsubscribeFunc();
}
}
public static function empty() : ClosureCancelable
{
return new ClosureCancelable(function():void{});
}
}
} |
package com.somerandomdude.colortoolkit.schemes
{
import com.somerandomdude.colortoolkit.ColorUtil;
import com.somerandomdude.colortoolkit.spaces.HSB;
public class Compound extends ColorWheelScheme implements IColorScheme
{
public function Compound(primaryColor:int)
{
super(primaryColor);
}
override protected function generate() : void
{
var _primaryHSB:HSB = new HSB();
_primaryHSB.color = _primaryColor;
var c1:HSB = new HSB();
c1.color = ColorUtil.rybRotate(_primaryColor,30);
c1.brightness = wrap(_primaryHSB.brightness,25,60,25);
_colors.push(c1.color);
var c2:HSB = new HSB();
c2.color = ColorUtil.rybRotate(_primaryColor,30);
c2.brightness = wrap(_primaryHSB.brightness,40,10,40);
c2.saturation = wrap(_primaryHSB.saturation,40,20,40);
_colors.push(c2.color);
var c3:HSB = new HSB();
c3.color = ColorUtil.rybRotate(_primaryColor,160);
c3.brightness = Math.max(20,_primaryHSB.brightness);
c3.saturation = wrap(_primaryHSB.saturation,25,10,25);
_colors.push(c3.color);
var c4:HSB = new HSB();
c4.color = ColorUtil.rybRotate(_primaryColor,150);
c4.brightness = wrap(_primaryHSB.brightness,30,60,30);
c4.saturation = wrap(_primaryHSB.saturation,10,80,10);
_colors.push(c4.color);
var c5:HSB = new HSB();
c5.color = ColorUtil.rybRotate(_primaryColor,150);
c5.brightness = wrap(_primaryHSB.brightness,40,20,40);
c5.saturation = wrap(_primaryHSB.saturation,10,80,10);
_colors.push(c5.color);
}
}
}
|
package com.axiomalaska.charts.base
{
import com.axiomalaska.charts.scale.IScale;
import com.axiomalaska.charts.skins.graphical_elements.AxiomChartGraphicalElement;
import flash.geom.Point;
import mx.core.IVisualElement;
public interface IAxiomChartElement extends IVisualElement
{
function set graphicalElement($graphicalElement:AxiomChartGraphicalElement):void;
function get graphicalElement():AxiomChartGraphicalElement;
function set chartContainer($chartContainer:IAxiomChartContainer):void;
function get chartContainer():IAxiomChartContainer;
function get plottableItems():Vector.<AxiomChartPlottableItem>;
function invalidate():void;
function beforeRedraw():void;
function redraw():void;
function afterRedraw():void;
function buildPlottableItems():void;
function getPointAtValue($xAxisValue:Number,$yAxisValue:Number):Point;
function getXAxisValueAtPoint($point:Point):Number;
function getYAxisValueAtPoint($point:Point):Number;
function getNearestPlottableItem($point:Point):AxiomChartPlottableItem;
function createPlottableItem($object:Object,$point:Point = null,$label:String = null,$description:String = null):AxiomChartPlottableItem;
function addPlottableItem($plottableItem:AxiomChartPlottableItem):void;
function removePlottableItemAt($index:int):void;
function removePlottableItem($plottableItem:AxiomChartPlottableItem):void;
function getPlottableItemAt($index:int):AxiomChartPlottableItem;
function getPlottableItemIndex($plottableItem:AxiomChartPlottableItem):int;
function getPlottableItems():Vector.<AxiomChartPlottableItem>;
function setPlottableItems($plottableItems:Vector.<AxiomChartPlottableItem>):void;
}
} |
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package sh.saqoo.format.fbx
{
/**
*
*
*/
public class FBXParseError extends Error
{
/** The location in the string where the error occurred */
private var _location:int;
/** The string in which the parse error occurred */
private var _text:String;
/**
* Constructs a new JSONParseError.
*
* @param message The error message that occured during parsing
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function FBXParseError( message:String = "", location:int = 0, text:String = "" )
{
super( message );
name = "FBXParseError";
_location = location;
_text = text;
}
/**
* Provides read-only access to the location variable.
*
* @return The location in the string where the error occurred
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function get location():int
{
return _location;
}
/**
* Provides read-only access to the text variable.
*
* @return The string in which the error occurred
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function get text():String
{
return _text;
}
}
}
|
package {
import flash.events.Event;
import flash.display.MovieClip;
public class ArrowClass {
public function ArrowClass(dir:Number) {
}
}
}
|
package interfaces.skin
{
import spark.components.Label;
import spark.components.supportClasses.StyleableTextField;
import spark.skins.mobile.ButtonSkin;
public class ValueButtonSkin extends ButtonSkin
{
public var valueDisplay:Label;
//----------------------
// Constructor
//----------------------
public function ValueButtonSkin()
{
super();
}
//----------------------
// Methods
//----------------------
override protected function createChildren():void
{
super.createChildren();
valueDisplay = new Label();
valueDisplay.id = "valueDisplay";
valueDisplay.setStyle("textAlign", "right");
valueDisplay.setStyle("verticalAlign", "middle");
this.addChild(valueDisplay);
labelDisplayShadow.visible = false;
}
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
labelDisplay.x = 20;
setElementSize(valueDisplay, unscaledWidth / 2, labelDisplay.height);
setElementPosition(valueDisplay, unscaledWidth - valueDisplay.width - 20, labelDisplay.y);
}
}
}
|
package view.scene.shop
{
import flash.display.*;
import flash.filters.*;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.Dictionary;
import flash.filters.DropShadowFilter;
import flash.geom.*;
import mx.core.UIComponent;
import mx.core.ClassFactory;
import mx.containers.*;
import mx.controls.*;
import mx.collections.ArrayCollection;
import org.libspark.thread.*;
import org.libspark.thread.utils.*;
import org.libspark.thread.threads.between.BeTweenAS3Thread;
import model.*;
import model.events.*;
import view.image.common.AvatarItemImage;
import view.image.shop.*;
import view.image.item.*;
import view.scene.common.*;
import view.scene.item.PartInventoryClip;
import view.scene.BaseScene;
import view.scene.ModelWaitShowThread;
import view.*;
import view.utils.*;
import controller.LobbyCtrl;
import controller.*;
/**
* ShopBodyListPanelの表示クラス
*
*/
public class ShopBodyListPanel extends ShopItemListPanel
{
// アイテムパネル
private var _shopInventoryPanelImage:ShopInventoryPanelImage = new ShopInventoryPanelImage(AvatarPart.PARTS_BODY_TYPE);
/**
* コンストラクタ
*
*/
public function ShopBodyListPanel(shopID:int =0)
{
super(shopID);
}
public override function init():void
{
super.init();
ctrl.addEventListener(AvatarPartEvent.GET_PART, getAvatarPartSuccessHandler);
}
public override function final():void
{
super.final();
ctrl.removeEventListener(AvatarPartEvent.GET_PART, getAvatarPartSuccessHandler);
}
override protected function get tabTypes():Array
{
return AvatarPart.PARTS_BODY_TYPE;
}
override protected function getItemTypeIdx(i:int):int
{
return i;
}
protected override function get itemInventoryPanelImage():BasePanelImage
{
return _shopInventoryPanelImage;
}
protected override function imageDicFinal():void
{
for (var key:Object in _imageDic) {
RemoveChild.apply(_imageDic[key]);
_imageDic[key].final();
delete _imageDic[key];
}
}
// インベントリからデータを生成する
override protected function inventoryToData():void
{
var i:int;
var itemNum:int = 0; // アイテムの個数
var items:Array = Shop.ID(_shopID).bodyPartsList;
var prices:Array = Shop.ID(_shopID).bodyPartsPriceList;
var coins:Array = Shop.ID(_shopID).bodyPartsCoinList;
var part:AvatarPart;
log.writeLog(log.LV_INFO, this, "items", items);
log.writeLog(log.LV_INFO, this, "price", prices);
// データプロバイダーにタイプごとのアイテムを設定する
for(i = 0; i < items.length; i++)
{
part = items[i];
if (part && !checkPremiumCoin(coins[part.id]))
{
// アイテムのイメージを作成
setItem(part);
// アイテムの個数をインクリメント
_itemDic[part].price = prices[part.id];
_itemDic[part].coins = coins[part.id];
_dpList[part.type-AvatarPart.PARTS_GENRE_ID[part.genre]].push(_itemDic[part]);
_itemDic[part].getUpdateCount();
}
}
}
// DicにAvatarItemを格納
override protected function setItem(item:*):void
{
if (_itemDic[item] == null)
{
_itemDic[item] = new ShopPartInventoryClip(item);
}
}
// DicにAvatarItemを格納
protected override function getImage(item:*):DisplayObject
{
if (_imageDic[item] == null)
{
_imageDic[item] = new AvatarPartIcon(item);
}
return _imageDic[item];
}
protected override function createSelectItemImage():void
{
// 選択中のアイテムのイメージ
// _selectImage = new AvatarItemImage(_selectItem.avatarItem.image, _selectItem.avatarItem.imageFrame);
log.writeLog(log.LV_FATAL, this, "CLICK!!!!!!!!!!!!!!!!!!!");
_selectImage = getImage(_selectItem.avatarPart);
// Unlight.GCW.watch(_selectImage);
log.writeLog(log.LV_FATAL, this, "selectimagecreate",_selectImage);
_selectImage.x = 320;
_selectImage.y = 416;
_selectImage.scaleX = _selectImage.scaleY = 1.0;
// _selectImage.x = 341;
// _selectImage.y = 420;
// _selectImage.scaleX = _selectImage.scaleY = 0.5;
_container.addChild(_selectImage);
// BaseScene(_selectImage).getShowThread(_container).start();
_selectImage.visible = true;
log.writeLog(log.LV_FATAL, this, "selectimagecreate",_selectImage);
_selectItemName.text = _selectItem.avatarPart.name;
_selectItemCountA.text = int(_selectItem.count+1).toString();
_selectItemCountB.text = _selectItem.count.toString();
if(_selectItem.avatarPart.duration==0)
{
_selectItemTime.text = "-";
}else{
_selectItemTime.text = TimeFormat.toDateString(_selectItem.avatarPart.duration);
}
_selectItemTiming.text = "-";
_selectItemCaption.text = _selectItem.avatarPart.caption;
log.writeLog(log.LV_FATAL, this, "selectimagecreate,onuse");
if(_selectItem.count == 0)
{
itemInventoryPanelImage.onUse();
}else{
itemInventoryPanelImage.offUse();
}
_beforeGems.text = _avatar.gems.toString();
_afterGems.text = _avatar.gems-_selectItem.price < 0 ? String(_avatar.gems-_selectItem.price) : (_avatar.gems-_selectItem.price).toString();
_afterGems.styleName = _avatar.gems-_selectItem.price < 0 ? "ShopGemsNumericRed" : _selectItem.price > 0 ? "ShopGemsNumericYellow" : "ShopGemsNumeric";
// モンスターコイン
for(var i:int = 0; i < _selectItem.coins.length; i++)
{
coinCalc(_beforeCoins[i], _afterCoins[i], CharaCardDeck.binder.sortCharaCardId(Const.COIN_SET[i]), _selectItem.coins[i]);
}
}
// アイテムがかわれた時のハンドラ
override protected function buyItemHandler(e:Event):void
{
SE.playClick();
_buySendPanel.selectVisible = false;
// 確認パネルを出す
_buySendPanel.visible = true;
_container.mouseChildren = false;
_container.mouseEnabled = false;
}
// アイテム購入ハンドラ
override protected function pushBuyYesHandler(e:MouseEvent):void
{
// // アイテムを購入
// _lobbyCtrl.buyItem(_shopID, _selectItem.card.id);
_lobbyCtrl.buyPart(_shopID, _selectItem.avatarPart.id);
_buySendPanel.visible = false;
_container.mouseChildren = true;
_container.mouseEnabled = true;
}
// アイテム購入キャンセル
private function pushBuyNoHandler(e:MouseEvent):void
{
_buySendPanel.visible = false;
_container.mouseChildren = true;
_container.mouseEnabled = true;
}
// アイテム購入に成功した時のイベント
protected function getAvatarPartSuccessHandler(e:AvatarPartEvent):void
{
if (AvatarPart.ID(e.id).genre == AvatarPart.GENRE_BODY)
{
var dp:Array = _dpList[AvatarPart.ID(e.id).type-AvatarPart.GENRE_BODY] as Array;
updateCount(dp, e.id);
}
}
protected function updateCount(dp:Array,id:int):void
{
log.writeLog(log.LV_FATAL, this, "updatea part count",id);
if(_itemDic[AvatarPart.ID(id)]!=null)
{
_itemDic[AvatarPart.ID(id)].getUpdateCount();
_selectItemCountA.text = int(_selectItem.count+1).toString();
_selectItemCountB.text = _selectItem.count.toString();
}
// for(var i:int = 0; i < dp.length; i++)
// {
// if(dp[i].avatarPart.id == id)
// {
// log.writeLog(log.LV_FATAL, this, "count up !!!!",id);
// dp[i].getUpdateCount();
// _selectItemCountA.text = int(dp[i].count+1).toString();
// _selectItemCountB.text = dp[i].count.toString();
// break;
// }
// }
}
}
}
import flash.display.Sprite;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import mx.core.UIComponent;
import org.libspark.thread.Thread;
import model.*;
import model.events.*;
import view.image.shop.*;
import view.image.item.*;
import view.scene.common.*;
import view.scene.*;
import view.BaseShowThread;
import view.IViewThread;
import view.scene.common.AvatarClip;
class ShowThread extends BaseShowThread
{
public function ShowThread(view:IViewThread, stage:DisplayObjectContainer, at:int)
{
super(view, stage);
}
protected override function run():void
{
next(close);
}
}
|
table taxonDivision
"ncbi taxonomy high level divisions"
(
uint id ; "division id in GenBank taxonomy database"
char[3] code; "division code 3 characters "
string name ; "division name e.g. BCT, PLN, VRT, MAM, PRI..."
string comments ; "free-text comments "
)
|
/*
ADOBE SYSTEMS INCORPORATED
Copyright 2008 Adobe Systems Incorporated. All Rights Reserved.
NOTICE: Adobe permits you to modify and distribute this file only in accordance with
the terms of Adobe AIR SDK license agreement. You may have received this file from a
source other than Adobe. Nonetheless, you may modify or distribute this file only in
accordance with such agreement.
*/
package air.update.descriptors
{
import air.update.logging.Logger;
import air.update.utils.Constants;
import flash.filesystem.File;
[ExcludeClass]
public class StateDescriptor
{
private static var logger:Logger = Logger.getLogger("air.update.descriptors.StateDescriptor");
public static const NAMESPACE_STATE_1_0:Namespace = new Namespace("http://ns.adobe.com/air/framework/update/state/1.0");
// private
private var xml:XML;
private var defaultNS:Namespace;
public function StateDescriptor(xml:XML)
{
this.xml = xml;
defaultNS = xml.namespace();
}
/**
* Determines if the given namespace refers to the current version of state descriptor
*/
public static function isThisVersion(ns:Namespace):Boolean
{
return ns && ns.uri == NAMESPACE_STATE_1_0.uri;
}
/**
* Creates the default XML file
*/
public static function defaultState():StateDescriptor
{
default xml namespace = StateDescriptor.NAMESPACE_STATE_1_0;
var initialXML:XML =
<state>
<lastCheck>{new Date()}</lastCheck>
</state>;
return new StateDescriptor(initialXML);
}
public function getXML():XML
{
return xml;
}
public function get lastCheckDate():Date
{
return stringToDate_defaultNull(xml.lastCheck.toString());
}
public function set lastCheckDate(value:Date):void
{
xml.lastCheck = value.toString();
}
public function get currentVersion():String
{
return xml.currentVersion.toString();
}
public function set currentVersion(value:String):void
{
xml.currentVersion = value;
}
public function get previousVersion():String
{
return xml.previousVersion.toString();
}
public function set previousVersion(value:String):void
{
xml.previousVersion = value;
}
public function get storage():File
{
return stringToFile_defaultNull(xml.storage.toString());
}
public function set storage(value:File):void
{
xml.storage = fileToString_defaultEmpty(value);
}
public function get updaterLaunched():Boolean
{
return stringToBoolean_defaultFalse(xml.updaterLaunched.toString());
}
public function set updaterLaunched(value:Boolean):void
{
xml.updaterLaunched = value.toString();
}
public function get failedUpdates():Array
{
var updates:Array = new Array();
for each (var version:XML in xml.failed.*)
{
updates.push(version);
}
return updates;
}
public function addFailedUpdate(value:String):void
{
if (xml.failed.length() == 0)
{
xml.failed = <failed/>
}
xml.failed.appendChild(<version>{value}</version>);
}
public function removeAllFailedUpdates():void
{
xml.failed = <failed />
}
public function validate():void
{
default xml namespace = defaultNS;
if (!isThisVersion(defaultNS))
{
throw new Error("unknown state version", Constants.ERROR_STATE_UNKNOWN);
}
if (xml.lastCheck.toString() == "")
{
throw new Error("lastCheck must have a non-empty value", Constants.ERROR_LAST_CHECK_MISSING);
}
if (!validateDate(xml.lastCheck.toString()))
{
throw new Error("Invalid date format for state/lastCheck", Constants.ERROR_LAST_CHECK_INVALID);
}
if (xml.previousVersion.toString() != "" && !validateText(xml.previousVersion))
{
throw new Error("Illegal value for state/previousVersion", Constants.ERROR_PREV_VERSION_INVALID);
}
if (xml.currentVersion.toString() != "" && !validateText(xml.currentVersion))
{
throw new Error("Illegal value for state/currentVersion", Constants.ERROR_CURRENT_VERSION_INVALID);
}
if (xml.storage.toString() != "" && (!validateText(xml.storage) || !validateFile(xml.storage.toString())))
{
throw new Error("Illegal value for state/storage", Constants.ERROR_STORAGE_INVALID);
}
if ([ "", "true", "false"].indexOf(xml.updaterLaunched.toString()) == -1 )
{
throw new Error("Illegal value \"" + xml.updaterLaunched.toString() + "\" for state/updaterLaunched.", Constants.ERROR_LAUNCHED_INVALID);
}
if (!validateFailed(xml.failed))
{
throw new Error("Illegal values for state/failed", Constants.ERROR_FAILED_INVALID);
}
// check if all the update data is in place
var count:int = 0;
if (previousVersion != "") count ++;
if (currentVersion != "") count ++;
if (storage) count ++;
if (count > 0 && count != 3)
{
throw new Error("All state/previousVersion, state/currentVersion, state/storage, state/updaterLaunched must be set", Constants.ERROR_VERSIONS_INVALID);
}
}
private function validateDate(dateString:String):Boolean
{
var result:Boolean = false;
try
{
var n:Number = Date.parse(dateString);
if (!isNaN(n))
{
result = true;
}
}catch(err:Error)
{
result = false;
}
return result;
}
private function validateFile(fileString:String):Boolean
{
var result:Boolean = false;
try
{
var file:File = new File(fileString);
result = true;
}catch(err:Error)
{
result = false;
}
return result;
}
private function validateText(elem:XMLList):Boolean
{
// See if element contains simple content
if (!elem.hasSimpleContent())
{
return false;
}
if (elem.length() > 1)
{
// XMLList contains more than one element - ie. there is more than one
// <name> or <description> element. This is invalid.
return false;
}
return true;
}
private function validateFailed(elem:XMLList):Boolean
{
if (elem.length() > 1)
{
// XMLList contains more than one element - ie. there is more than one
// <name> or <description> element. This is invalid.
return false;
}
var elemChildren:XMLList = elem.*;
for each (var child:XML in elemChildren)
{
if (child.name() == null)
{
// If any element doesn't have a name
return false;
}
if (child.name().localName != "version")
{
// If any element is not <version>, it's not valid
return false;
}
if (!child.hasSimpleContent())
{
// If any <version> element contains more than simple content, it's not valid
return false;
}
}
return true;
}
private function stringToDate_defaultNull(dateString:String):Date
{
var date:Date = null;
if (dateString)
{
date = new Date(dateString);
}
return date;
}
private function stringToBoolean_defaultFalse(str:String):Boolean
{
switch (str) {
case "true":
case "1":
return true;
case "":
case "false":
case "0":
return false;
}
return false;
}
private function stringToFile_defaultNull(str:String):File
{
if (!str)
{
return null;
}
return new File(str);
}
private function fileToString_defaultEmpty(file:File):String
{
if (file && file.nativePath)
{
return file.nativePath;
}
return "";
}
}
} |
package views.client.http {
import starling.display.Sprite;
import starling.text.TextField;
import starling.utils.Align;
import views.SrollableContent;
public class HttpPanel extends Sprite {
private var holder:Sprite = new Sprite();
private var fileList:SrollableContent;
public function HttpPanel() {
super();
fileList = new SrollableContent(1200,275,holder);
fileList.y = 20;
addChild(fileList);
}
public function populate(_itms:Vector.<String>):void {
clear();
var txt:TextField;
for(var j:int=0,ll:int=_itms.length;j<ll;++j){
txt = new TextField(800,32,_itms[j]);
txt.format.setTo("Fira Sans Semi-Bold 13",13,0xD8D8D8,Align.LEFT);
txt.x = 24;
txt.y = j*22;
txt.batchable = true;
txt.touchable = false;
holder.addChild(txt);
}
fileList.fullHeight = (j*22)+12;
fileList.init();
}
public function destroy():void {
fileList.reset();
var k:int = holder.numChildren;
while(k--)
holder.removeChildAt(k);
holder.dispose();
}
public function clear():void {
fileList.reset();
var k:int = holder.numChildren;
while(k--)
holder.removeChildAt(k);
}
}
} |
package tests.pvp
{
import altern.ray.IRaycastImpl;
import altern.ray.Raycaster;
import alternativa.a3d.collisions.CollisionBoundNode;
import alternativa.a3d.collisions.CollisionUtil;
import alternativa.a3d.controller.SimpleFlyController;
import alternativa.a3d.controller.ThirdPersonController;
import alternativa.a3d.controller.ThirdPersonTargetingSystem;
import alternativa.a3d.materials.HealthBarFillMaterial;
import alternativa.a3d.objects.ArrowLobMeshSet2;
import alternativa.a3d.objects.HealthBarSet;
import alternativa.a3d.objects.ProjectileDomain;
import alternativa.a3d.rayorcollide.TerrainRaycastImpl;
import alternativa.a3d.systems.enemy.A3DEnemyAggroSystem;
import alternativa.a3d.systems.enemy.A3DEnemyArcSystem;
import alternativa.a3d.systems.hud.EdgeRaycastTester;
import alternativa.a3d.systems.hud.TargetBoardTester;
import alternativa.engine3d.core.Occluder;
import alternativa.engine3d.materials.TextureMaterial;
import alternativa.engine3d.utils.GeometryUtil;
import spawners.ModelBundle;
//import alternativa.a3d.systems.hud.DestCalcTester;
import alternativa.a3d.systems.hud.HealthBarRenderSystem;
import alternativa.a3d.systems.hud.TrajRaycastTester;
import alternativa.engine3d.controllers.OrbitCameraMan;
import alternativa.engine3d.core.Camera3D;
import alternativa.engine3d.core.Object3D;
import alternativa.engine3d.core.VertexAttributes;
import alternativa.engine3d.materials.FillMaterial;
import alternativa.engine3d.materials.Grid2DMaterial;
import alternativa.engine3d.materials.Material;
import alternativa.engine3d.materials.NormalMapSpace;
import alternativa.engine3d.materials.StandardTerrainMaterial2;
import alternativa.engine3d.materials.VertexLightTextureMaterial;
import alternativa.engine3d.objects.Mesh;
import alternativa.engine3d.primitives.Box;
import alternativa.engine3d.primitives.PlanarRim;
import alternativa.engine3d.primitives.Plane;
import alternativa.engine3d.RenderingSystem;
import alternativa.engine3d.resources.BitmapTextureResource;
import alternativa.engine3d.resources.Geometry;
import alternterrain.CollidableMesh;
import arena.components.char.AggroMem;
import arena.components.char.HealthFlags;
import arena.components.char.HitFormulas;
import arena.components.char.MovementPoints;
import arena.components.enemy.EnemyAggro;
import arena.components.enemy.EnemyIdle;
import arena.components.weapon.Weapon;
import arena.components.weapon.WeaponSlot;
import arena.components.weapon.WeaponState;
import arena.systems.enemy.AggroMemManager;
import arena.systems.enemy.EnemyAggroNode;
import arena.systems.enemy.EnemyAggroSystem;
import arena.systems.player.AnimAttackSystem;
import arena.systems.player.IStance;
import arena.systems.player.LimitedPlayerMovementSystem;
import arena.systems.weapon.IProjectileDomain;
import arena.views.hud.ArenaHUD;
import ash.core.Entity;
import ash.fsm.EngineState;
import ash.tick.FixedTickProvider;
import ash.tick.FrameTickProvider;
import ash.tick.ITickProvider;
import components.Ellipsoid;
import components.Gravity;
import util.geom.Vec3;
//import ash.tick.MultiUnitTickProvider;
//import ash.tick.UnitTickProvider;
import com.bit101.components.Label;
import com.bit101.components.ProgressBar;
import com.flashartofwar.fcss.utils.FSerialization;
import com.greensock.easing.Cubic;
import com.greensock.easing.Linear;
import com.greensock.TweenLite;
import components.controller.SurfaceMovement;
import components.Health;
import components.ImmovableCollidable;
import components.MovableCollidable;
import components.Pos;
import components.Rot;
import components.tweening.Tween;
import components.Vel;
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.utils.setTimeout;
import haxe.ds.StringMap;
import haxe.io.BytesInput;
import input.KeyPoll;
import spawners.arena.GladiatorBundle;
import spawners.arena.projectiles.Projectiles;
import spawners.arena.skybox.ClearBlueSkyAssets;
import spawners.arena.skybox.SkyboxBase;
import spawners.arena.terrain.MistEdge;
import spawners.arena.terrain.TerrainBase;
import spawners.arena.terrain.TerrainTest;
import spawners.arena.water.NormalWaterAssets;
import spawners.arena.water.WaterBase;
import spawners.grounds.CarribeanTextures;
import spawners.grounds.GroundBase;
import systems.animation.IAnimatable;
import systems.collisions.CollidableNode;
import systems.collisions.EllipsoidCollider;
import systems.collisions.GroundPlaneCollisionSystem;
import systems.player.a3d.GladiatorStance;
import systems.player.a3d.ThirdPersonAiming;
import systems.player.PlayerAction;
import systems.player.PlayerTargetingSystem;
import systems.player.PlayerTargetNode;
import systems.sensors.HealthTrackingSystem;
import systems.SystemPriorities;
import systems.tweening.TweenSystem;
import util.geom.PMath;
import util.SpawnerBundle;
import util.SpawnerBundleLoader;
import views.engine3d.MainView3D;
import views.ui.bit101.PreloaderBar;
import alternativa.engine3d.alternativa3d;
use namespace alternativa3d;
/**
* WIP pvp demo. This will later act as the main controller, for combat mode encounters in the RPG.
*
* todo:
*
* Obstacles and stuffs in environment. Integrate to terrain!
* Attack animation swing arc blocking
*
* ((Chance to stun, Special abilities like: Dodge Tumble, Kick, Throw dirt up))
* ______________________
*
*
*
* Add variety of units with ranged/guns.
*
* PC Top-view command mode with mouse camera scrolling and select individuals with mouse. (RTS style)
*
* Formation support with:
* Console individual + follower list mechanic for roster..Cycle through menu of individuals/leaders.
* PC Mouse Drag Box or Shift + Select mechanic for Roster, (can cycle left/right) based on selected leaders to allow moving as formation.
*
* [[Link attacks (combined non-critical attacks from nearby in-range units around target)]]
* Coordinate attacks (moving from formation movement to individual/movement unit actions)
*
*
* @author Glidias
*/
public class PVPDemo3 extends MovieClip
{
private var _template3D:MainView3D;
private var deadScene:Object3D = new Object3D();
private var game:TheGame;
private var ticker:FrameTickProvider;
private var _preloader:PreloaderBar = new PreloaderBar()
private var bundleLoader:SpawnerBundleLoader;
private var _modelBundle:ModelBundle;
private var _followAzimuth:Boolean = false;
private var spectatorPerson:SimpleFlyController;
private var arenaSpawner:ArenaSpawner;
private var collisionScene:Object3D = new Object3D();
private var _gladiatorBundle:GladiatorBundle;
private var arenaHUD:ArenaHUD;
private var aggroMemManager:AggroMemManager;
private var _waterBase:WaterBase;
private var _skyboxBase:SkyboxBase;
private var _terrainBase:TerrainBase;
private var arrowProjectileDomain:ProjectileDomain = new ProjectileDomain();
public var SHOW_PREFERED_STANCES_ENDTURN:int = 2;
private var waterSettings:String = "XwaterMaterial { perturbReflectiveBy:0.5; perturbRefractiveBy:0.5; waterTintAmount:0.3; fresnelMultiplier:0.43; reflectionMultiplier:0.5; waterColorR:0; waterColorG:0.15; waterColorB:0.115; }";
public function PVPDemo3()
{
haxe.initSwc(this);
//throw new Error(bico(4,0));
// throw new Error(findNumSucceedProb(90, 13, 10)*100);
//Occluder.TEST_INTERSECT();
if (root.loaderInfo.parameters.waterSettings) {
waterSettings = root.loaderInfo.parameters.waterSettings;
}
game = new TheGame(stage);
addChild( _template3D = new MainView3D() );
_template3D.onViewCreate.add(onReady3D);
_template3D.visible = false;
addChild(_preloader);
ArrowLobMeshSet2;
PlanarRim;
}
private function setupTerrainMaterial():Material {
var standardMaterial:StandardTerrainMaterial2 = new StandardTerrainMaterial2(new BitmapTextureResource( new CarribeanTextures.SAND().bitmapData ) , new BitmapTextureResource( _terrainBase.normalMap), null, null );
// standardMaterial.uvMultiplier2 = _terrainBase.mapScale;
//throw new Error([standardMaterial.opaquePass, standardMaterial.alphaThreshold, standardMaterial.transparentPass]);
//standardMaterial.transparentPass = false;
standardMaterial.normalMapSpace = NormalMapSpace.OBJECT;
standardMaterial.specularPower = 0;
standardMaterial.glossiness = 0;
standardMaterial.mistMap = new BitmapTextureResource(new MistEdge.EDGE().bitmapData);
StandardTerrainMaterial2.fogMode = 1;
StandardTerrainMaterial2.fogFar = _terrainBase.FAR_CLIPPING;
StandardTerrainMaterial2.fogNear = 256 * 32;
StandardTerrainMaterial2.fogColor = _template3D.viewBackgroundColor;
standardMaterial.waterLevel = _waterBase.plane.z;
standardMaterial.waterMode = 1;
//standardMaterial.tileSize = 512;
standardMaterial.pageSize = _terrainBase.loadedPage.heightMap.RowWidth - 1;
// _terrainBase.loadedPage.heightMap.flatten(standardMaterial.waterLevel + 130); // flat test
// _terrainBase.loadedPage.heightMap.randomise(255); // randomise test
// _terrainBase.loadedPage.heightMap.slopeAltAlongY(88); // slope zig zag test
// _terrainBase.loadedPage.heightMap.slopeAlongY(122); // slope linear test
return standardMaterial;
}
private function setupTerrainLighting():void {
// _template3D.directionalLight.x = 0;
// _template3D.directionalLight.y = -100;
// _template3D. directionalLight.z = -100;
_template3D.directionalLight.x = 44;
_template3D.directionalLight.y = -100;
_template3D.directionalLight.z = 100;
_template3D.directionalLight.lookAt(0, 0, 0);
_template3D.directionalLight.intensity = .65;
_template3D.ambientLight.intensity = 0.4;
}
private function setupTerrainAndWater():void
{
FSerialization.applyStyle(_waterBase.waterMaterial, FSerialization.parseStylesheet(waterSettings).getStyle("waterMaterial") );
_waterBase.plane.z = -50+ (-64000 +84);//_terrainBase.loadedPage.Square.MinY + 444;
_waterBase.addToScene(_template3D.scene);
_skyboxBase.addToScene(_template3D.scene);
_waterBase.setupFollowCamera();
_waterBase.hideFromReflection.push(_template3D.camera);
_waterBase.hideFromReflection.push(arenaHUD.hud);
var terrainMat:Material = setupTerrainMaterial();
_template3D.scene.addChild( _terrainBase.getNewTerrain(terrainMat , 0, 1) );
_terrainBase.terrain.waterLevel = _waterBase.plane.z;
//_terrainBase.terrain.debug = true;
var hWidth:Number = (_terrainBase.terrain.boundBox.maxX - _terrainBase.terrain.boundBox.minX) * .5 * _terrainBase.terrain.scaleX;
_terrainBase.terrain.x -= hWidth*.5;
_terrainBase.terrain.y += hWidth*.5;
//throw new Error([(camera.x - terrainLOD.x) / terrainLOD.scaleX, -(camera.y - terrainLOD.y) / terrainLOD.scaleX]);
///*
var camera:Camera3D = _template3D.camera;
_terrainBase.terrain.detail = 1;
camera.z = _terrainBase.sampleObjectPos(camera) ;
//if (camera.z < _waterBase.plane.z) camera.z = _waterBase.plane.z;
camera.z += 122;
spectatorPerson.setObjectPosXYZ(camera.x, camera.y, camera.z);
// */
_waterBase.plane.z *= _terrainBase.TERRAIN_HEIGHT_SCALE;
}
// customise methods accordingly here...
private function getSpawnerBundles():Vector.<SpawnerBundle>
{
return new <SpawnerBundle>[_gladiatorBundle = new GladiatorBundle(arenaSpawner), arenaHUD = new ArenaHUD(stage) ,
_modelBundle = new ModelBundle(Projectiles, null, true),
_terrainBase = new TerrainBase(TerrainTest,1, 144/256), //.25*.25 // 0.09375
_skyboxBase = new SkyboxBase(ClearBlueSkyAssets),
_waterBase = new WaterBase(NormalWaterAssets),
new GroundBase([CarribeanTextures])
];
}
private function setupViewSettings():void
{
_template3D.viewBackgroundColor = 0xDDDDDD;
}
private function randomiseHeights(amt:Number, geom:Geometry):void {
var pos:Vector.<Number> = geom.getAttributeValues(VertexAttributes.POSITION);
for (var i:int = 0; i < pos.length; i+=3) {
pos[i + 2] = Math.random()*amt;
}
geom.setAttributeValues(VertexAttributes.POSITION, pos);
}
private function setupEnvironment():void
{
TerrainBase;
arenaSpawner.getNewDummyBox(SpawnerBundle.context3D);
_template3D.scene.addChild(deadScene);
_template3D.stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContextCreated);
// example visual scene
var box:Mesh = new Box(100, 13, 100 + 64, 1, 1, 1, false, new FillMaterial(0xCCCCCC, .85) );
//box.z = 0;
occluderTest = new Occluder();
_targetBoardTester.testOccluder = occluderTest;
_template3D.scene.addChild(box);
_template3D.scene.addChild(occluderTest);
_debugBox = new Box(32, 32, 72, 1, 1, 1, false, new FillMaterial(0xFF0000) );
_template3D.scene.addChild(_debugBox);
SpawnerBundle.uploadResources(_debugBox.getResources());
//var mat:VertexLightTextureMaterial = new VertexLightTextureMaterial(new BitmapTextureResource(new BitmapData(4, 4, false, 0xBBBBBB),
// var planeFloor:Mesh = new Plane(2048, 2048, 8, 8, false, false, null, new Grid2DMaterial(0xBBBBBB, 1) );
// randomiseHeights( -177, planeFloor.geometry);
// planeFloor.calculateBoundBox();
// _template3D.scene.addChild(planeFloor);
//arenaSpawner.addCrossStage(SpawnerBundle.context3D);
//SpawnerBundle.uploadResources(planeFloor.getResources(true, null));
setupTerrainLighting();
setupTerrainAndWater();
box.z = _terrainBase.sample(box.x, box.y);
//GeometryUtil.globalizeMesh(box);
occluderTest.x = box.x;
occluderTest.y = box.y;
occluderTest.z = box.z;
//var anotherOccluder:Occluder = new Occluder();
//var plTest:Plane = new Plane(100, 100, 1, 1, true, false);
//anotherOccluder.createForm(plTest.geometry);
occluderTest.createForm(box.geometry);
SpawnerBundle.uploadResources(box.getResources());
//box.visible = false;
collisionScene.addChild(box.clone());
// _gladiatorBundle.textureMat.waterLevel = _waterBase.plane.z;
// _terrainBase.terrain.z = -_terrainBase.terrain.boundBox.minZ;
// collision scene (can be something else)
var rootCollisionNode:CollisionBoundNode;
game.colliderSystem.collidable = rootCollisionNode = new CollisionBoundNode();
rootCollisionNode.addChild( _terrainBase.getTerrainCollisionNode() );
//rootCollisionNode.addChild( CollisionUtil.getCollisionGraph(box) );
// rootCollisionNode.addChild( CollisionUtil.getCollisionGraph(_waterBase.plane) );
game.colliderSystem._collider.threshold = 0.00001;
// (Optional) Enforced ground plane collision
game.gameStates.thirdPerson.addInstance( new GroundPlaneCollisionSystem(_waterBase.plane.z - 20, true) ).withPriority(SystemPriorities.resolveCollisions);
}
private function setupProjectiles():void
{
game.engine.addEntity( new Entity().add(arrowProjectileDomain, IProjectileDomain) );
arrowProjectileDomain.setHitResolver(_animAttackSystem);
if (_modelBundle.getSubModelPacket("arrow").getMaterial() is TextureMaterial) {
// do nothing, basic texture material is fine for current batch amount
}
else {
ArrowLobMeshSet2.BATCH_AMOUNT = 58;
}
var arrowLob:ArrowLobMeshSet2 = new ArrowLobMeshSet2( (_modelBundle.getSubModelPacket("arrow").model as Mesh).geometry, _modelBundle.getSubModelPacket("arrow").getMaterial() );
_template3D.scene.addChild(arrowLob);
arrowProjectileDomain.init( arrowLob );
arrowLob.setGravity(216 * 3);
SpawnerBundle.uploadResources(arrowLob.getResources());
arrowLob.setPermanentArrows();
}
private function onContextCreated(e:Event):void
{
throw new Error("Created again! Context loss earlier");
}
private var markedTargets:Vector.<Object3D> = new Vector.<Object3D>();
private var _enemyAggroSystem:EnemyAggroSystem;
// CAMERA CONTROLLING
private var testArr:Array = [];
private var testArr2:Array = [];
private var curArr:Array = testArr;
private var arrayOfSides:Array = [testArr, testArr2];
private var sideIndex:int = 0;
private var testIndex:int = 0;
private var thirdPersonController:ThirdPersonController;
private var commanderCameraController:ThirdPersonController;
private var engineStateCommander:EngineState;
private var engineStateTransiting:EngineState;
private var _commandLookTarget:Object3D;
private var _commandLookEntity:Entity;
private static const CHASE_Z_OFFSET:Number = 44;
private static const CMD_Z_OFFSET:Number = 72 + 40;
private var TARGET_MODE_ZOOM:Number = 55;
private static var CMD_DIST:Number = 730;
private var transitionCamera:ThirdPersonController;
private var centerPlayerTween:Tween;
private var _transitCompleteCallback:Function;
private var _sceneLocked:Boolean = false;
// RULES
private var movementPoints:MovementPoints = new MovementPoints();
private var MAX_MOVEMENT_POINTS:Number = 1000;// 4;// 9999;// 7;
private var MAX_COMMAND_POINTS:int = 5;
private var ASSIGNED_HP:int = 1120; // 120;
private var COMMAND_POINTS_PER_TURN:int = 5;
private var commandPoints:Vector.<int> = new <int>[0,0];
private var collOtherClass:Class = ImmovableCollidable;
// Deault weapon stats
private var TEST_WEAPON_LIST:WeaponSlot = getTestWeaponList();
//private var TEST_MELEE_WEAPON:Weapon = getTestRangedWeapon(); //getTestWeaponFireModes(); //
private var testRangeWeapon:Weapon;
private function getTestWeaponList():WeaponSlot {
var weapSlot:WeaponSlot = new WeaponSlot().init();
weapSlot.slots[0] = getTestRangedWeapon();
weapSlot.slots[1] = getTestWeaponFireModes();
// weapSlot.slots[0] = getTestWeaponFireModes();
return weapSlot;
}
private function getTestWeaponFireModes():Weapon {
var head:Weapon;
var tail:Weapon;
head = getTestWeapon(false); // swing
head.nextFireMode = tail = getTestWeapon(true); // thrust
//tail.nextFireMode = tail = testRangeWeapon = getTestRangedWeapon();
return head;
}
private function getTestRangedWeapon():Weapon {
var w:Weapon = new Weapon();
w.projectileSpeed = 20.4318 * ArenaHUD.METER_UNIT_SCALE;
w.name = "Longbow";
w.fireMode = Weapon.FIREMODE_TRAJECTORY;
w.fireModeLabel = "Shoot arrow";
w.sideOffset =11;
w.heightOffset = 13;
w.minRange = 40;
w.damage = 15;
w.cooldownTime = 5;// .8;
//w.cooldownTime = thrust ? 0.3 : 0.36666666666666666666666666666667;
w.hitAngle = 45 * PMath.DEG_RAD;
w.damageRange = 6; // damage up-range variance
// Thrust: 10-20 : Swing 25-30
w.critMinRange = 800;
w.critMaxRange = 1600;
w.deviation = .25;
w.range = ArenaHUD.METER_UNIT_SCALE * 50;
w.deviation = HitFormulas.getDeviationForRange(512, 16);
w.timeToSwing = .3;
w.strikeTimeAtMaxRange = 0; //0.0001;
w.strikeTimeAtMinRange = 0;// 0.0001;
w.muzzleVelocity = 16.4318 * ArenaHUD.METER_UNIT_SCALE;// * 197.206;
w.muzzleLength = 40;
w.parryEffect = .4;
w.stunEffect = 0;
w.stunMinRange = 0;
w.stunMaxRange = 0;
w.matchAnimVarsWithStats();
w.anim_fullSwingTime = 0.96;
w.minPitch = -Math.PI*.2;
w.maxPitch = Math.PI * .2;
w.rangeMode = Weapon.RANGEMODE_BOW;
w.id = "bow";
w.projectileDomain = arrowProjectileDomain;
return w;
}
private function getTestWeapon(thrust:Boolean=false):Weapon {
/*
var w:Weapon = new Weapon();
w.name = "Some Melee weapon";
w.range = 0.74 * ArenaHUD.METER_UNIT_SCALE + ArenaHUD.METER_UNIT_SCALE * .25;
w.minRange = 16;
w.damage = 25;
w.cooldownTime = 1.0;
w.hitAngle = 22 * 180 / Math.PI;
w.damageRange = 7; // damage up-range variance
w.critMinRange = w.range * .35;
w.critMaxRange = w.range * .70;
if (w.critMinRange < 16) {
var corr:Number = (16 - w.critMinRange);
w.critMinRange += corr;
w.critMaxRange += corr;
}
if (w.critMaxRange > w.range) w.critMaxRange = w.range;
w.timeToSwing =.15;
w.strikeTimeAtMaxRange = .8;
w.strikeTimeAtMinRange = w.timeToSwing+.005; // usually close to time to swing
w.parryEffect = .4;
w.stunEffect = 0;
w.stunMinRange = 0;
w.stunMaxRange = 0;
return w;
*/
A3DEnemyAggroSystem;
A3DEnemyArcSystem;
ProjectileDomain;
var w:Weapon = new Weapon();
w.minPitch = -Math.PI*.25;
w.maxPitch = Math.PI*.25;
w.projectileSpeed = 0;
w.deviation = 0;
w.name = "Melee weapon";
w.fireMode = thrust ? Weapon.FIREMODE_THRUST : Weapon.FIREMODE_SWING;
w.sideOffset =thrust ? 15 : 36+16;// thrust ? 15 : 36;
w.heightOffset = 0;
// w.range = 0.74 * ArenaHUD.METER_UNIT_SCALE + ArenaHUD.METER_UNIT_SCALE * .25;
//w.range += 32;
w.range = 68;
//w.range += 16;
w.minRange = 16;
w.damage = thrust ? 13 : 25;
w.cooldownTime = thrust ? 0.7 : 0.96;
//w.cooldownTime = thrust ? 0.3 : 0.36666666666666666666666666666667;
w.hitAngle = 45 * PMath.DEG_RAD;
w.damageRange = thrust ? 10 : 5; // damage up-range variance
// Thrust: 10-20 : Swing 25-30
w.critMinRange = w.range * .35;
w.critMaxRange = w.range * .70;
if (w.critMinRange < 16) {
var corr:Number = (16 - w.critMinRange);
w.critMinRange += corr;
w.critMaxRange += corr;
}
if (w.critMaxRange > w.range) w.critMaxRange = w.range;
w.timeToSwing = thrust ? 0.3 : 0.4; // thrust ? 0.13333333333333333333333333333333 : 0.26666666666666666666666666666667;
w.strikeTimeAtMaxRange = w.timeToSwing;// thrust ? 0.4 : 0.6;
w.strikeTimeAtMinRange = w.timeToSwing; // usually close to time to swing
w.parryEffect = .4;
w.stunEffect = 0;
w.stunMinRange = 0;
w.stunMaxRange = 0;
w.matchAnimVarsWithStats();
w.anim_fullSwingTime = 0.96;
return w;
}
/// <summary>
/// Calculates the binomial coefficient (nCk) (N items, choose k)
/// </summary>
/// <param name="n">the number items</param>
/// <param name="k">the number to choose</param>
/// <returns>the binomial coefficient</returns>
// /*
public function bico( n:Number, k:Number):Number
{
if (k > n) { return 0; }
if (n == k) { return 1; } // only one way to chose when n == k
if (k > n - k) { k = n - k; } // Everything is symmetric around n-k, so it is quicker to iterate over a smaller k than a larger one.
var c:Number = 1;
for (var i:int = 1; i <= k; i++)
{
c *= n--;
c /= i;
}
return c;
}
// */
private function findNumCombiProb(s:int, n:int, x:int):Number {
return findNumCombi(s, n, x) / Math.pow(x, n);
}
private function findNumSucceedProb(s:int, n:int, x:int):Number {
var total:Number = Math.pow(x, n);
var max:Number = x * n;
var accum:Number = 0;
for (var i:int = s; i <= max; i++) {
accum += findNumCombi(i, n, x) ;
}
return accum / total;
}
private function findNumCombi(s:int, n:int, x:int):Number {
var accum:Number = 0;
var limit:int = (s - n) / x;
for (var k:int = 0; k <= limit; k++) {
accum += Math.pow( -1, k) * bico(n, k) * bico(s - x * k - 1, n - 1);
}
return accum;
}
private function getDeductionCP():int {
return 1;
}
// -- code goes here
private function setupStartingEntites():void {
// Register any custom skins needed for this game
//arenaSpawner.setupSkin(, ArenaSpawner.RACE_SAMNIAN);
// spawn any beginning entieies
var curPlayer:Entity;
arenaSpawner.addTextureResourceSide(SpawnerBundle.context3D, ArenaSpawner.RACE_SAMNIAN, 1, _gladiatorBundle.getSideTexture(1) );
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 0, -520, _terrainBase.sample(0,-520)+44, 0, 0, "0", null, null, TEST_WEAPON_LIST); testArr.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66, -520, _terrainBase.sample(66,-520)+44, 0, 0, "1", null, null, TEST_WEAPON_LIST); testArr.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66*2, -520, _terrainBase.sample(66*2,-520)+44, 0, 0, "2", null, null, TEST_WEAPON_LIST); testArr.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66*3, -520, _terrainBase.sample(66*3,-520)+44, 0, 0, "3", null, null, TEST_WEAPON_LIST); testArr.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66 * 4, -520, _terrainBase.sample(66*4,-520)+44, 0, 0, "4", null, null, TEST_WEAPON_LIST); testArr.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66 * 6, 520, _terrainBase.sample( 66 * 6, 520)+44, Math.PI, 1, "0", null, null, TEST_WEAPON_LIST); testArr2.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66 * 7, 520, _terrainBase.sample(66 * 7, 520)+44, Math.PI, 1, "1", null, null, TEST_WEAPON_LIST); testArr2.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66 * 8, 520, _terrainBase.sample(66 * 8, 520)+44, Math.PI, 1, "2", null, null, TEST_WEAPON_LIST); testArr2.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66 * 9, 520, _terrainBase.sample(66*9,520)+44, Math.PI, 1, "3", null, null, TEST_WEAPON_LIST); testArr2.push(curPlayer);
curPlayer = arenaSpawner.addGladiator(ArenaSpawner.RACE_SAMNIAN, null, 66 * 10, 520, _terrainBase.sample(66*10,520)+44, Math.PI, 1, "4", null, null, TEST_WEAPON_LIST); testArr2.push(curPlayer);
var health:Health;
var i:int = testArr.length;
while (--i > -1) {
testArr[i].add( new Counter());
health = testArr[i].get(Health) as Health;
health.hp = health.maxHP = ASSIGNED_HP;
//health.onDamaged.add(onDamaged);
//health.onDamaged.add(onDamaged);
}
i = testArr2.length;
while (--i > -1) {
testArr2[i].add( new Counter());
health = testArr2[i].get(Health) as Health;
health.hp = health.maxHP = ASSIGNED_HP;
// health.onDamaged.add(onDamaged);
// health.onDamaged.add(onDamaged);
}
//arenaSpawner.switchPlayer(testArr[testIndex], stage);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, 1);
}
private function onKeyDown(e:KeyboardEvent):void
{
if ( game.gameStates.engineState.currentState === engineStateTransiting || _sceneLocked) {
// for now until interupt case is available
return;
}
var keyCode:uint = e.keyCode;
if (keyCode === Keyboard.TAB && !game.keyPoll.isDown(keyCode) ) {
cyclePlayerChoice();
}
else if (keyCode === Keyboard.B && !game.keyPoll.isDown(keyCode) ) {
if ( game.gameStates.engineState.currentState === game.gameStates.thirdPerson && !sceneLocked && !_targetMode ) { //
cycleWeapon();
}
}
else if (keyCode === Keyboard.R && !game.keyPoll.isDown(keyCode)) {
if (!_targetMode && game.gameStates.engineState.currentState === game.gameStates.thirdPerson && !sceneLocked ) attemptReloadTurn();
}
else if (keyCode === Keyboard.L && !game.keyPoll.isDown(keyCode) ) {
changeCameraView("commander");
}
else if (keyCode === Keyboard.K && !game.keyPoll.isDown(keyCode) ) {
if (commandPoints[sideIndex] - getDeductionCP() >= 0 ) {
switchToPlayer();
}
}
else if (keyCode === Keyboard.Z && !game.keyPoll.isDown(keyCode) ) {
if (arenaHUD.charWeaponEnabled ) toggleTargetingMode();
}
else if (keyCode === Keyboard.BACKSPACE && !game.keyPoll.isDown(keyCode)) {
endPhase();
}
else if (keyCode === Keyboard.F && !game.keyPoll.isDown(keyCode)) {
if ( arenaHUD.checkStrike(keyCode) ) { // for now, HP reduction is insntatneous within this method
// remove controls, perform animation, before toggling targeting mode and restoring back controls
resolveStrikeAction();
//toggleTargetingMode();
}
}
else if (keyCode >= Keyboard.NUMBER_1 && keyCode <= Keyboard.NUMBER_9 && !game.keyPoll.isDown(keyCode) ) {
if ( arenaHUD.checkStrike(keyCode) ) { // for now, HP reduction is insntatneous within this method
// remove controls, perform animation, before toggling targeting mode and restoring back controls
resolveStrikeAction();
//toggleTargetingMode();
}
}
//else if (keyCode === Keyboard.B && !game.keyPoll.isDown(keyCode)) {
// testAnim(1);
//}
else if (keyCode === Keyboard.N && !game.keyPoll.isDown(keyCode)) {
testAnim2(1);
}
else if (keyCode === Keyboard.G && !game.keyPoll.isDown(keyCode)) {
testAnim(.5);
}
else if (keyCode === Keyboard.Y && !game.keyPoll.isDown(keyCode)) {
testAnim2(0);
}
else if (keyCode === Keyboard.H && !game.keyPoll.isDown(keyCode)) {
testAnim2(.5);
}
else if (keyCode === Keyboard.T && !game.keyPoll.isDown(keyCode)) {
testAnim(0);
}
else if (keyCode === Keyboard.P && !game.keyPoll.isDown(keyCode)) {
if ( game.gameStates.engineState.currentState === engineStateCommander ) showPreferedStances();
}
else if (keyCode === Keyboard.RIGHTBRACKET) {
_terrainBase.terrain.debug = ! _terrainBase.terrain.debug;
}
else if (keyCode === Keyboard.NUMPAD_ADD) {
_template3D.camera.fov += 1 * Math.PI/180;
}
else if (keyCode === Keyboard.NUMPAD_SUBTRACT) {
_template3D.camera.fov -= 1 * Math.PI/180;
}
//*/
}
private function onEnemyInterrupt():void {
disablePlayerMovement();
sceneLocked = true;
// _followAzimuth = true;
arcSystem.setVisible(false);
arenaHUD.notifyEnemyInterrupt();
_animAttackSystem.resolved.addOnce(onFinishEnemyInterrupt);
}
private function onFinishEnemyInterrupt():void
{
arenaHUD.appendMessage("Finished interrupt !");
sceneLocked = false;
arcSystem.setVisible(true);
arenaHUD.notifyEnemyInterrupt(false);
// _followAzimuth = false;
if (movementPoints.movementTimeLeft > 0) arenaSpawner.currentPlayerEntity.add(game.keyPoll, KeyPoll);
}
private function attemptReloadTurn():void
{
if (commandPoints[sideIndex] <= 0) {
return;
}
if (!arenaSpawner.currentPlayerEntity.has(Health)) return;
var counter:Counter = arenaSpawner.currentPlayerEntity.get(Counter) as Counter;
var measure:Number = MAX_MOVEMENT_POINTS / (1 << (counter.value-1));
if ( !arenaHUD.charWeaponEnabled || movementPoints.movementTimeLeft < measure*.5) { // attempt reload turn
movementPoints.movementTimeLeft = MAX_MOVEMENT_POINTS / (1 << counter.value);
counter.value++;
arenaHUD.reloadTurn();
targetingSystem.reset();
commandPoints[sideIndex]--;
updateCP();
arenaHUD.hideStars();
// reset all cooldowns of enemies
//_enemyAggroSystem.resetCooldownsOfAllAggro();
//aggroMemManager.processAllEnemyAggroNodes();
/*
arenaSpawner.currentPlayerEntity.remove( KeyPoll);
movementPoints.timeElapsed = .75;
game.engine.updateComplete.addOnce(onReloadFrameDone);
else
*/
if (!arenaSpawner.currentPlayerEntity.has(KeyPoll)) {
arenaSpawner.currentPlayerEntity.add(game.keyPoll, KeyPoll);
}
};
}
private function onReloadFrameDone():void
{
arenaSpawner.currentPlayerEntity.add(game.keyPoll, KeyPoll);
}
private function cycleWeapon():void
{
var index:int = arenaHUD.cycleWeapon();
if (index < 0) return;
var weapSlot:WeaponSlot = arenaSpawner.currentPlayerEntity.get(WeaponSlot) as WeaponSlot;
var gladiatorStance:GladiatorStance =arenaSpawner.currentPlayerEntity.get(IStance) as GladiatorStance;
var toReset:Boolean = false;
if (gladiatorStance != null) {
if (_targetMode) { // kiv
toReset = true;
toggleTargetingMode();
//gladiatorStance.setIdleStance( _lastTargetStance);
}
gladiatorStance.switchWeapon( weapSlot.slots[index] );
if (toReset) {
toggleTargetingMode();
TweenLite.delayedCall(0, toggleTargetingMode);
}
}
delayTimeElapsed = arcSystem.setTimeElapsed(arenaSpawner.currentPlayerEntity.get(Weapon) as Weapon);
//throw new Error(delayTimeElapsed);
//game.keyPoll.resetAllStates();
}
private function resolveStrikeAction():void
{
sceneLocked = true;
playerStriking = true;
(arenaSpawner.currentPlayerEntity.get(IStance) as GladiatorStance).attacking = true;
_followAzimuth = false;
if (!_animAttackSystem.getResolved()) {
arenaHUD.appendSpanTagMessage("Resolving action...");
_animAttackSystem.resolved.addOnce(resolveStrikeAction);
return;
}
if ( isPlayerDead() ) { // assumed player has died before action can be executed!
return;
}
arenaHUD.appendSpanTagMessage("Player executed action!");
//delayTimeElapsed = 0;
var showSimult:Boolean = showAttacksSimulatenously();
//arenaHUD.appendMessage("ENemy is aggroing? " + (arenaHUD.enemyStrikeResult!=0) + ", "+ showSimult);
arenaHUD.delayEnemyStrikeT = 0;
if (showSimult) {
var timeEnemySwing:Number = performEnemyCounterAttack();
// ensure always player strikes last
var delayPlayer:Number = arenaHUD.playerChosenWeaponStrike.anim_fullSwingTime > timeEnemySwing ? .3 : timeEnemySwing - arenaHUD.playerChosenWeaponStrike.anim_fullSwingTime + .3;
//_animAttackSystem.checkTime(.3);
game.engine.addEntity( new Entity().add(new Tween(arenaHUD, delayPlayer, { delayEnemyStrikeT:1 }, {onComplete:doPlayerStrikeAction} ) ) );
}
else {
doPlayerStrikeAction();
}
}
private function doPlayerStrikeAction():void {
var timeToDeplete:Number;
if (arenaHUD.playerChosenWeaponStrike.fireMode > 0) {
AnimAttackSystem.performMeleeAttackAction(arenaHUD.playerWeaponModeForAttack, arenaSpawner.currentPlayerEntity, arenaHUD.targetEntity, arenaHUD.strikeResult > 0 ? arenaHUD.playerDmgDealRoll : 0);
//game.engine.updateComplete.addOnce(onUpdateTimeActionDone);
// delayTimeElapsed = .3 + Math.random() * .15 + arenaHUD.playerChosenWeaponStrike.strikeTimeAtMaxRange;
timeToDeplete = arenaHUD.playerChosenWeaponStrike.strikeTimeAtMaxRange + arenaHUD.playerChosenWeaponStrike.timeToSwing;
}
else {
Weapon.shootWeapon( arenaHUD.playerChosenWeaponStrike.rangeMode, arenaSpawner.currentPlayerEntity, arenaHUD.targetEntity, arenaHUD.strikeResult > 0 ? arenaHUD.playerDmgDealRoll : 0, _animAttackSystem, true);
//game.engine.updateComplete.addOnce(onUpdateTimeActionDone);
// delayTimeElapsed = .3 + Math.random() * .15 + arenaHUD.playerChosenWeaponStrike.timeToSwing;
timeToDeplete = arenaHUD.playerChosenWeaponStrike.timeToSwing;
}
var tarTimeLeft:Number = movementPoints.movementTimeLeft - timeToDeplete;
if (tarTimeLeft < 0) tarTimeLeft = 0;
TweenLite.to( movementPoints, delayTimeElapsed, { movementTimeLeft:tarTimeLeft } );
_animAttackSystem.resolved.addOnce(resolveStrikeAction2);
aggroMemManager.addToAggroMem(arenaSpawner.currentPlayerEntity, arenaHUD.targetEntity);
if (arenaHUD.strikeResult > 0) {
var targetHP:Health = (arenaHUD.targetEntity.get(Health) as Health);
if (targetHP.hp > arenaHUD.playerDmgDealRoll) targetHP.onDamaged.addOnce(onEnemyTargetDamaged);
}
}
private function showAttacksSimulatenously():Boolean
{
return arenaHUD.enemyStrikeResult != 0 && arenaHUD.strikeResult > 0 && arenaHUD.enemyGoesFirst
}
private function performEnemyCounterAttack():Number
{
return AnimAttackSystem.performMeleeAttackAction(arenaHUD.enemyWeaponModeForAttack, arenaHUD.targetEntity, arenaSpawner.currentPlayerEntity, arenaHUD.enemyStrikeResult > 0 ? arenaHUD.enemyDmgDealRoll : 0);
}
private function isPlayerDead():Boolean
{
var hp:Health = arenaSpawner.currentPlayerEntity.get(Health) as Health;
return hp == null || hp.hp <= 0;
}
private var delayTimeElapsed:Number;
private function onUpdateTimeActionDone():void
{
movementPoints.timeElapsed = 0;
}
private function onEnemyTargetDamaged(hp:int, amount:int):void {
if (amount > 0) {
var stance:GladiatorStance = arenaHUD.targetEntity.get(IAnimatable) as GladiatorStance;
stance.updateTension( -1*Math.random(), 0);
stance.flinch();
}
else {
}
}
private function onPlayerDamaged(hp:int, amount:int):void {
if (amount > 0) {
var stance:GladiatorStance = arenaSpawner.currentPlayerEntity.get(IAnimatable) as GladiatorStance;
//stance.flinch();
}
else {
}
}
private function resolveStrikeAction2():void
{
if (arenaHUD.strikeResult == -1) {
arenaHUD.notifyPlayerActionMiss();
}
else {
// /*
var weapState:WeaponState = arenaHUD.targetEntity.get(WeaponState) as WeaponState;
if (weapState!=null && weapState.trigger && weapState.fireMode != null && weapState.fireMode.fireMode<=0) {
weapState.cancelTrigger();
var e:EnemyAggro = arenaHUD.targetEntity.get(EnemyAggro) as EnemyAggro;
if (e != null) e.flag = 0;
}
//*/
}
if (arenaHUD.strikeResult > 0) {
// TweenLite.delayedCall(.5, resolveStrikeAction3);
game.engine.addEntity( new Entity().add( new Tween(arenaHUD, .5, { }, { onComplete:resolveStrikeAction3 } )));
}
else resolveStrikeAction3();
}
private function resolveStrikeAction3():void
{
// resolveStrikeActionFully(true);
// return;
if ( arenaHUD.enemyStrikeResult != 0 && !showAttacksSimulatenously() ) {
//if (arenaHUD.targetEntity.get(Health) == null || arenaHUD.targetEntity.get(Health).hp <= 0) {
// throw new Error("Exception healthdeead");
//}
AnimAttackSystem.performMeleeAttackAction(arenaHUD.enemyWeaponModeForAttack, arenaHUD.targetEntity, arenaSpawner.currentPlayerEntity, arenaHUD.enemyStrikeResult > 0 ? arenaHUD.enemyDmgDealRoll : 0);
_animAttackSystem.resolved.addOnce(resolveStrikeActionFully);
if (arenaHUD.enemyStrikeResult > 0) {
var targetHP:Health = (arenaSpawner.currentPlayerEntity.get(Health) as Health);
if (targetHP.hp > arenaHUD.enemyDmgDealRoll) targetHP.onDamaged.addOnce(onPlayerDamaged);
}
/*
else {
resolveStrikeActionFully(true);
}
*/
}
else {
resolveStrikeActionFully(true);
}
}
private function resolveStrikeActionFully(instant:Boolean=false):void
{
// new stuff here
instant = false;
EnemyAggroSystem.AGGRO_HAS_CRITICAL = false;
aggroMemManager.setupSupportFireOnTarget(arenaHUD.targetEntity, arenaSpawner.currentPlayerEntity, delayTimeElapsed);
//(arenaHUD.targetEntity.get(IStance) as GladiatorStance).attacking = true;
playerStriking = false;
if (aggroMemManager._supportCount != 0) {
game.engine.addEntity( new Entity().add( new Tween({}, .45, { }, { onComplete:resolveStrikeActionFully2 } )));
// TweenLite.delayedCall(.45, resolveStrikeActionFully2); //, [instant]
//trace("Support fire: +" + aggroMemManager._supportCount);
}
else resolveStrikeActionFully2(instant);
}
private function resolveStrikeActionFully2(instant:Boolean=false):void {
if (delayTimeElapsed > 0) {
game.engine.updateComplete.addOnce(onUpdateTimeActionDone);
movementPointSystem.enabled = false;
movementPoints.timeElapsed = delayTimeElapsed;
}
// throw new Error("A"+instant);
//instant = true;
if (!instant ) { //&& arenaHUD.enemyStrikeResult > 0
//TweenLite.delayedCall(delayTimeElapsed+.3, resolveToggleTargetingMode);
game.engine.addEntity( new Entity().add( new Tween(arenaHUD, .3, { }, { onComplete:resolveToggleTargetingMode } )))
//resolveToggleTargetingMode();
}
else {
resolveToggleTargetingMode();
}
}
private function resolveToggleTargetingMode():void
{
if ( !_animAttackSystem.getResolved() ) {
_animAttackSystem.resolved.addOnce(resolveToggleTargetingMode2);
}
else {
resolveToggleTargetingMode2();
}
}
private function resolveToggleTargetingMode2():void {
playerStriking = true;
EnemyAggroSystem.AGGRO_HAS_CRITICAL = true;
aggroMemManager.removeSupportFire(arenaSpawner.currentPlayerEntity);
toggleTargetingMode();
sceneLocked = false;
(arenaSpawner.currentPlayerEntity.get(IStance) as GladiatorStance).attacking = false;
_followAzimuth = (arenaSpawner.currentPlayerEntity.get(Health) != null);
}
private function testAnim(blend:Number=.5):void
{
var stance:GladiatorStance = (arenaSpawner.currentPlayerEntity || curArr[testIndex]).get(IAnimatable) as GladiatorStance;
if (stance ==null) stance = curArr[testIndex].get(IAnimatable) as GladiatorStance;
stance.swing(blend);
}
private function testAnim2(blend:Number=.5):void
{
var stance:GladiatorStance = (arenaSpawner.currentPlayerEntity || curArr[testIndex]).get(IAnimatable) as GladiatorStance;
if (stance ==null) stance = curArr[testIndex].get(IAnimatable) as GladiatorStance;
stance.thrust(blend);
}
private var _targetMode:Boolean = false;
private var _lastTargetZoom:Number;
private var _lastTargetStance:int;
private function toggleTargetingMode():void
{
if ( game.gameStates.engineState.currentState != game.gameStates.thirdPerson) {
return;
}
var gladiatorStance:GladiatorStance = arenaSpawner.currentPlayerEntity.get(IAnimatable) as GladiatorStance;
if (!_targetMode) {
_lastTargetZoom = thirdPersonController.thirdPerson.controller.getDistance();
_lastTargetStance = gladiatorStance.stance;
}
_targetMode = !_targetMode;
gladiatorStance.standEnabled = !_targetMode;
arenaHUD.setTargetMode(_targetMode);
//arcSystem.arcs.visible = !_targetMode;
if (_targetMode) {
thirdPersonController.thirdPerson.preferedZoom = TARGET_MODE_ZOOM;
thirdPersonController.thirdPerson.controller.disableMouseWheel();
movementPointSystem.noDeplete = true;
_animAttackSystem.checkTime( movementPointSystem.addRealFreeTime(.3) );
//movementPoints.timeElapsed = movementPointSystem._freeTime;
//movementPointSystem.enabled = false;
disablePlayerMovement();
if (gladiatorStance.stance == 0) {
//gladiatorStance.stance = 1;
gladiatorStance.setIdleStance( 1);
}
//arenaSpawner.currentPlayerEntity.add(game.keyPoll, KeyPoll);
}
else {
exitTargetMode();
//gladiatorStance.setIdleStance( _lastTargetStance);
}
gladiatorStance.setTargetMode(_targetMode);
}
private function disablePlayerMovement():void
{
(arenaSpawner.currentPlayerEntity.get(SurfaceMovement) as SurfaceMovement).resetAllStates();
game.keyPoll.resetAllStates();
arenaSpawner.currentPlayerEntity.remove(KeyPoll);
//movementPoints.timeElapsed = 0;
//movementPointSystem._freeTime = 0;
}
private function exitTargetMode():void
{
_targetMode = false;
arenaHUD.setTargetMode(_targetMode);
thirdPersonController.thirdPerson.preferedZoom = _lastTargetZoom;
thirdPersonController.thirdPerson.controller.enableMouseWheel();
var gladiatorStance:GladiatorStance = arenaSpawner.currentPlayerEntity.get(IAnimatable) as GladiatorStance;
if (movementPoints.movementTimeLeft > 0) arenaSpawner.currentPlayerEntity.add(game.keyPoll, KeyPoll);
movementPointSystem.enabled = true;
movementPointSystem.noDeplete = false;
gladiatorStance.setTargetMode(_targetMode);
}
private var CAMERA_PHASETO_AVERAGE:Boolean = false; // switch phase new side average position? else selected target
private var CAMERA_PHASEFROM_AVERAGE:Boolean = true; // old side average position? else nearest target from above
private function startPhase():void {
sideIndex = 0;
curArr = arrayOfSides[sideIndex];
_newPhase = true;
// TODO: Naive vs Exploratory version
//setSideDanger(curArr);
for (var i:int = 0; i < arrayOfSides.length; i++) {
setSideDanger( arrayOfSides[i] );
}
commandPoints[sideIndex] += COMMAND_POINTS_PER_TURN;
if (commandPoints[sideIndex] > MAX_COMMAND_POINTS) commandPoints[sideIndex] = MAX_COMMAND_POINTS;
updateCP();
if (game.gameStates.engineState.currentState != engineStateCommander) {
_transitCompleteCallback = selectFirstMan;
changeCameraView("commander");
}
aggroMemManager.notifyStartPhase(sideIndex);
}
private function setSideDanger(arr:Array):void
{
var len:int = arr.length;
for (var i:int = 0; i < len; i++) {
var stance:GladiatorStance = arr[i].get(IAnimatable) as GladiatorStance;
if (stance != null) {
stance.danger = true;
stance.setStanceAndRefresh(stance.preferedStance);
}
}
}
private function selectFirstMan():void {
setTimeout(selectFirstMan2, 0);
}
private function selectFirstMan2():void {
cyclePlayerChoice(0);
}
private function endPhase():void {
if (game.gameStates.engineState.currentState != engineStateCommander) {
doEndTurn();
return;
}
var oldArr:Array = arrayOfSides[sideIndex];
len = oldArr.length;
for (i = 0; i < len; i++ ) {
var stance:GladiatorStance = oldArr[i].get(IAnimatable) as GladiatorStance;
if (stance !=null && stance.stance != stance.preferedStance) stance.setStanceAndRefresh(stance.preferedStance);
}
sideIndex++;
if (sideIndex >= commandPoints.length) {
sideIndex = 0;
}
curArr = arrayOfSides[sideIndex];
aggroMemManager.notifyStartPhase(sideIndex);
var x:Number = 0;
var y:Number = 0;
var x2:Number = 0;
var y2:Number = 0;
var i:int;
var len:int;
var obj:Object3D;
var dx:Number;
var dy:Number;
var d:Number = Number.MAX_VALUE;
commandPoints[sideIndex] += COMMAND_POINTS_PER_TURN;
if (commandPoints[sideIndex] > MAX_COMMAND_POINTS) commandPoints[sideIndex] = MAX_COMMAND_POINTS;
updateCP();
i = testArr.length;
while (--i > -1) {
var counter:Counter = testArr[i].get(Counter) as Counter;
counter.value = 0;
}
i = testArr2.length;
while (--i > -1) {
counter = testArr2[i].get(Counter) as Counter;
counter.value = 0;
}
len = curArr.length;
// TODO: visibility awareness determination required... before adding them in...
if (CAMERA_PHASETO_AVERAGE) {
for (i = 0; i < len; i++) {
obj = curArr[i].get(Object3D);
x += obj.x;
y += obj.y;
}
x /= len;
y /= len;
}
else {
obj = curArr[0].get(Object3D);
x = obj.x;
y = obj.y;
}
len = oldArr.length;
if (CAMERA_PHASEFROM_AVERAGE) {
for (i = 0; i < len; i++) {
obj = oldArr[i].get(Object3D);
x2 += obj.x;
y2 += obj.y;
}
x2 /= len;
y2 /= len;
}
else {
var nx:Number = 0;
var ny:Number = 0;
for (i = 0; i < len; i++) {
obj = oldArr[i].get(Object3D);
x2 = obj.x;
y2 = obj.y;
dx = x2 - x;
dy = y2 - y;
var testD:Number = dx * dx + dy * dy ;
if (testD < d) {
d = testD;
nx = x2;
ny = y2;
}
}
x2 = nx;
y2 = ny;
}
x = x2 - x;
y = y2 - y;
var fromAng:Number = commanderCameraController.thirdPerson.controller.angleLongitude;
var ang:Number = (Math.atan2(y, x) - Math.PI*.5) * (180 / Math.PI);
//ang = curArr != testArr ? 180 : 0;
game.engine.addEntity( new Entity().add( new Tween(commanderCameraController.thirdPerson.controller, 3, { angleLongitude: getDestAngle(fromAng,ang) } ) ) );
testIndex = 0;
cyclePlayerChoice(0);
arenaHUD.newPhase();
}
private function focusOnCurPlayer():void {
arenaSpawner.switchPlayer(null, stage);
focusOnTargetChar(curArr[testIndex]);
}
private function cyclePlayerChoice(cycleAmount:int=1):void // cycling players only allowed in commander view
{
if (game.gameStates.engineState.currentState != engineStateCommander) {
if (_targetMode) exitTargetMode();
changeCameraView("commander");
return;
}
if ( game.gameStates.engineState.currentState === engineStateCommander ) {
testIndex+=cycleAmount;
if (testIndex >= curArr.length) testIndex = 0;
focusOnTargetChar(curArr[testIndex]);
}
}
private function focusOnTargetChar(targetEntity:Entity, friendly:Boolean=true):void
{
var pos:Object3D = targetEntity.get(Object3D) as Object3D;
if (friendly) {
arenaHUD.setChar(targetEntity);
}
markedTargets[0] = pos;
arenaHUD.showArrowMarkers(markedTargets);
var counter:Counter = targetEntity.get(Counter) as Counter;
movementPoints.movementTimeLeft= MAX_MOVEMENT_POINTS / (1 << counter.value);
var props:Object = { x:pos.x, y:pos.y, z:pos.z + CMD_Z_OFFSET };
if ( centerPlayerTween == null) {
centerPlayerTween = new Tween(_commandLookEntity.get(Object3D), 2, props );
}
else {
centerPlayerTween.updateProps( _commandLookEntity.get(Object3D), props );
centerPlayerTween.t = 0;
}
if (centerPlayerTween.dead) {
centerPlayerTween.dead = false;
game.engine.addEntity( new Entity().add( centerPlayerTween ) );
}
}
private function updateTargetCharFocus():void {
if (arenaSpawner.currentPlayer != null) {
_commandLookTarget._x = arenaSpawner.currentPlayer.x;
_commandLookTarget._y = arenaSpawner.currentPlayer.y;
_commandLookTarget._z = arenaSpawner.currentPlayer.z + CMD_Z_OFFSET;
arenaSpawner.disableStanceControls(stage);
}
}
private function unsetPlayerHP():void {
var hp:Health = arenaSpawner.currentPlayerEntity.get(Health) as Health;
if (hp != null) {
hp.unsetFlags( HealthFlags.FLAG_PLAYER );
}
}
private function setPlayerHP():void {
var hp:Health = arenaSpawner.currentPlayerEntity.get(Health) as Health;
if (hp != null) {
hp.setFlags( HealthFlags.FLAG_PLAYER );
}
}
private function switchToPlayer():void {
if (game.gameStates.engineState.currentState === game.gameStates.thirdPerson) {
return;
}
_targetMode = false;
arenaHUD.setTargetMode(_targetMode);
commandPoints[sideIndex] -= getDeductionCP();
updateCP();
game.keyPoll.resetAllStates();
if (arenaSpawner.currentPlayerEntity) {
arenaSpawner.currentPlayerEntity.remove(MovementPoints);
unsetPlayerHP();
}
arenaSpawner.switchPlayer(curArr[testIndex], stage);
var stance:GladiatorStance;
stance = arenaSpawner.currentPlayerEntity.get(IAnimatable) as GladiatorStance;
stance.setTargetMode(_targetMode);
stance.attacking = false;
for (var i:int = 0; i < curArr.length; i++) {
if (i != testIndex) {
stance = curArr[i].get(IAnimatable) as GladiatorStance;
if (stance == null) continue;
if (stance.stance==0) stance.setStanceAndRefresh(1);
//setTimeout(stance.crouch, Math.random() * 600);
stance.setStanceAndRefresh(2);
}
}
var counter:Counter = arenaSpawner.currentPlayerEntity.get(Counter) as Counter;
movementPoints.movementTimeLeft = MAX_MOVEMENT_POINTS / (1 << counter.value);
counter.value++;
setPlayerHP();
arenaSpawner.currentPlayerEntity.add( movementPoints, MovementPoints);
//var untyped:* = arenaSpawner.currentPlayerSkin.getSurface(0).material;
//arenaSpawner.currentPlayerSkin.getSurface(0).material as
//arenaSpawner.currentPlayerSkin.getSurface(0).material
thirdPersonController.thirdPerson.setFollowComponents( arenaSpawner.currentPlayer, arenaSpawner.currentPlayerEntity.get(Rot) as Rot);
thirdPersonController.thirdPerson.setVisAlphaInstance( arenaSpawner.currentPlayer, .95 );
thirdPersonAiming.setCameraParameters(thirdPersonController.thirdPerson.followTarget, _template3D.camera, thirdPersonController.thirdPerson.cameraForward);
thirdPersonAiming.setEntity( arenaSpawner.currentPlayerEntity);
changeCameraView("thirdPerson");
}
private function getDestAngle(actualangle:Number, destangle:Number):Number {
var difference:Number = destangle - actualangle;
if (difference < -180) difference += 360;
if (difference > 180) difference -= 360;
return difference + actualangle;
}
private function changeCameraView(targetState:String):void {
// TODO: interrupt case.
arenaHUD.clearArrows();
if (targetState === "thirdPerson" && game.gameStates.engineState.currentState === engineStateCommander) {
_transitCompleteCallback = onCharacterZoomedInTurnStartl
game.gameStates.engineState.changeState("transiting");
arenaHUD.setState("transiting");
transitionCameras(commanderCameraController.thirdPerson, thirdPersonController.thirdPerson, targetState);
}
else if (targetState === "commander" && game.gameStates.engineState.currentState === game.gameStates.thirdPerson) {
doEndTurn();
}
/*
else if (targetState === "commander" && game.gameStates.engineState.currentState === game.gameStates.spectator) {
game.gameStates.engineState.changeState("transiting");
transitionCameras(spectatorPerson, commanderCameraController.thirdPerson, targetState, arenaSpawner.currentPlayer.x, arenaSpawner.currentPlayer.y, arenaSpawner.currentPlayer.z, Cubic.easeIn);
}
*/
else {
//throw new Error("NO transition");
game.gameStates.engineState.changeState("spectator");
game.gameStates.engineState.changeState(targetState);
arenaHUD.setState(targetState);
}
}
private function doEndTurn():void
{
///*
if (!_animAttackSystem.getResolved()) {
disablePlayerMovement();
sceneLocked = true;
_followAzimuth = false;
arenaHUD.appendSpanTagMessage("Resolving turn...");
_animAttackSystem.resolved.addOnce(doEndTurn);
return;
}
_followAzimuth = true;
var targetState:String = "commander";
//throw new Error("A");
if (!_newPhase) arenaHUD.appendSpanTagMessage("Turn resolved!");
//*/
_newPhase = false;
sceneLocked = false;
_transitCompleteCallback = focusOnCurPlayer;
updateTargetCharFocus();
if (arenaSpawner.currentPlayerEntity) arenaSpawner.currentPlayerEntity.remove(MovableCollidable);
arenaHUD.setTargetChar(null);
endTurnAI();
game.gameStates.engineState.changeState("transiting");
arenaHUD.setState("transiting");
transitionCameras(thirdPersonController.thirdPerson, commanderCameraController.thirdPerson, targetState, NaN, NaN, NaN, Cubic.easeIn);
}
private function onCharacterZoomedInTurnStartl():void
{
var stance:GladiatorStance = arenaSpawner.currentPlayerEntity.get(IAnimatable) as GladiatorStance;
if (stance.stance != stance.preferedStance) stance.setStanceAndRefresh(stance.preferedStance);
stance.enableFast = true
/*
for (var i:int = 0; i < curArr.length; i++) {
if (i != testIndex) {
var stance:GladiatorStance = curArr[i].get(IAnimatable) as GladiatorStance;
if (stance.stance==0) stance.setStanceAndRefresh(1);
setTimeout(stance.crouch, Math.random() * 600);
}
}
*/
}
private var _targetTransitState:String;
private var _animAttackSystem:AnimAttackSystem;
private var arcSystem:A3DEnemyArcSystem;
private var thirdPersonAiming:ThirdPersonAiming;
private var _newPhase:Boolean;
private function transitionCameras(fromCamera:OrbitCameraMan, toCamera:OrbitCameraMan, targetState:String=null, customX:Number=Number.NaN, customY:Number = Number.NaN, customZ:Number = Number.NaN, customEase:Function=null, duration:Number=1):void
{
//fromCamera.controller.angleLatitude %= 360;
//fromCamera.controller.angleLongitude %= 360;
//toCamera.controller.angleLatitude %= 360;
//toCamera.controller.angleLongitude %= 360;
//transitionCamera.thirdPerson.validateFollowTarget();
fromCamera.validateFollowTarget();
toCamera.validateFollowTarget();
transitionCamera.thirdPerson.instantZoom = fromCamera.preferedZoom;
transitionCamera.thirdPerson.controller.angleLatitude = fromCamera.controller.angleLatitude;
transitionCamera.thirdPerson.controller.angleLongitude = fromCamera.controller.angleLongitude;
var transitCameraTarget:Object3D = transitionCamera.thirdPerson.followTarget;
transitCameraTarget.x = isNaN(customX) ? fromCamera.controller._followTarget.x : customX;
transitCameraTarget.y = isNaN(customY) ?fromCamera.controller._followTarget.y : customY;
transitCameraTarget.z = isNaN(customZ) ? fromCamera.controller._followTarget.z : customZ;
var tarX:Number = toCamera.controller._followTarget.x;
var tarY:Number = toCamera.controller._followTarget.y;
var tarZ:Number = toCamera.controller._followTarget.z;
var ease:Function = customEase != null ? customEase : Cubic.easeOut;
var tween:Tween =new Tween(transitionCamera.thirdPerson.controller, duration, { setDistance:toCamera.controller.getDistance(), angleLatitude:getDestAngle(transitionCamera.thirdPerson.controller.angleLatitude, toCamera.controller.angleLatitude), angleLongitude:getDestAngle(transitionCamera.thirdPerson.controller.angleLongitude, toCamera.controller.angleLongitude) }, { ease:ease } );
var tween2:Tween = new Tween(transitionCamera.thirdPerson.followTarget, duration, { x:tarX, y:tarY, z:tarZ }, { ease:ease } );
game.engine.addEntity( new Entity().add( tween ) );
game.engine.addEntity( new Entity().add( tween2 ) );
if (targetState != null) {
_targetTransitState = targetState;
tween.onComplete = onTransitComplete;
//game.gameStates.engineState.changeState(targetState);
}
}
private function onTransitComplete():void {
game.gameStates.engineState.changeState(_targetTransitState);
arenaHUD.setState(_targetTransitState);
if (_targetTransitState != "commander") {
arenaHUD.hideStars();
if ( _targetTransitState === "thirdPerson" ) {
/*
if (destCalcTester) {
destCalcTester.pos = arenaSpawner.getPlayerEntity().get(Pos) as Pos;
destCalcTester.rot = arenaSpawner.getPlayerEntity().get(Rot) as Rot;
destCalcTester.ellipsoid = arenaSpawner.getPlayerEntity().get(Ellipsoid) as Ellipsoid;
destCalcTester.gravity = arenaSpawner.getPlayerEntity().get(Gravity) as Gravity;
destCalcTester.surfaceMovement = arenaSpawner.getPlayerEntity().get(SurfaceMovement) as SurfaceMovement;
destCalcTester.movementPoints = arenaSpawner.getPlayerEntity().get(MovementPoints) as MovementPoints;
}
*/
activateEnemyAggro();
}
}
else {
arenaHUD.showStars();
if (SHOW_PREFERED_STANCES_ENDTURN==2) {
showPreferedStances();
}
if (arenaSpawner.currentPlayerEntity) {
unsetPlayerHP();
arenaSpawner.currentPlayerEntity.remove(MovementPoints);
}
}
_targetTransitState = null;
if (_transitCompleteCallback != null) {
_transitCompleteCallback();
_transitCompleteCallback = null;
}
}
private function endTurnAI():void
{
aggroMemManager.notifyEndTurn();
var otherSide:int = aggroMemManager.activeSide == 0 ? 1 : 0;
var enemySide:Array = arrayOfSides[otherSide];
var len:int = enemySide.length;
for ( var i:int = 0; i < len; i++) {
var e:Entity = enemySide[i];
e.remove( collOtherClass );
}
var mySide:Array = arrayOfSides[aggroMemManager.activeSide];
len = mySide.length;
for ( i = 0; i < len; i++) {
e = mySide[i];
if (e === arenaSpawner.currentPlayerEntity) continue;
e.remove( collOtherClass );
}
if (SHOW_PREFERED_STANCES_ENDTURN==1) showPreferedStances();
}
private function showPreferedStances():void {
var i:int;
var len:int = curArr.length;
for (i = 0; i < len; i++) {
var stance:GladiatorStance = curArr[i].get(IAnimatable) as GladiatorStance;
if (stance.stance != stance.preferedStance) stance.setStanceAndRefresh(stance.preferedStance);
}
}
private function activateEnemyAggro():void
{
arenaSpawner.currentPlayerEntity.add( new MovableCollidable().init() ); // temp, for testing only
aggroMemManager.notifyTurnStarted(arenaSpawner.currentPlayerEntity);
delayTimeElapsed= arcSystem.setTimeElapsed(arenaSpawner.currentPlayerEntity.get(Weapon) as Weapon);
// temporary, considering putting this in aggroMemManager???
///*
var otherSide:int = aggroMemManager.activeSide == 0 ? 1 : 0;
var enemySide:Array = arrayOfSides[otherSide];
var len:int = enemySide.length;
for ( var i:int = 0; i < len; i++) {
var e:Entity = enemySide[i];
e.add( new collOtherClass().init() );
(e.get(IStance) as GladiatorStance).attacking = true;
}
var mySide:Array = arrayOfSides[aggroMemManager.activeSide];
len = mySide.length;
for ( i = 0; i < len; i++) {
e= mySide[i];
if (e === arenaSpawner.currentPlayerEntity) continue;
e.add( new collOtherClass().init() );
(e.get(IStance) as GladiatorStance).attacking = false;
}
// */
}
private function onOutOfFuel():void {
//arenaSpawner.currentPlayerEntity.get(Vel).x = 0;
// arenaSpawner.currentPlayerEntity.get(SurfaceMovement);
// cyclePlayerChoice();
game.keyPoll.resetAllStates()
arenaSpawner.currentPlayerEntity.remove(KeyPoll);
//movementPoints.timeElapsed = 0;
arenaHUD.outOfFuel();
}
private function onStanceChange(val:int):void {
arenaHUD.setStance(val);
}
private function setupGameplay():void
{
GladiatorStance.ON_STANCE_CHANGE.add(onStanceChange);
// Tweening system
game.engine.addSystem( new TweenSystem(), SystemPriorities.animate );
var raycasterCameraBackRay:Raycaster = new Raycaster(game.gameStates.colliderSystem.collidable as IRaycastImpl);
// Third person
///*
var dummyEntity:Entity = arenaSpawner.getNullEntity(); // arenaSpawner.getPlayerBoxEntity(SpawnerBundle.context3D);
// arenaSpawner.getNullEntity();
_commandLookTarget = dummyEntity.get(Object3D) as Object3D;
_commandLookEntity = dummyEntity;
_commandLookTarget.z = CMD_Z_OFFSET;
//game.engine.addEntity(dummyEntity);
//*/
// possible to set raycastScene parameter to something else besides "collisionScene"...
thirdPersonController = new ThirdPersonController(stage, _template3D.camera, collisionScene, _commandLookTarget, _commandLookTarget, null, null, null, true);
thirdPersonController.thirdPerson.instantZoom = 140;
var terrainRaycast:TerrainRaycastImpl;
collisionScene.addChild( terrainRaycast = new TerrainRaycastImpl(_terrainBase.terrain) );
thirdPersonController.thirdPerson.preferedMinDistance = 0.1;// 100;
thirdPersonController.thirdPerson.controller.minDistance = 0;
thirdPersonController.thirdPerson.controller.maxDistance = 12240;
thirdPersonController.thirdPerson.offsetZ = 22;// CHASE_Z_OFFSET
thirdPersonController.thirdPerson.raycaster = raycasterCameraBackRay;
//thirdPersonController.thirdPerson.offsetX = 22;
game.gameStates.thirdPerson.addInstance( thirdPersonAiming = new ThirdPersonAiming() ).withPriority(SystemPriorities.preRender);
game.gameStates.thirdPerson.addInstance(thirdPersonController).withPriority(SystemPriorities.postRender);
arcSystem = new A3DEnemyArcSystem(_template3D.scene);
//arenaHUD.arcContainer = arcSystem.arcs;
game.gameStates.thirdPerson.addInstance(arcSystem ).withPriority(SystemPriorities.postRender);
_waterBase.hideFromReflection.push(arcSystem.arcs);
// setup targeting system
var myTargetingSystem:ThirdPersonTargetingSystem = new ThirdPersonTargetingSystem(thirdPersonController.thirdPerson);
targetingSystem = myTargetingSystem;
game.gameStates.thirdPerson.addInstance(targetingSystem).withPriority(SystemPriorities.postRender);
targetingSystem.targetChanged.add(onTargetChanged);
targetingSystem.targetChanged.add(arenaHUD.setTargetChar);
/*
game.gameStates.thirdPerson.addInstance( new TrajRaycastTester(terrainRaycast, thirdPersonController.thirdPerson.rayOrigin, thirdPersonController.thirdPerson.rayDirection) ).withPriority(SystemPriorities.postRender);
*/
/*
game.gameStates.thirdPerson.addInstance( new EdgeRaycastTester(terrainRaycast as TerrainRaycastImpl,thirdPersonController) ).withPriority(SystemPriorities.postRender);
*/
// game.gameStates.thirdPerson.addInstance( destCalcTester = new DestCalcTester(new Ellipsoid(20, 20, 36), new Vec3(), new Vec3(), game.colliderSystem.collidable, _debugBox ) );
// special PVP movement limited time
movementPointSystem;
game.gameStates.thirdPerson.addInstance( movementPointSystem= new LimitedPlayerMovementSystem() ).withPriority(SystemPriorities.preMove);
movementPointSystem.outOfFuel.add( onOutOfFuel);
commanderCameraController = new ThirdPersonController(stage, _template3D.camera, collisionScene, _commandLookTarget, _commandLookTarget, null, null, null, true );
commanderCameraController.thirdPerson.raycaster = raycasterCameraBackRay;
//commanderCameraController.thirdPerson.preferedMinDistance = CMD_DIST;
commanderCameraController.thirdPerson.instantZoom = CMD_DIST;
//// commanderCameraController.thirdPerson.controller.maxDistance = CMD_DIST;
// commanderCameraController.thirdPerson.controller.minDistance = CMD_DIST;
engineStateCommander = game.gameStates.getNewSpectatorState();
engineStateCommander.addInstance( commanderCameraController).withPriority(SystemPriorities.postRender);
game.gameStates.engineState.addState("commander", engineStateCommander);
transitionCamera = new ThirdPersonController(stage, _template3D.camera, collisionScene, _commandLookTarget, _commandLookTarget, null, null, null, false);
transitionCamera.thirdPerson.raycaster = raycasterCameraBackRay;
transitionCamera.thirdPerson.controller.disablePermanently();
transitionCamera.thirdPerson.controller.stopMouseLook ();
transitionCamera.thirdPerson.mouseWheelSensitivity = 0;
engineStateTransiting = game.gameStates.getNewSpectatorState();
transitionCamera.thirdPerson.controller.minAngleLatitude = -Number.MAX_VALUE;
transitionCamera.thirdPerson.controller.maxAngleLatidude = Number.MAX_VALUE;
transitionCamera.thirdPerson.controller.minAngleLatitude = -Number.MAX_VALUE;
transitionCamera.thirdPerson.controller.maxAngleLatidude = Number.MAX_VALUE;
transitionCamera.thirdPerson.controller.minDistance = -Number.MAX_VALUE;
transitionCamera.thirdPerson.controller.maxDistance= Number.MAX_VALUE;
engineStateTransiting.addInstance( transitionCamera).withPriority(SystemPriorities.postRender);
game.gameStates.engineState.addState("transiting", engineStateTransiting);
// (Optional) Go straight to 3rd person
//throw new Error(game.gameStates.engineState.currentState);
//game.gameStates.engineState.changeState("thirdPerson");
arenaSpawner.currentPlayer = _commandLookTarget;
arenaHUD.setCamera(_template3D.camera);
_template3D.camera.addChild( arenaHUD.hud);
game.gameStates.thirdPerson.addInstance( _animAttackSystem = new AnimAttackSystem() ).withPriority(SystemPriorities.stateMachines);
// game.gameStates.( _animAttackSystem= new AnimAttackSystem() ).withPriority(SystemPriorities.stateMachines);
game.gameStates.thirdPerson.addInstance( _enemyAggroSystem = new A3DEnemyAggroSystem(collisionScene) ).withPriority(SystemPriorities.stateMachines);
_enemyAggroSystem.timeChecker = _animAttackSystem;
//_enemyAggroSystem.onEnemyAttack.add(onEnemyAttack);
// _enemyAggroSystem.onEnemyReady.add(onEnemyReady);
// _enemyAggroSystem.onEnemyStrike.add(onEnemyStrike);
//_enemyAggroSystem.onEnemyCooldown.add(onEnemyCooldown);
// aggro mem manager
aggroMemManager = new AggroMemManager();
aggroMemManager.weaponLOSChecker = _enemyAggroSystem;
arenaHUD.weaponLOSCheck = _enemyAggroSystem;
aggroMemManager.init(game.engine, _enemyAggroSystem, _enemyAggroSystem);
aggroMemManager.aggroList.nodeAdded.add(onEnemyAggroNodeAdded);
game.gameStates.engineState.changeState("thirdPerson");
arenaHUD.setState("thirdPerson");
startPhase();
}
private function onEnemyAggroNodeAdded(node:EnemyAggroNode):void
{
var gStance:GladiatorStance = node.entity.get(IAnimatable) as GladiatorStance;
if (gStance != null && gStance.stance == 0) {
gStance.stance = 1;
gStance.setIdleStance(1);
}
}
private function onEnemyCooldown(e:Entity, cooldown:Number):void
{
var obj:Object3D = e.get(Object3D) as Object3D;
arenaHUD.appendMessage(obj.name+" is on cooldown! "+cooldown);
}
private function onEnemyAttack(e:Entity):void
{
var obj:Object3D = e.get(Object3D) as Object3D;
arenaHUD.appendMessage(obj.name+" swings weapon at player!");
}
private function onEnemyStrike(e:Entity):void
{
var obj:Object3D = e.get(Object3D) as Object3D;
if ((e.get(WeaponState) as WeaponState).fireMode.fireMode > 0) {
arenaHUD.appendMessage("Enemy interrupt occured!");
//arenaHUD.appendMessage(obj.name+" finiished his strike!");
onEnemyInterrupt();
}
}
private function onEnemyReady(e:Entity):void
{
var obj:Object3D = e.get(Object3D) as Object3D;
arenaHUD.appendMessage(obj.name+" is ready to attack!");
}
private var playerStriking:Boolean = false;
private function onDamaged(e:Entity, hp:int, amount:int):void
{
var stance:GladiatorStance;
if (e != arenaSpawner.currentPlayerEntity) { // assume damage inflicted by active currentPlayerEntity
if ( playerStriking ) {
arenaHUD.txtPlayerStrike(e, hp, amount);
}
else {
arenaHUD.txtEnemyGotHit(e, hp, amount);
stance = e.get(GladiatorStance) as GladiatorStance;
if (stance != null) stance.flinch();
}
}
else { // assume damage taken from entity under aggro system
if (amount > 0) {
arenaHUD.txtTookDamageFrom(_enemyAggroSystem.currentAttackingEnemy, hp, amount);
// movementPoints.movementTimeLeft -= .5;
if ( movementPoints.movementTimeLeft < 0) movementPoints.movementTimeLeft = 0;
var gladiatorStance:GladiatorStance = arenaSpawner.currentPlayerEntity.get(IStance) as GladiatorStance;
if (gladiatorStance != null) {
//gladiatorStance.enableFast = false;
if (sceneLocked) gladiatorStance.flinch();
}
}
}
}
private function onMurdered(e:Entity, hp:int, amount:int):void
{
if (e != arenaSpawner.currentPlayerEntity) { // assume active currentPlayerEntity killed entity
arenaHUD.txtPlayerStrike(e, hp, amount, true);
unregisterEntity(e);
arenaSpawner.killGladiator2(e, deadScene);
}
else { // assume currentePlayerNEtity killed by entity under aggro system!
arenaHUD.txtTookDamageFrom(_enemyAggroSystem.currentAttackingEnemy, hp, amount, true);
unregisterEntity(arenaSpawner.currentPlayerEntity);
if (curArr[testIndex] == null) { // do a naive reset for this case.
testIndex = 0;
//throw new Error("null pointer after unregistration...");
}
arenaSpawner.killGladiator2(arenaSpawner.currentPlayerEntity, deadScene);
_followAzimuth = false;
arenaHUD.killPlayer();
//game.engine.removeEntity(arenaSpawner.currentPlayerEntity);
}
}
private function unregisterEntity(e:Entity):void //naive approach for roster atm.
{
var arr:Array;
var removeIndex:int = testArr.indexOf(e);
arr = testArr;
if (removeIndex < 0) {
removeIndex = testArr2.indexOf(e);
arr = testArr2;
}
if (removeIndex < 0) {
//throw new Error("COUld not find entity in registry!");
return;
}
arr.splice(removeIndex, 1);
}
private function onTargetChanged(node:PlayerTargetNode ):void
{
//throw new Error("A:"+node.obj.name);
if (node != null) {
markedTargets[0] = node.obj;
arenaHUD.showArrowMarkers(markedTargets);
}
else {
arenaHUD.clearArrows();
//markedTargets.length = 0;
//arenaHUD.showArrowMarkers(markedTargets);
}
}
// boilerplate below...
private function onReady3D():void
{
SpawnerBundle.context3D = _template3D.stage3D.context3D;
setupViewSettings();
arenaSpawner = new ArenaSpawner(game.engine, game.keyPoll);
bundleLoader = new SpawnerBundleLoader(stage, onSpawnerBundleLoaded, getSpawnerBundles() );
bundleLoader.progressSignal.add( _preloader.setProgress );
bundleLoader.loadBeginSignal.add( _preloader.setLabel );
}
private function createHPBarSet():HealthBarSet {
var hpBarSet:HealthBarSet = new HealthBarSet(100, new HealthBarFillMaterial(0xFFFFFF, 1), 10, 64, 4);
SpawnerBundle.uploadResources(hpBarSet.getResources());
_template3D.scene.addChild(hpBarSet);
_waterBase.hideFromReflection.push(hpBarSet);
return hpBarSet;
}
private function onSpawnerBundleLoaded():void
{
removeChild(_preloader);
_template3D.visible = true;
// _template3D.scene.addChild(
game.gameStates.thirdPerson.addInstance( _targetBoardTester = new TargetBoardTester(_template3D.scene, null, _template3D.camera, game.keyPoll, _terrainBase.terrain) ).withPriority(SystemPriorities.postRender);
game.engine.addSystem( new HealthBarRenderSystem( createHPBarSet(), ~HealthFlags.FLAG_PLAYER ), SystemPriorities.render );
game.engine.addSystem( new RenderingSystem(_template3D.scene), SystemPriorities.render );
spectatorPerson =new SimpleFlyController(
new EllipsoidCollider(GameSettings.SPECTATOR_RADIUS.x, GameSettings.SPECTATOR_RADIUS.y, GameSettings.SPECTATOR_RADIUS.z),
null ,
stage,
_template3D.camera,
GameSettings.SPECTATOR_SPEED,
GameSettings.SPECTATOR_SPEED_SHIFT_MULT);
game.gameStates.spectator.addInstance(spectatorPerson).withPriority(SystemPriorities.postRender);
// Add a Health trackign listenining system
game.engine.addSystem( new HealthTrackingSystem(), SystemPriorities.stateMachines);
HealthTrackingSystem.SIGNAL_DAMAGE.add(onDamaged);
HealthTrackingSystem.SIGNAL_MURDER.add(onMurdered);
setupEnvironment();
_targetBoardTester.terrainLOD = _terrainBase.terrain;
setupInterface();
setupStartingEntites();
setupGameplay();
setupProjectiles();
ticker = new FrameTickProvider(stage);
ticker.add(renderTick);
ticker.start();
updateTicker = new FrameTickProvider(stage);// new UnitTickProvider(stage, fixedTime);
updateTicker.add(updateTick);
updateTicker.start();
}
private var fixedTime:Number = 1 / 40;
private var updateTicker:ITickProvider;
private var targetingSystem:ThirdPersonTargetingSystem;
private var movementPointSystem:LimitedPlayerMovementSystem;
private var _debugBox:Box;
private var occluderTest:Occluder;
private var _targetBoardTester:TargetBoardTester;
//private var destCalcTester:DestCalcTester;
private function setupInterface():void
{
}
private function updateCP():void
{
// testCPLabel.text = (sideIndex > 0 ? "Ghost army" : "Player army" )+" CP left: "+commandPoints[sideIndex] +" / "+MAX_COMMAND_POINTS;
arenaHUD.updateTurnInfo( commandPoints[sideIndex], MAX_COMMAND_POINTS, (sideIndex > 0 ? "Ghost army" : "Player army" ), sideIndex, COMMAND_POINTS_PER_TURN );
}
private function updateTick(time:Number):void {
//if (time != 1 / 60) throw new Error("DIFF");
//time *= 4;
game.engine.update(time);
arenaHUD.updateFuel( movementPoints.movementTimeLeft / MAX_MOVEMENT_POINTS );
arenaHUD.update();
}
private function renderTick(time:Number):void {
thirdPersonController.thirdPerson.followAzimuth = _followAzimuth || game.keyPoll.isDown(Keyboard.V);
var camera:Camera3D = _template3D.camera;
_skyboxBase.update(_template3D.camera);
_template3D.camera.startTimer();
// adjust offseted waterlevels
_waterBase.waterMaterial.update(_template3D.stage3D, _template3D.camera, _waterBase.plane, _waterBase.hideFromReflection);
_template3D.camera.stopTimer();
// set to default waterLevels
_template3D.render();
}
private function tick(time:Number):void
{
thirdPersonController.thirdPerson.followAzimuth = _followAzimuth || game.keyPoll.isDown(Keyboard.V);
game.engine.update(time);
arenaHUD.updateFuel( movementPoints.movementTimeLeft / MAX_MOVEMENT_POINTS );
arenaHUD.update();
var camera:Camera3D = _template3D.camera;
_skyboxBase.update(_template3D.camera);
_template3D.camera.startTimer();
// adjust offseted waterlevels
_waterBase.waterMaterial.update(_template3D.stage3D, _template3D.camera, _waterBase.plane, _waterBase.hideFromReflection);
_template3D.camera.stopTimer();
// set to default waterLevels
_template3D.render();
}
public function get sceneLocked():Boolean
{
return _sceneLocked;
}
public function set sceneLocked(value:Boolean):void
{
_sceneLocked = value;
}
}
}
import ash.core.Entity;
import components.Health;
class Counter {
public var value:int = 0;
}
|
package laya.ani.bone.canvasmesh {
import laya.ani.bone.MeshTools;
import laya.maths.Matrix;
import laya.renders.RenderContext;
import laya.resource.Texture;
/**
* @private
* 简化mesh绘制,多顶点mesh改为四顶点mesh,只绘制矩形不绘制三角形
*/
public class SimpleSkinMeshCanvas extends SkinMeshCanvas {
/**
* 当前绘制用的mesh
*/
private var tempMesh:MeshData = new MeshData();
/**
* 当前mesh数据是否可用
*/
private var cacheOK:Boolean = false;
/**
* 当前渲染数据是否可用
*/
private var cacheCmdOK:Boolean=false;
/**
* transform参数缓存
*/
private var transformCmds:Array=[];
/**
* drawImage参数缓存
*/
private var drawCmds:Array=[]
override public function init2(texture:Texture, vs:Array, ps:Array, verticles:Array, uvs:Array):void {
super.init2(texture, vs, ps, verticles, uvs);
cacheOK = false;
cacheCmdOK=false;
transformCmds.length=6;
drawCmds.length=9;
}
override public function renderToContext(context:RenderContext):void {
this.context = context.ctx || context;
if (mesh) {
if (mesh.uvs.length <= 8) {
if (mode == 0) {
_renderWithIndexes(mesh);
}
else {
_renderNoIndexes(mesh);
}
return;
}
if (!cacheOK) {
tempMesh.texture = mesh.texture;
tempMesh.uvs = mesh.texture.uv;
tempMesh.vertices = MeshTools.solveMesh(mesh, tempMesh.vertices);
cacheOK = true;
}
if (mode == 0) {
_renderWithIndexes(tempMesh);
}
else {
_renderNoIndexes(tempMesh);
}
}
}
override public function _renderWithIndexes(mesh:MeshData):void {
if(cacheCmdOK)
{
renderByCache(mesh);
return;
}
var indexes:Array = mesh.indexes;
var i:int, len:int = indexes.length;
if (len > 1)
len = 1;
for (i = 0; i < len; i += 3) {
var index0:int = indexes[i] * 2;
var index1:int = indexes[i + 1] * 2;
var index2:int = indexes[i + 2] * 2;
this._renderDrawTriangle(mesh, index0, index1, index2);
}
cacheCmdOK=true;
}
override public function _renderDrawTriangle(mesh:MeshData, index0:int, index1:int, index2:int):void {
var context:* = this.context;
var uvs:Array = mesh.uvs;
var vertices:Array = mesh.vertices;
var texture:Texture = mesh.texture;
var source:Texture = texture.bitmap;
var textureSource:* = source.source;
var textureWidth:Number = texture.width;
var textureHeight:Number = texture.height;
var sourceWidth:Number = source.width;
var sourceHeight:Number = source.height;
//uv数据
var u0:Number;
var u1:Number;
var u2:Number;
var v0:Number;
var v1:Number;
var v2:Number;
if (mesh.useUvTransform) {
var ut:Matrix = mesh.uvTransform;
u0 = ((uvs[index0] * ut.a) + (uvs[index0 + 1] * ut.c) + ut.tx) * sourceWidth;
u1 = ((uvs[index1] * ut.a) + (uvs[index1 + 1] * ut.c) + ut.tx) * sourceWidth;
u2 = ((uvs[index2] * ut.a) + (uvs[index2 + 1] * ut.c) + ut.tx) * sourceWidth;
v0 = ((uvs[index0] * ut.b) + (uvs[index0 + 1] * ut.d) + ut.ty) * sourceHeight;
v1 = ((uvs[index1] * ut.b) + (uvs[index1 + 1] * ut.d) + ut.ty) * sourceHeight;
v2 = ((uvs[index2] * ut.b) + (uvs[index2 + 1] * ut.d) + ut.ty) * sourceHeight;
}
else {
u0 = uvs[index0] * sourceWidth;
u1 = uvs[index1] * sourceWidth;
u2 = uvs[index2] * sourceWidth;
v0 = uvs[index0 + 1] * sourceHeight;
v1 = uvs[index1 + 1] * sourceHeight;
v2 = uvs[index2 + 1] * sourceHeight;
}
//绘制顶点数据
var x0:Number = vertices[index0];
var x1:Number = vertices[index1];
var x2:Number = vertices[index2];
var y0:Number = vertices[index0 + 1];
var y1:Number = vertices[index1 + 1];
var y2:Number = vertices[index2 + 1];
// 计算矩阵,将图片变形到合适的位置
var delta:Number = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2);
var dDelta:Number = 1 / delta;
var deltaA:Number = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2);
var deltaB:Number = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2);
var deltaC:Number = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2);
var deltaD:Number = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2);
var deltaE:Number = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2);
var deltaF:Number = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2);
transformCmds[0]=deltaA * dDelta;
transformCmds[1]=deltaD * dDelta;
transformCmds[2]=deltaB * dDelta;
transformCmds[3]=deltaE * dDelta;
transformCmds[4]=deltaC * dDelta;
transformCmds[5]=deltaF * dDelta;
drawCmds[0]=textureSource;
drawCmds[1]=texture.uv[0] * sourceWidth;
drawCmds[2]=texture.uv[1] * sourceHeight;
drawCmds[3]=textureWidth;
drawCmds[4]=textureHeight;
drawCmds[5]=texture.uv[0] * sourceWidth;
drawCmds[6]=texture.uv[1] * sourceHeight;
drawCmds[7]=textureWidth;
drawCmds[8]=textureHeight;
context.save();
if (transform) {
var mt:Matrix = transform;
context.transform(mt.a, mt.b, mt.c, mt.d, mt.tx, mt.ty);
}
context.transform.apply(context,transformCmds);
context.drawImage.apply(context,drawCmds);
context.restore();
}
/**
* 绘制缓存的命令
* @param mesh
*
*/
private function renderByCache(mesh:MeshData):void
{
var context:* = this.context;
context.save();
if (transform) {
var mt:Matrix = transform;
context.transform(mt.a, mt.b, mt.c, mt.d, mt.tx, mt.ty);
}
context.transform.apply(context,transformCmds);
context.drawImage.apply(context,drawCmds);
context.restore();
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// 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 mx.managers
{
COMPILE::SWF
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.InteractiveObject;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.system.Capabilities;
import flash.system.IME;
import flash.text.TextField;
import flash.ui.Keyboard;
}
//import mx.core.IButton;
import mx.core.IChildList;
import mx.core.IUIComponent;
import mx.core.mx_internal;
import mx.events.FlexEvent;
//import mx.utils.Platform;
use namespace mx_internal;
import org.apache.royale.events.EventDispatcher;
import org.apache.royale.events.MouseEvent;
import mx.core.UIComponent;
/**
* The FocusManager class manages the focus on components in response to mouse
* activity or keyboard activity (Tab key). There can be several FocusManager
* instances in an application. Each FocusManager instance
* is responsible for a set of components that comprise a "tab loop". If you
* hit Tab enough times, focus traverses through a set of components and
* eventually get back to the first component that had focus. That is a "tab loop"
* and a FocusManager instance manages that loop. If there are popup windows
* with their own set of components in a "tab loop" those popup windows will have
* their own FocusManager instances. The main application always has a
* FocusManager instance.
*
* <p>The FocusManager manages focus from the "component level".
* In Flex, a UITextField in a component is the only way to allow keyboard entry
* of text. To the Flash Player or AIR, that UITextField has focus. However, from the
* FocusManager's perspective the component that parents the UITextField has focus.
* Thus there is a distinction between component-level focus and player-level focus.
* Application developers generally only have to deal with component-level focus while
* component developers must understand player-level focus.</p>
*
* <p>All components that can be managed by the FocusManager must implement
* mx.managers.IFocusManagerComponent, whereas objects managed by player-level focus do not.</p>
*
* <p>The FocusManager also managers the concept of a defaultButton, which is
* the Button on a form that dispatches a click event when the Enter key is pressed
* depending on where focus is at that time.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
COMPILE::SWF
public class FocusManager extends EventDispatcher implements IFocusManager
{
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* @private
*
* Default value of parameter, ignore.
*/
private static const FROM_INDEX_UNSPECIFIED:int = -2;
//--------------------------------------------------------------------------
//
// Class variables
//
//--------------------------------------------------------------------------
/**
* @private
*
* Place to hook in additional classes
*/
public static var mixins:Array;
// flag to turn on/off some ie specific behavior
mx_internal static var ieshifttab:Boolean = true;
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* <p>A FocusManager manages the focus within the children of an IFocusManagerContainer.
* It installs itself in the IFocusManagerContainer during execution
* of the constructor.</p>
*
* @param container An IFocusManagerContainer that hosts the FocusManager.
*
* @param popup If <code>true</code>, indicates that the container
* is a popup component and not the main application.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function FocusManager(container:IFocusManagerContainer, popup:Boolean = false)
{
super();
this.popup = popup;
IMEEnabled = true;
/*
// Only <= IE8 supported focus cycling out of the SWF
browserMode = Capabilities.playerType == "ActiveX" && !popup;
desktopMode = Platform.isAir && !popup;
// Flash main windows come up activated, AIR main windows don't
windowActivated = !desktopMode;
*/
container.focusManager = this; // this property name is reserved in the parent
// trace("FocusManager constructor " + container + ".focusManager");
_form = container;
focusableObjects = [];
focusPane = new Sprite();
focusPane.name = "focusPane";
addFocusables(DisplayObject(container));
// Listen to the stage so we know when the root application is loaded.
container.addEventListener(Event.ADDED, addedHandler);
container.addEventListener(Event.REMOVED, removedHandler);
container.addEventListener(FlexEvent.SHOW, showHandler);
container.addEventListener(FlexEvent.HIDE, hideHandler);
container.addEventListener(FlexEvent.HIDE, childHideHandler, true);
container.addEventListener("_navigationChange_",viewHideHandler, true);
/*
//special case application and window
if (container.systemManager is SystemManager)
{
// special case application. It shouldn't need to be made
// active and because we defer appCreationComplete, this
// would steal focus back from any popups created during
// instantiation
if (container != SystemManager(container.systemManager).application)
container.addEventListener(FlexEvent.CREATION_COMPLETE,
creationCompleteHandler);
}
*/
if (mixins)
{
var n:int = mixins.length;
for (var i:int = 0; i < n; i++)
{
new mixins[i](this);
}
}
// Make sure the SystemManager is running so it can tell us about
// mouse clicks and stage size changes.
try
{
/*
var awm:IActiveWindowManager =
IActiveWindowManager(container.systemManager.getImplementation("mx.managers::IActiveWindowManager"));
if (awm)
awm.addFocusManager(container); // build a message that does the equal
*/
if (hasEventListener("initialize"))
dispatchEvent(new Event("initialize"));
}
catch (e:Error)
{
// ignore null pointer errors caused by container using a
// systemManager from another sandbox.
}
// may need to remove this and use ActiveWindowManager
activate();
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var LARGE_TAB_INDEX:int = 99999;
mx_internal var calculateCandidates:Boolean = true;
/**
* @private
*
* True if this focus manager is a popup, false if it is a main application.
*
*/
mx_internal var popup:Boolean;
/**
* @private
*
* True if this focus manager will try to enable/disable the IME based on
* whether the focused control uses IME. Leaving this as a backdoor just in case.
*
*/
mx_internal var IMEEnabled:Boolean;
/**
* @private
* We track whether we've been last activated or saw a TAB
* This is used in browser tab management
*/
mx_internal var lastAction:String;
/**
* @private
* Tab management changes based on whether were in a browser or not
* This value is also affected by whether you are a modal dialog or not
*/
public var browserMode:Boolean;
/**
* @private
* Activation changes depending on whether we're running in AIR or not
*/
public var desktopMode:Boolean;
/**
* @private
* Tab management changes based on whether were in a browser or not
* If non-null, this is the object that will
* lose focus to the browser
*/
private var browserFocusComponent:InteractiveObject;
/**
* @private
* Total set of all objects that can receive focus
* but might be disabled or invisible.
*/
mx_internal var focusableObjects:Array;
/**
* @private
* Filtered set of objects that can receive focus right now.
*/
private var focusableCandidates:Array;
/**
* @private
*/
private var activated:Boolean;
/**
* @private
*/
private var windowActivated:Boolean;
/**
* @private
*
* true if focus was changed to one of focusable objects. False if focus passed to
* the browser.
*/
mx_internal var focusChanged:Boolean;
/**
* @private
*
* if non-null, the location to move focus from instead of the object
* that has focus in the stage.
*/
mx_internal var fauxFocus:DisplayObject;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// showFocusIndicator
//----------------------------------
/**
* @private
* Storage for the showFocusIndicator property.
*/
mx_internal var _showFocusIndicator:Boolean = false;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get showFocusIndicator():Boolean
{
return _showFocusIndicator;
}
/**
* @private
*/
public function set showFocusIndicator(value:Boolean):void
{
var changed:Boolean = _showFocusIndicator != value;
// trace("FM " + this + " showFocusIndicator = " + value);
_showFocusIndicator = value;
if (hasEventListener("showFocusIndicator"))
dispatchEvent(new Event("showFocusIndicator"));
}
//----------------------------------
// defaultButton
//----------------------------------
/**
* @private
* The current default button.
*/
//private var defButton:IButton;
/**
* @private
*/
//private var _defaultButton:IButton;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
//public function get defaultButton():IButton
//{
// return _defaultButton;
//}
/**
* @private
* We don't type the value as Button for dependency reasons
public function set defaultButton(value:IButton):void
{
var button:IButton = value ? IButton(value) : null;
if (button != _defaultButton)
{
if (_defaultButton)
_defaultButton.emphasized = false;
if (defButton)
defButton.emphasized = false;
_defaultButton = button;
if (defButton != _lastFocus || _lastFocus == _defaultButton)
{
defButton = button;
if (button)
button.emphasized = true;
}
}
}
*/
//----------------------------------
// defaultButtonEnabled
//----------------------------------
/**
* @private
* Storage for the defaultButtonEnabled property.
*/
//private var _defaultButtonEnabled:Boolean = true;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
public function get defaultButtonEnabled():Boolean
{
return _defaultButtonEnabled;
}
*/
/**
* @private
public function set defaultButtonEnabled(value:Boolean):void
{
_defaultButtonEnabled = value;
// Synchronize with the new value. We ensure that our
// default button is de-emphasized if defaultButtonEnabled
// is false.
if (defButton)
defButton.emphasized = value;
}
*/
//----------------------------------
// focusPane
//----------------------------------
/**
* @private
* Storage for the focusPane property.
*/
private var _focusPane:Sprite;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get focusPane():Sprite
{
return _focusPane;
}
/**
* @private
*/
public function set focusPane(value:Sprite):void
{
_focusPane = value;
}
//----------------------------------
// form
//----------------------------------
/**
* @private
* Storage for the form property.
*/
private var _form:IFocusManagerContainer;
/**
* @private
* The form is the property where we store the IFocusManagerContainer
* that hosts this FocusManager.
*/
mx_internal function get form():IFocusManagerContainer
{
return _form;
}
/**
* @private
*/
mx_internal function set form (value:IFocusManagerContainer):void
{
_form = value;
}
//----------------------------------
// _lastFocus
//----------------------------------
/**
* @private
* the object that last had focus
*/
private var _lastFocus:IFocusManagerComponent;
/**
* @private
*/
mx_internal function get lastFocus():IFocusManagerComponent
{
return _lastFocus;
}
/**
* @private
*/
mx_internal function set lastFocus(value:IFocusManagerComponent):void
{
_lastFocus = value;
}
//----------------------------------
// nextTabIndex
//----------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get nextTabIndex():int
{
return getMaxTabIndex() + 1;
}
/**
* Gets the highest tab index currently used in this Focus Manager's form or subform.
*
* @return Highest tab index currently used.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function getMaxTabIndex():int
{
var z:Number = 0;
var n:int = focusableObjects.length;
for (var i:int = 0; i < n; i++)
{
var t:Number = focusableObjects[i].tabIndex;
if (!isNaN(t))
z = Math.max(z, t);
}
return z;
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getFocus():IFocusManagerComponent
{
var stage:Stage = Sprite(form)./*systemManager.*/stage;
if (!stage)
return null;
var o:InteractiveObject = stage.focus;
// If a Stage* object (such as StageText or StageWebView) has focus,
// stage.focus will be set to null. Much of the focus framework is not
// set up to handle this. So, if stage.focus is null, we return the last
// IFocusManagerComponent that had focus. In ADL, focus works slightly
// different than it does on device when using StageText. In ADL, when
// the focus is a StageText component, a TextField whose parent is the
// stage is assigned focus.
if ((!o && _lastFocus) || (o is TextField && o.parent == stage))
return _lastFocus;
return findFocusManagerComponent(o);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function setFocus(o:IFocusManagerComponent):void
{
// trace("FM " + this + " setting focus to " + o);
o.setFocus();
if (hasEventListener("setFocus"))
dispatchEvent(new Event("setFocus"));
// trace("FM set focus");
}
/**
* @private
*/
private function focusInHandler(event:FocusEvent):void
{
var target:InteractiveObject = InteractiveObject(event.target);
// trace("FocusManager focusInHandler in = " + this._form.systemManager.loaderInfo.url);
// trace("FM " + this + " focusInHandler " + target);
// dispatch cancelable FocusIn to see if Marshal Plan mixin wants it
if (hasEventListener(FocusEvent.FOCUS_IN))
if (!dispatchEvent(new FocusEvent(FocusEvent.FOCUS_IN, false, true, target)))
return;
if (isParent(DisplayObjectContainer(form), target))
{
/*
if (_defaultButton)
{
if (target is IButton && target != _defaultButton
&& !(target is IToggleButton))
_defaultButton.emphasized = false;
else if (_defaultButtonEnabled)
_defaultButton.emphasized = true;
}
*/
// trace("FM " + this + " setting last focus " + target);
_lastFocus = findFocusManagerComponent(InteractiveObject(target));
/*
if (Capabilities.hasIME)
{
var usesIME:Boolean;
if (_lastFocus is IIMESupport)
{
var imeFocus:IIMESupport = IIMESupport(_lastFocus);
if (imeFocus.enableIME)
usesIME = true;
}
if (IMEEnabled)
IME.enabled = usesIME;
}
*/
/*
// handle default button here
// we can't check for Button because of cross-versioning so
// for now we just check for an emphasized property
if (_lastFocus is IButton && !(_lastFocus is IToggleButton))
{
defButton = _lastFocus as IButton;
}
else
{
// restore the default button to be the original one
if (defButton && defButton != _defaultButton)
defButton = _defaultButton;
}
*/
}
}
/**
* @private Useful for debugging
*/
private function focusOutHandler(event:FocusEvent):void
{
var target:InteractiveObject = InteractiveObject(event.target);
// trace("FocusManager focusOutHandler in = " + this._form.systemManager.loaderInfo.url);
// trace("FM " + this + " focusOutHandler " + target);
}
/**
* @private
* restore focus to whoever had it last
*/
private function activateHandler(event:Event):void
{
// var target:InteractiveObject = InteractiveObject(event.target);
// trace("FM " + this + " activateHandler ", _lastFocus);
// if we were the active FM when we were deactivated
// and we're not running in AIR, then dispatch the event now
// otherwise wait for the AIR events to fire
if (activated && !desktopMode)
{
dispatchEvent(new FlexEvent(FlexEvent.FLEX_WINDOW_ACTIVATE));
// restore focus if this focus manager had last focus
if (_lastFocus && (!browserMode || ieshifttab))
_lastFocus.setFocus();
lastAction = "ACTIVATE";
}
}
/**
* @private
* Dispatch event if we're not running in AIR. AIR will
* dispatch windowDeactivate that we respond to instead
*/
private function deactivateHandler(event:Event):void
{
// var target:InteractiveObject = InteractiveObject(event.target);
// trace("FM " + this + " deactivateHandler ", _lastFocus);
// if we are the active FM when we were deactivated
// and we're not running in AIR, then dispatch the event now
// otherwise wait for the AIR events to fire
if (activated && !desktopMode)
{
dispatchEvent(new FlexEvent(FlexEvent.FLEX_WINDOW_DEACTIVATE));
}
}
/**
* @private
* restore focus to whoever had it last
*/
private function activateWindowHandler(event:Event):void
{
// var target:InteractiveObject = InteractiveObject(event.target);
// trace("FM " + this + " activateWindowHandler ", _lastFocus);
windowActivated = true;
if (activated)
{
dispatchEvent(new FlexEvent(FlexEvent.FLEX_WINDOW_ACTIVATE));
// restore focus if this focus manager had last focus
if (_lastFocus && !browserMode)
_lastFocus.setFocus();
lastAction = "ACTIVATE";
}
}
/**
* @private
* If we're responsible for the focused control, remove focus from it
* so it gets the same events as it would if the whole app lost focus
*/
private function deactivateWindowHandler(event:Event):void
{
// var target:InteractiveObject = InteractiveObject(event.target);
// trace("FM " + this + " deactivateWindowHandler ", _lastFocus);
/*
windowActivated = false;
if (activated)
{
dispatchEvent(new FlexEvent(FlexEvent.FLEX_WINDOW_DEACTIVATE));
if (form.systemManager.stage)
form.systemManager.stage.focus = null;
}
*/
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function showFocus():void
{
/*
if (!showFocusIndicator)
{
showFocusIndicator = true;
if (_lastFocus)
_lastFocus.drawFocus(true);
}
*/
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function hideFocus():void
{
// trace("FOcusManger " + this + " Hide Focus");
/*
if (showFocusIndicator)
{
showFocusIndicator = false;
if (_lastFocus)
_lastFocus.drawFocus(false);
}
*/
// trace("END FOcusManger Hide Focus");
}
/**
* The SystemManager activates and deactivates a FocusManager
* if more than one IFocusManagerContainer is visible at the same time.
* If the mouse is clicked in an IFocusManagerContainer with a deactivated
* FocusManager, the SystemManager will call
* the <code>activate()</code> method on that FocusManager.
* The FocusManager that was activated will have its <code>deactivate()</code> method
* called prior to the activation of another FocusManager.
*
* <p>The FocusManager adds event handlers that allow it to monitor
* focus related keyboard and mouse activity.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function activate():void
{
// we can get a double activation if we're popping up and becoming visible
// like the second time a menu appears
if (activated)
{
// trace("FocusManager is already active " + this);
return;
}
// trace("FocusManager activating = " + this._form.systemManager.loaderInfo.url);
// trace("FocusManager activating " + this);
// listen for focus changes, use weak references for the stage
// form.systemManager can be null if the form is created in a sandbox and
// added as a child to the root system manager.
var sm:ISystemManager = form.systemManager;
if (sm)
{
/*
if (sm.isTopLevelRoot())
{
sm.stage.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, mouseFocusChangeHandler, false, 0, true);
sm.stage.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler, false, 0, true);
sm.stage.addEventListener(Event.ACTIVATE, activateHandler, false, 0, true);
sm.stage.addEventListener(Event.DEACTIVATE, deactivateHandler, false, 0, true);
}
else
{
*/
sm.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, mouseFocusChangeHandler, false, 0, true);
sm.addEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler, false, 0, true);
sm.addEventListener(Event.ACTIVATE, activateHandler, false, 0, true);
sm.addEventListener(Event.DEACTIVATE, deactivateHandler, false, 0, true);
//}
}
form.addEventListener(FocusEvent.FOCUS_IN, focusInHandler, true);
form.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler, true);
form.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
form.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownCaptureHandler, true);
//form.addEventListener(KeyboardEvent.KEY_DOWN, defaultButtonKeyHandler);
form.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, true);
if (sm)
{
// AIR Window events, but don't want to link in AIREvent
// use capture phase because these get sent by the main Window
// and we might be managing a popup in that window
sm.addEventListener("windowActivate", activateWindowHandler, true, 0, true);
sm.addEventListener("windowDeactivate", deactivateWindowHandler, true, 0, true);
}
activated = true;
dispatchEvent(new FlexEvent(FlexEvent.FLEX_WINDOW_ACTIVATE));
// Restore focus to the last control that had it if there was one.
if (_lastFocus)
setFocus(_lastFocus);
if (hasEventListener("activateFM"))
dispatchEvent(new Event("activateFM"));
}
/**
* The SystemManager activates and deactivates a FocusManager
* if more than one IFocusManagerContainer is visible at the same time.
* If the mouse is clicked in an IFocusManagerContainer with a deactivated
* FocusManager, the SystemManager will call
* the <code>activate()</code> method on that FocusManager.
* The FocusManager that was activated will have its <code>deactivate()</code> method
* called prior to the activation of another FocusManager.
*
* <p>The FocusManager removes event handlers that allow it to monitor
* focus related keyboard and mouse activity.</p>
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function deactivate():void
{
// trace("FocusManager deactivating " + this);
// trace("FocusManager deactivating = " + this._form.systemManager.loaderInfo.url);
// listen for focus changes
var sm:ISystemManager = form.systemManager;
if (sm)
{
/*
if (sm.isTopLevelRoot())
{
sm.stage.removeEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, mouseFocusChangeHandler);
sm.stage.removeEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler);
sm.stage.removeEventListener(Event.ACTIVATE, activateHandler);
sm.stage.removeEventListener(Event.DEACTIVATE, deactivateHandler);
}
else
{
*/
sm.removeEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, mouseFocusChangeHandler);
sm.removeEventListener(FocusEvent.KEY_FOCUS_CHANGE, keyFocusChangeHandler);
sm.removeEventListener(Event.ACTIVATE, activateHandler);
sm.removeEventListener(Event.DEACTIVATE, deactivateHandler);
//}
}
form.removeEventListener(FocusEvent.FOCUS_IN, focusInHandler, true);
form.removeEventListener(FocusEvent.FOCUS_OUT, focusOutHandler, true);
form.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
form.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownCaptureHandler, true);
//form.removeEventListener(KeyboardEvent.KEY_DOWN, defaultButtonKeyHandler);
// stop listening for default button in Capture phase
form.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler, true);
activated = false;
dispatchEvent(new FlexEvent(FlexEvent.FLEX_WINDOW_DEACTIVATE));
if (hasEventListener("deactivateFM"))
dispatchEvent(new Event("deactivateFM"));
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function findFocusManagerComponent(
o:InteractiveObject):IFocusManagerComponent
{
return findFocusManagerComponent2(o) as IFocusManagerComponent;
}
/**
* @private
*
* This version of the method differs from the old one to support SWFLoader
* being in the focusableObjects list but not being a component that
* gets focus. SWFLoader is in the list of focusable objects so
* focus may be passed over a bridge to the components on the other
* side of the bridge.
*/
private function findFocusManagerComponent2(
o:InteractiveObject):DisplayObject
{
try
{
while (o)
{
if ((o is IFocusManagerComponent && IFocusManagerComponent(o).focusEnabled) /*||
o is ISWFLoader*/)
return o;
o = o.parent;
}
}
catch (error:SecurityError)
{
// can happen in a loaded child swf
// trace("findFocusManagerComponent: handling security error");
}
// tab was set somewhere else
return null;
}
/**
* @private
* Returns true if p is a parent of o.
*/
private function isParent(p:DisplayObjectContainer, o:DisplayObject):Boolean
{
if (p == o)
return false;
//if (p is IRawChildrenContainer)
// return IRawChildrenContainer(p).rawChildren.contains(o);
return p.contains(o);
}
private function isEnabledAndVisible(o:DisplayObject):Boolean
{
var formParent:DisplayObjectContainer = DisplayObjectContainer(form);
while (o != formParent)
{
if (o is IUIComponent)
if (!IUIComponent(o).enabled)
return false;
/*
if (o is IVisualElement)
if (IVisualElement(o).designLayer && !IVisualElement(o).designLayer.effectiveVisibility)
return false;
*/
if (!o.visible)
return false;
o = o.parent;
// if no parent, then not on display list
if (!o)
return false;
}
return true;
}
/**
* @private
*/
private function sortByTabIndex(a:InteractiveObject, b:InteractiveObject):int
{
var aa:int = a.tabIndex;
var bb:int = b.tabIndex;
if (aa == -1)
aa = int.MAX_VALUE;
if (bb == -1)
bb = int.MAX_VALUE;
return (aa > bb ? 1 :
aa < bb ? -1 : sortByDepth(DisplayObject(a), DisplayObject(b)));
}
/**
* @private
*/
private function sortFocusableObjectsTabIndex():void
{
// trace("FocusableObjectsTabIndex");
focusableCandidates = [];
var n:int = focusableObjects.length;
for (var i:int = 0; i < n; i++)
{
var c:IFocusManagerComponent = focusableObjects[i] as IFocusManagerComponent;
if ((c && c.tabIndex && !isNaN(Number(c.tabIndex))) /*||
focusableObjects[i] is ISWFLoader*/)
{
// if we get here, it is a candidate
focusableCandidates.push(focusableObjects[i]);
}
}
focusableCandidates.sort(sortByTabIndex);
}
/**
* @private
*/
private function sortByDepth(aa:DisplayObject, bb:DisplayObject):Number
{
var val1:String = "";
var val2:String = "";
var index:int;
var tmp:String;
var tmp2:String;
var zeros:String = "0000";
var a:DisplayObject = DisplayObject(aa);
var b:DisplayObject = DisplayObject(bb);
// TODO (egreenfi): If a component lives inside of a group, we care about not its display object index, but
// its index within the group. See SDK-25144
while (a != DisplayObject(form) && a.parent)
{
index = getChildIndex(a.parent, a);
tmp = index.toString(16);
if (tmp.length < 4)
{
tmp2 = zeros.substring(0, 4 - tmp.length) + tmp;
}
val1 = tmp2 + val1;
a = a.parent;
}
while (b != DisplayObject(form) && b.parent)
{
index = getChildIndex(b.parent, b);
tmp = index.toString(16);
if (tmp.length < 4)
{
tmp2 = zeros.substring(0, 4 - tmp.length) + tmp;
}
val2 = tmp2 + val2;
b = b.parent;
}
return val1 > val2 ? 1 : val1 < val2 ? -1 : 0;
}
private function getChildIndex(parent:DisplayObjectContainer, child:DisplayObject):int
{
try
{
return parent.getChildIndex(child);
}
catch(e:Error)
{
//if (parent is IRawChildrenContainer)
// return IRawChildrenContainer(parent).rawChildren.getChildIndex(child);
throw e;
}
throw new Error("FocusManager.getChildIndex failed"); // shouldn't ever get here
}
/**
* @private
* Calculate what focusableObjects are valid tab candidates.
*/
private function sortFocusableObjects():void
{
// trace("FocusableObjects " + focusableObjects.length.toString());
focusableCandidates = [];
var n:int = focusableObjects.length;
for (var i:int = 0; i < n; i++)
{
var c:InteractiveObject = focusableObjects[i];
// trace(" " + c);
if (c.tabIndex && !isNaN(Number(c.tabIndex)) && c.tabIndex > 0)
{
sortFocusableObjectsTabIndex();
return;
}
focusableCandidates.push(c);
}
focusableCandidates.sort(sortByDepth);
}
/**
* Call this method to make the system
* think the Enter key was pressed and the defaultButton was clicked
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
mx_internal function sendDefaultButtonEvent():void
{
// trace("FocusManager.sendDefaultButtonEvent " + defButton);
defButton.dispatchEvent(new MouseEvent("click"));
}
*/
/**
* @private
* Do a tree walk and add all children you can find.
*/
mx_internal function addFocusables(o:DisplayObject, skipTopLevel:Boolean = false):void
{
// trace(">>addFocusables " + o);
if ((o is IFocusManagerComponent) && !skipTopLevel)
{
var addToFocusables:Boolean = false;
if (o is IFocusManagerComponent)
{
var focusable:IFocusManagerComponent = IFocusManagerComponent(o);
if (focusable.focusEnabled)
{
if (focusable.tabFocusEnabled && isTabVisible(o))
{
addToFocusables = true;
}
}
}
if (addToFocusables)
{
if (focusableObjects.indexOf(o) == -1)
{
focusableObjects.push(o);
calculateCandidates = true;
// trace("FM added " + o);
}
}
o.addEventListener("tabFocusEnabledChange", tabFocusEnabledChangeHandler);
o.addEventListener("tabIndexChange", tabIndexChangeHandler);
}
if (o is DisplayObjectContainer)
{
var doc:DisplayObjectContainer = DisplayObjectContainer(o);
// Even if they aren't focusable now,
// listen in case they become later.
var checkChildren:Boolean;
if (o is IFocusManagerComponent)
{
o.addEventListener("hasFocusableChildrenChange", hasFocusableChildrenChangeHandler);
checkChildren = IFocusManagerComponent(o).hasFocusableChildren;
}
else
{
o.addEventListener("tabChildrenChange", tabChildrenChangeHandler);
checkChildren = doc.tabChildren;
}
var i:int;
if (checkChildren)
{
/*
if (o is IRawChildrenContainer)
{
// trace("using view rawChildren");
var rawChildren:IChildList = IRawChildrenContainer(o).rawChildren;
// recursively visit and add children of components
// we don't do this for containers because we get individual
// adds for the individual children
for (i = 0; i < rawChildren.numChildren; i++)
{
try
{
addFocusables(rawChildren.getChildAt(i));
}
catch(error:SecurityError)
{
// Ignore this child if we can't access it
// trace("addFocusables: ignoring security error getting child from rawChildren: " + error);
}
}
}
else
{
*/
// trace("using container's children");
// recursively visit and add children of components
// we don't do this for containers because we get individual
// adds for the individual children
for (i = 0; i < doc.numChildren; i++)
{
try
{
addFocusables(doc.getChildAt(i));
}
catch(error:SecurityError)
{
// Ignore this child if we can't access it
// trace("addFocusables: ignoring security error getting child at document." + error);
}
}
//}
}
}
// trace("<<addFocusables " + o);
}
/**
* @private
* is it really tabbable?
*/
private function isTabVisible(o:DisplayObject):Boolean
{
var s:DisplayObject = DisplayObject(form.systemManager);
if (!s) return false;
var p:DisplayObjectContainer = o.parent;
while (p && p != s)
{
if (!p.tabChildren)
return false;
if (p is IFocusManagerComponent && !(IFocusManagerComponent(p).hasFocusableChildren))
return false;
p = p.parent;
}
return true;
}
private function isValidFocusCandidate(o:DisplayObject, g:String):Boolean
{
if (o is IFocusManagerComponent)
if (!IFocusManagerComponent(o).focusEnabled)
return false;
if (!isEnabledAndVisible(o))
return false;
if (o is IFocusManagerGroup)
{
// reject if it is in the same tabgroup
var tg:IFocusManagerGroup = IFocusManagerGroup(o);
if (g == tg.groupName) return false;
}
return true;
}
private function getIndexOfFocusedObject(o:DisplayObject):int
{
if (!o)
return -1;
var n:int = focusableCandidates.length;
// trace(" focusableCandidates " + n);
var i:int = 0;
for (i = 0; i < n; i++)
{
// trace(" comparing " + focusableCandidates[i]);
if (focusableCandidates[i] == o)
return i;
}
// no match? try again with a slower match for certain
// cases like DG editors
for (i = 0; i < n; i++)
{
var iui:IUIComponent = focusableCandidates[i] as IUIComponent;
if (iui && iui.owns(o as IUIComponent))
return i;
}
return -1;
}
private function getIndexOfNextObject(i:int, shiftKey:Boolean, bSearchAll:Boolean, groupName:String):int
{
var n:int = focusableCandidates.length;
var start:int = i;
while (true)
{
if (shiftKey)
i--;
else
i++;
if (bSearchAll)
{
if (shiftKey && i < 0)
break;
if (!shiftKey && i == n)
break;
}
else
{
i = (i + n) % n;
// came around and found the original
if (start == i)
break;
// if start is -1, set start to first valid value of i
if (start == -1)
start = i;
}
// trace("testing " + focusableCandidates[i]);
if (isValidFocusCandidate(focusableCandidates[i], groupName))
{
// trace(" stopped at " + i);
var o:DisplayObject = DisplayObject(findFocusManagerComponent2(focusableCandidates[i]));
if (o is IFocusManagerGroup)
{
// when landing on an element that is part of group, try to
// advance selection to the selected group element
var j:int;
var obj:DisplayObject;
var tg1:IFocusManagerGroup = IFocusManagerGroup(o);
var tg2:IFocusManagerGroup;
// normalize the "no selected group element" case
// to the "first group element selected" case
// (respecting the tab direction)
var groupElementToFocus:IFocusManagerGroup = null;
for (j = 0; j < focusableCandidates.length; j++)
{
obj = focusableCandidates[j];
if (obj is IFocusManagerGroup)
{
tg2 = IFocusManagerGroup(obj);
if (tg2.groupName == tg1.groupName && isEnabledAndVisible(obj) &&
tg2["document"] == tg1["document"])
{
if (tg2.selected)
{
groupElementToFocus = tg2;
break;
}
if ((!shiftKey && groupElementToFocus == null) || shiftKey)
groupElementToFocus = tg2;
}
}
}
if (tg1 != groupElementToFocus)
{
var foundAnotherGroup:Boolean = false;
// cycle the entire focusable candidates array forward or backward,
// wrapping around boundaries, searching for our focus candidate
j = i;
for (var k:int = 0; k < focusableCandidates.length - 1; k++)
{
if (!shiftKey)
{
j++;
if (j == focusableCandidates.length)
j = 0;
}
else
{
j--;
if (j == -1)
j = focusableCandidates.length - 1;
}
obj = focusableCandidates[j];
if (isEnabledAndVisible(obj))
{
if (foundAnotherGroup)
{
// we're now just trying to find a selected member of this group
if (obj is IFocusManagerGroup)
{
tg2 = IFocusManagerGroup(obj);
if (tg2.groupName == tg1.groupName && tg2["document"] == tg1["document"])
{
if (tg2.selected)
{
i = j;
break;
}
}
}
}
else if (obj is IFocusManagerGroup)
{
tg2 = IFocusManagerGroup(obj);
if (tg2.groupName == tg1.groupName && tg2["document"] == tg1["document"])
{
if (tg2 == groupElementToFocus)
{
// if objects of same group have different tab index
// skip you aren't selected.
if (InteractiveObject(obj).tabIndex != InteractiveObject(o).tabIndex && !tg1.selected)
return getIndexOfNextObject(i, shiftKey, bSearchAll, groupName);
i = j;
break;
}
}
else
{
// switch to new group and hunt for selected item
tg1 = tg2;
i = j;
// element is part of another group, stop if selected
if (tg2.selected)
break;
else
foundAnotherGroup = true;
}
}
else
{
// element isn't part of any group, stop
i = j;
break;
}
}
}
}
}
return i;
}
}
return i;
}
/**
* @private
*/
private function setFocusToNextObject(event:FocusEvent):void
{
focusChanged = false;
if (focusableObjects.length == 0)
return;
var focusInfo:FocusInfo = getNextFocusManagerComponent2(event.shiftKey, fauxFocus);
// trace("winner = ", focusInfo.displayObject);
// If we are about to wrap focus around, send focus back to the parent.
if (!popup && (focusInfo.wrapped || !focusInfo.displayObject))
{
if (hasEventListener("focusWrapping"))
if (!dispatchEvent(new FocusEvent("focusWrapping", false, true, null, event.shiftKey)))
return;
}
if (!focusInfo.displayObject)
{
event.preventDefault();
return;
}
setFocusToComponent(focusInfo.displayObject, event.shiftKey);
}
private function setFocusToComponent(o:Object, shiftKey:Boolean):void
{
focusChanged = false;
if (o)
{
if (hasEventListener("setFocusToComponent"))
if (!dispatchEvent(new FocusEvent("setFocusToComponent", false, true, InteractiveObject(o), shiftKey)))
return;
if (o is IFocusManagerComplexComponent)
{
IFocusManagerComplexComponent(o).assignFocus(shiftKey ? "bottom" : "top");
focusChanged = true;
}
else if (o is IFocusManagerComponent)
{
setFocus(IFocusManagerComponent(o));
focusChanged = true;
}
}
}
/**
* @private
*/
mx_internal function setFocusToNextIndex(index:int, shiftKey:Boolean):void
{
if (focusableObjects.length == 0)
return;
// I think we'll have time to do this here instead of at creation time
// this makes and orders the focusableCandidates array
if (calculateCandidates)
{
sortFocusableObjects();
calculateCandidates = false;
}
var focusInfo:FocusInfo = getNextFocusManagerComponent2(shiftKey, null, index);
// If we are about to wrap focus around, send focus back to the parent.
if (!popup && focusInfo.wrapped)
{
if (hasEventListener("setFocusToNextIndex"))
if (!dispatchEvent(new FocusEvent("setFocusToNextIndex", false, true, null, shiftKey)))
return;
}
setFocusToComponent(focusInfo.displayObject, shiftKey);
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getNextFocusManagerComponent(
backward:Boolean = false):IFocusManagerComponent
{
const focusInfo:FocusInfo = getNextFocusManagerComponent2(backward, fauxFocus);
return focusInfo ? focusInfo.displayObject as IFocusManagerComponent : null;
}
/**
* Find the next object to set focus to.
*
* @param backward true if moving in the backwards in the tab order, false if moving forward.
* @param fromObject object to move focus from, if null move from the current focus.
* @param formIndex index to move focus from, if specified use fromIndex to find the
* object, not fromObject.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
private function getNextFocusManagerComponent2(
backward:Boolean = false,
fromObject:DisplayObject = null,
fromIndex:int = FROM_INDEX_UNSPECIFIED):FocusInfo
{
if (focusableObjects.length == 0)
return null;
// I think we'll have time to do this here instead of at creation time
// this makes and orders the focusableCandidates array
if (calculateCandidates)
{
sortFocusableObjects();
calculateCandidates = false;
}
// trace("focus was at " + fromObject);
// trace("focusableObjects " + focusableObjects.length);
var i:int = fromIndex;
if (fromIndex == FROM_INDEX_UNSPECIFIED)
{
// if there is no passed in object, then get the object that has the focus
var o:DisplayObject = fromObject;
if (!o)
o = Sprite(form)./*systemManager,*/stage.focus;
else if (o == Sprite(form)./*systemManager.*/stage)
o == null;
o = DisplayObject(findFocusManagerComponent2(InteractiveObject(o)));
var g:String = "";
if (o is IFocusManagerGroup)
{
var tg:IFocusManagerGroup = IFocusManagerGroup(o);
g = tg.groupName;
}
i = getIndexOfFocusedObject(o);
}
// trace(" starting at " + i);
var bSearchAll:Boolean = false;
var start:int = i;
if (i == -1) // we didn't find it
{
if (backward)
i = focusableCandidates.length;
bSearchAll = true;
// trace("search all " + i);
}
var j:int = getIndexOfNextObject(i, backward, bSearchAll, g);
// if we wrapped around, get if we have a parent we should pass
// focus to.
var wrapped:Boolean = false;
if (backward)
{
if (j >= i)
wrapped = true;
}
else if (j <= i)
wrapped = true;
var focusInfo:FocusInfo = new FocusInfo();
focusInfo.displayObject = findFocusManagerComponent2(focusableCandidates[j]);
focusInfo.wrapped = wrapped;
return focusInfo;
}
/**
* @private
*/
private function getTopLevelFocusTarget(o:InteractiveObject):InteractiveObject
{
while (o != InteractiveObject(form))
{
if (o is IFocusManagerComponent &&
IFocusManagerComponent(o).focusEnabled &&
/*IFocusManagerComponent(o).mouseFocusEnabled &&*/
(o is IUIComponent ? IUIComponent(o).enabled : true))
return o;
if (hasEventListener("getTopLevelFocusTarget"))
if (!dispatchEvent(new FocusEvent("getTopLevelFocusTarget", false, true, o.parent)))
return null;
o = o.parent;
if (o == null)
break;
}
return null;
}
/**
* Returns a String representation of the component hosting the FocusManager object,
* with the String <code>".focusManager"</code> appended to the end of the String.
*
* @return Returns a String representation of the component hosting the FocusManager object,
* with the String <code>".focusManager"</code> appended to the end of the String.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
override public function toString():String
{
return Object(form).toString() + ".focusManager";
}
/**
* @private
*
* Clear the browser focus component and undo any tab index we may have set.
*/
private function clearBrowserFocusComponent():void
{
if (browserFocusComponent)
{
if (browserFocusComponent.tabIndex == LARGE_TAB_INDEX)
browserFocusComponent.tabIndex = -1;
browserFocusComponent = null;
}
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/**
* @private
* Listen for children being added
* and see if they are focus candidates.
*/
private function addedHandler(event:Event):void
{
var target:DisplayObject = DisplayObject(event.target);
// trace("FM: addedHandler: got added for " + target);
// if it is truly parented, add it, otherwise it will get added when the top of the tree
// gets parented.
if (target.stage)
{
// trace("FM: addedHandler: adding focusables");
addFocusables(DisplayObject(event.target));
}
}
/**
* @private
* Listen for children being removed.
*/
private function removedHandler(event:Event):void
{
var i:int;
var o:DisplayObject = DisplayObject(event.target);
var focusPaneParent:DisplayObject = focusPane ? focusPane.parent : null;
// Remove the focusPane to allow the focusOwner to be garbage collected.
// Avoid recursion by not processing the removal of the focusPane itself.
/*
if (focusPaneParent && o != focusPane)
{
if (o is DisplayObjectContainer &&
isParent(DisplayObjectContainer(o), focusPane))
{
if (focusPaneParent is ISystemManager)
ISystemManager(focusPaneParent).focusPane = null;
else
IUIComponent(focusPaneParent).focusPane = null;
}
}
*/
// trace("FM got added for " + event.target);
if (o is IFocusManagerComponent)
{
for (i = 0; i < focusableObjects.length; i++)
{
if (o == focusableObjects[i])
{
/*
if (o == _lastFocus)
{
_lastFocus.drawFocus(false);
_lastFocus = null;
}
*/
// trace("FM removed " + o);
focusableObjects.splice(i, 1);
focusableCandidates = [];
calculateCandidates = true;
break;
}
}
o.removeEventListener("tabFocusEnabledChange", tabFocusEnabledChangeHandler);
o.removeEventListener("tabIndexChange", tabIndexChangeHandler);
}
removeFocusables(o, false);
}
/**
* @private
*/
private function removeFocusables(o:DisplayObject, dontRemoveTabChildrenHandler:Boolean):void
{
var i:int;
if (o is DisplayObjectContainer)
{
if (!dontRemoveTabChildrenHandler)
{
o.removeEventListener("tabChildrenChange", tabChildrenChangeHandler);
o.removeEventListener("hasFocusableChildrenChange", hasFocusableChildrenChangeHandler);
}
for (i = 0; i < focusableObjects.length; i++)
{
if (isParent(DisplayObjectContainer(o), focusableObjects[i]))
{
/*
if (focusableObjects[i] == _lastFocus)
{
_lastFocus.drawFocus(false);
_lastFocus = null;
}
*/
// trace("FM removed " + focusableObjects[i]);
focusableObjects[i].removeEventListener(
"tabFocusEnabledChange", tabFocusEnabledChangeHandler);
focusableObjects[i].removeEventListener(
"tabIndexChange", tabIndexChangeHandler);
focusableObjects.splice(i, 1);
i = i - 1; // because increment would skip one
focusableCandidates = [];
calculateCandidates = true;
}
}
}
}
/**
* @private
*/
private function showHandler(event:Event):void
{
/*
var awm:IActiveWindowManager =
IActiveWindowManager(form.systemManager.getImplementation("mx.managers::IActiveWindowManager"));
if (awm)
awm.activate(form); // build a message that does the equal
*/
}
/**
* @private
*/
private function hideHandler(event:Event):void
{
/*
var awm:IActiveWindowManager =
IActiveWindowManager(form.systemManager.getImplementation("mx.managers::IActiveWindowManager"));
if (awm)
awm.deactivate(form); // build a message that does the equal
*/
}
/**
* @private
*/
private function childHideHandler(event:Event):void
{
var target:DisplayObject = DisplayObject(event.target);
// trace("FocusManager focusInHandler in = " + this._form.systemManager.loaderInfo.url);
// trace("FM " + this + " focusInHandler " + target);
if (lastFocus && !isEnabledAndVisible(DisplayObject(lastFocus)) && DisplayObject(form).stage)
{
DisplayObject(form).stage.focus = null;
lastFocus = null;
}
}
/**
* @private
*/
private function viewHideHandler(event:Event):void
{
// Target is the active view that is about to be hidden
var target:DisplayObjectContainer = event.target as DisplayObjectContainer;
var lastFocusDO:DisplayObject = lastFocus as DisplayObject;
// If the lastFocus is in the view about to be hidden, clear focus
if (target && lastFocusDO && target.contains(lastFocusDO))
lastFocus = null;
}
/**
* @private
*/
private function creationCompleteHandler(event:FlexEvent):void
{
/*
var o:DisplayObject = DisplayObject(form);
if (o.parent && o.visible && !activated)
{
var awm:IActiveWindowManager =
IActiveWindowManager(form.systemManager.getImplementation("mx.managers::IActiveWindowManager"));
if (awm)
awm.activate(form); // build a message that does the equal
}
*/
}
/**
* @private
* Add or remove if tabbing properties change.
*/
private function tabIndexChangeHandler(event:Event):void
{
calculateCandidates = true;
}
/**
* @private
* Add or remove if tabbing properties change.
*/
private function tabFocusEnabledChangeHandler(event:Event):void
{
calculateCandidates = true;
var o:IFocusManagerComponent = IFocusManagerComponent(event.target);
var n:int = focusableObjects.length;
for (var i:int = 0; i < n; i++)
{
if (focusableObjects[i] == o)
break;
}
if (o.tabFocusEnabled)
{
if (i == n && isTabVisible(DisplayObject(o)))
{
// trace("FM tpc added " + o);
// add it if were not already
if (focusableObjects.indexOf(o) == -1)
focusableObjects.push(o);
}
}
else
{
// remove it
if (i < n)
{
// trace("FM tpc removed " + o);
focusableObjects.splice(i, 1);
}
}
}
/**
* @private
* Add or remove if tabbing properties change.
*/
private function tabChildrenChangeHandler(event:Event):void
{
if (event.target != event.currentTarget)
return;
calculateCandidates = true;
var o:DisplayObjectContainer = DisplayObjectContainer(event.target);
if (o.tabChildren)
{
addFocusables(o, true);
}
else
{
removeFocusables(o, true);
}
}
/**
* @private
* Add or remove if tabbing properties change.
*/
private function hasFocusableChildrenChangeHandler(event:Event):void
{
if (event.target != event.currentTarget)
return;
calculateCandidates = true;
var o:IFocusManagerComponent = IFocusManagerComponent(event.target);
if (o.hasFocusableChildren)
{
addFocusables(DisplayObject(o), true);
}
else
{
removeFocusables(DisplayObject(o), true);
}
}
/**
* @private
* This gets called when mouse clicks on a focusable object.
* We block player behavior
*/
private function mouseFocusChangeHandler(event:FocusEvent):void
{
// trace("FocusManager: mouseFocusChangeHandler in = " + this._form.systemManager.loaderInfo.url);
// trace("FocusManager: mouseFocusChangeHandler " + event);
if (event.isDefaultPrevented())
return;
// If relatedObject is null because we don't have access to the
// object getting focus then allow the Player to set focus
// to the object. The isRelatedObjectInaccessible property is
// Player 10 only so we have to test if it is available. We
// will only see isRelatedObjectInaccessible if we are a version "10" swf
// (-target-player=10). Version "9" swfs will not see the property
// even if running in Player 10.
if (event.relatedObject == null &&
"isRelatedObjectInaccessible" in event &&
event["isRelatedObjectInaccessible"] == true)
{
// lost focus to a control in different sandbox.
return;
}
if (event.relatedObject is TextField)
{
var tf:TextField = event.relatedObject as TextField;
if (tf.type == "input" || tf.selectable)
{
return; // pass it on
}
}
event.preventDefault();
}
/**
* @private
* This gets called when the tab key is hit.
*/
mx_internal function keyFocusChangeHandler(event:FocusEvent):void
{
// trace("keyFocusChangeHandler handled by " + this);
// trace("keyFocusChangeHandler event = " + event);
var sm:ISystemManager = form.systemManager;
if (hasEventListener("keyFocusChange"))
if (!dispatchEvent(new FocusEvent("keyFocusChange", false, true, InteractiveObject(event.target))))
return;
showFocusIndicator = true;
focusChanged = false;
var haveBrowserFocusComponent:Boolean = (browserFocusComponent != null);
if (browserFocusComponent)
clearBrowserFocusComponent();
// see if we got here from a tab. We also need to check for
// keyCode == 0 because in IE sometimes the first time you tab
// in to the flash player, you get keyCode == 0 instead of TAB.
// Flash Player bug #2295688.
if ((event.keyCode == Keyboard.TAB || (browserMode && event.keyCode == 0))
&& !event.isDefaultPrevented())
{
if (haveBrowserFocusComponent)
{
if (hasEventListener("browserFocusComponent"))
dispatchEvent(new FocusEvent("browserFocusComponent", false, false, InteractiveObject(event.target)));
return;
}
/*
if (ieshifttab && lastAction == "ACTIVATE")
{
// IE seems to now require that we set focus to something during activate
// but then we get this keyFocusChange event. I think we used to not
// need to set focus on activate and we still got the keyFocusChange
// and then stage.focus was null and we'd use the keyFocusChange event
// to determine which control (first or last) got focus based on
// the shift key.
// If we set focus on activate, then we get this keyFocusChange which moves
// the focus somewhere else, so we set fauxFocus to the stage as a signal
// to the setFocusToNextObject logic that it shouldn't use the stage.focus
// as the starting point.
fauxFocus = sm.stage;
}
*/
// trace("tabHandled by " + this);
setFocusToNextObject(event);
if (ieshifttab && lastAction == "ACTIVATE")
{
fauxFocus = null;
}
// if we changed focus or if we're the main app
// eat the event
/*
if (focusChanged || sm == sm.getTopLevelRoot())
event.preventDefault();
*/
}
}
/**
* @private
* Watch for TAB keys.
*/
mx_internal function keyDownHandler(event:KeyboardEvent):void
{
// trace("onKeyDown handled by " + this);
// trace("onKeyDown event = " + event);
// if the target is in a bridged application, let it handle the click.
var sm:ISystemManager = form.systemManager;
if (hasEventListener("keyDownFM"))
if (!dispatchEvent(new FocusEvent("keyDownFM", false, true, InteractiveObject(event.target))))
return;
/*
if (sm is SystemManager)
SystemManager(sm).idleCounter = 0;
*/
if (event.keyCode == Keyboard.TAB)
{
lastAction = "KEY";
// I think we'll have time to do this here instead of at creation time
// this makes and orders the focusableCandidates array
if (calculateCandidates)
{
sortFocusableObjects();
calculateCandidates = false;
}
}
/*
if (browserMode)
{
if (browserFocusComponent)
clearBrowserFocusComponent();
if (event.keyCode == Keyboard.TAB && focusableCandidates.length > 0)
{
// get the object that has the focus
var o:DisplayObject = fauxFocus;
if (!o)
{
o = form.systemManager.stage.focus;
}
// trace("focus was at " + o);
// trace("focusableObjects " + focusableObjects.length);
o = DisplayObject(findFocusManagerComponent2(InteractiveObject(o)));
var g:String = "";
if (o is IFocusManagerGroup)
{
var tg:IFocusManagerGroup = IFocusManagerGroup(o);
g = tg.groupName;
}
var i:int = getIndexOfFocusedObject(o);
var j:int = getIndexOfNextObject(i, event.shiftKey, false, g);
if (event.shiftKey)
{
if (j >= i)
{
// we wrapped so let browser have it
browserFocusComponent = getBrowserFocusComponent(event.shiftKey);
if (browserFocusComponent.tabIndex == -1)
browserFocusComponent.tabIndex = 0;
}
}
else
{
if (j <= i)
{
// we wrapped so let browser have it
browserFocusComponent = getBrowserFocusComponent(event.shiftKey);
if (browserFocusComponent.tabIndex == -1)
browserFocusComponent.tabIndex = LARGE_TAB_INDEX;
}
}
}
}
*/
}
/**
* @private
* Watch for ENTER key.
private function defaultButtonKeyHandler(event:KeyboardEvent):void
{
var sm:ISystemManager = form.systemManager;
if (hasEventListener("defaultButtonKeyHandler"))
if (!dispatchEvent(new FocusEvent("defaultButtonKeyHandler", false, true)))
return;
if (defaultButtonEnabled && event.keyCode == Keyboard.ENTER &&
defButton && defButton.enabled)
{
sendDefaultButtonEvent();
}
}
*/
/**
* @private
* This gets called when the focus changes due to a mouse click.
*
* Note: If the focus is changing to a TextField, we don't call
* setFocus() on it because the player handles it;
* calling setFocus() on a TextField which has scrollable text
* causes the text to autoscroll to the end, making the
* mouse click set the insertion point in the wrong place.
*/
private function mouseDownCaptureHandler(event:MouseEvent):void
{
// trace("FocusManager mouseDownCaptureHandler in = " + this._form.systemManager.loaderInfo.url);
// trace("FocusManager mouseDownCaptureHandler target " + event.target);
showFocusIndicator = false;
}
/**
* @private
* This gets called when the focus changes due to a mouse click.
*
* Note: If the focus is changing to a TextField, we don't call
* setFocus() on it because the player handles it;
* calling setFocus() on a TextField which has scrollable text
* causes the text to autoscroll to the end, making the
* mouse click set the insertion point in the wrong place.
*/
private function mouseDownHandler(event:MouseEvent):void
{
// trace("FocusManager mouseDownHandler in = " + this._form.systemManager.loaderInfo.url);
// trace("FocusManager mouseDownHandler target " + event.target);
// if the target is in a bridged application, let it handle the click.
var sm:ISystemManager = form.systemManager;
var o:DisplayObject = getTopLevelFocusTarget(
InteractiveObject(event.target));
if (!o)
return;
// trace("FocusManager mouseDownHandler on " + o);
// Make sure the containing component gets notified.
// As the note above says, we don't set focus to a TextField ever
// because the player already did and took care of where
// the insertion point is, and we also don't call setfocus
// on a component that last the last focused object unless
// the last action was just to activate the player and didn't
// involve tabbing or clicking on a component
if ((o != _lastFocus || lastAction == "ACTIVATE") && !(o is TextField))
setFocus(IFocusManagerComponent(o));
else if (_lastFocus)
{
// trace("FM: skipped setting focus to " + _lastFocus);
}
if (hasEventListener("mouseDownFM"))
dispatchEvent(new FocusEvent("mouseDownFM", false, false, InteractiveObject(o)));
lastAction = "MOUSEDOWN";
}
/*
private function getBrowserFocusComponent(shiftKey:Boolean):InteractiveObject
{
var focusComponent:InteractiveObject = form.systemManager.stage.focus;
// if the focus is null it means focus is in an application we
// don't have access to. Use either the last object or the first
// object in this focus manager's list.
if (!focusComponent)
{
var index:int = shiftKey ? 0 : focusableCandidates.length - 1;
focusComponent = focusableCandidates[index];
}
return focusComponent;
}
*/
}
COMPILE::JS
public class FocusManager extends EventDispatcher implements IFocusManager
{
public function FocusManager(container:IFocusManagerContainer, popup:Boolean = false)
{
super();
form = container;
form.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownCaptureHandler, true);
}
private var form:IFocusManagerContainer;
private function mouseDownCaptureHandler(event:MouseEvent):void
{
var target:Object = event.target;
if (target is UIComponent)
target["element"].focus();
}
public function getNextFocusManagerComponent(
backward:Boolean = false):IFocusManagerComponent
{
return null;
}
private var _getFocus:IFocusManagerComponent;
public function getFocus():IFocusManagerComponent
{
return _getFocus;
//var stage:Stage = Sprite(form)./*systemManager.*/stage;
/* if (!stage)
return null;
var o:InteractiveObject = stage.focus;
// If a Stage* object (such as StageText or StageWebView) has focus,
// stage.focus will be set to null. Much of the focus framework is not
// set up to handle this. So, if stage.focus is null, we return the last
// IFocusManagerComponent that had focus. In ADL, focus works slightly
// different than it does on device when using StageText. In ADL, when
// the focus is a StageText component, a TextField whose parent is the
// stage is assigned focus.
if ((!o && _lastFocus) || (o is TextField && o.parent == stage))
return _lastFocus;
return findFocusManagerComponent(o); */
}
public function setFocus(o:IFocusManagerComponent):void
{
// trace("FM " + this + " setting focus to " + o);
o.setFocus();
if (hasEventListener("setFocus"))
dispatchEvent(new Event("setFocus"));
// trace("FM set focus");
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function hideFocus():void // not implemented
{
// trace("FOcusManger " + this + " Hide Focus");
/*
if (showFocusIndicator)
{
showFocusIndicator = false;
if (_lastFocus)
_lastFocus.drawFocus(false);
}
*/
// trace("END FOcusManger Hide Focus");
}
}
}
COMPILE::SWF
{
import flash.display.DisplayObject;
}
/**
* @private
*
* Plain old class to return multiple items of info about the potential
* change in focus.
*/
COMPILE::SWF
class FocusInfo
{
public var displayObject:DisplayObject; // object to get focus
public var wrapped:Boolean; // true if focus wrapped around
}
|
package com.playata.application.data.guild
{
public class GuildCompetitionStatus
{
public static const Unknown:int = 0;
public static const Started:int = 1;
public static const Finished:int = 2;
public function GuildCompetitionStatus()
{
super();
}
}
}
|
/**
* __ __ __
* ____/ /_ ____/ /______ _ ___ / /_
* / __ / / ___/ __/ ___/ / __ `/ __/
* / /_/ / (__ ) / / / / / /_/ / /
* \__,_/_/____/_/ /_/ /_/\__, /_/
* / /
* \/
* http://distriqt.com
*
* @brief
* @author Michael Archbold (https://github.com/marchbold)
* @created 22/9/20
* @copyright http://distriqt.com/copyright/license.txt
*/
package io.branch.nativeExtensions.branch.buo
{
public class ContentMetadata
{
////////////////////////////////////////////////////////
// CONSTANTS
//
private static const TAG:String = "ContentMetadata";
////////////////////////////////////////////////////////
// VARIABLES
//
private var _properties:Object;
////////////////////////////////////////////////////////
// FUNCTIONALITY
//
public function ContentMetadata()
{
_properties = {};
}
public function addCustomMetadata( key:String, value:String ):ContentMetadata
{
_properties[ key ] = value;
return this;
}
public function toObject():Object
{
return _properties;
}
}
}
|
/*
* The MIT License
*
* Copyright (c) 2007 The SixDegrees Project Team
* (Jason Bellone, Juan Rodriguez, Segolene de Basquiat, Daniel Lang).
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.un.cava.birdeye.ravis.graphLayout.visual {
import flash.display.Graphics;
import flash.geom.Point;
/**
* Interface for any Edge renderers,
* basically this is very simple as it just
* requires a draw() method.
* */
public interface IEdgeRenderer {
/**
* Access to the graphics object on which all
* drawing takes place. Previously this was passed
* to draw(), but since that would hardly
* change at all, it makes more sense
* to implement it as an attribute of the
* edge renderers.
* @param g The graphics object to be used with the edge renderer.
* */
function set graphics(g:Graphics):void;
/**
* @private
* */
function get graphics():Graphics;
/**
* Draws an edge.
* Colours and linestyle can be provided through the XML object associated
* with the (v)edge.
* flexible.
* @param vedge The edge to draw, it needs to provide all the information required, i.e. locations.
* */
function draw(vedge:IVisualEdge):void;
/**
* Returns the coordinates of the label for the given edge.
* Different edge renderers might want to specify a different
* place where to put the label.
* @param edge The Edge where the label coordinates should refer to.
* @returns The coordinates where the edge renderer wants to place the label
* */
function labelCoordinates(vedge:IVisualEdge):Point;
}
} |
package Beetle.NetPackage
{
/**
* Copyright © henryfan 2013
* Created by henryfan on 13-7-30.
* homepage:www.ikende.com
* email:henryfan@msn.com
*/
import flash.utils.ByteArray;
public interface IMessage
{
function Load(reader:ByteArray):void;
function Save(writer:ByteArray):void;
}
} |
package org.papervision3d.core.dyn
{
import org.papervision3d.core.math.NumberUV;
public class DynamicUVs
{
private static const GROW_SIZE:int = 300;
private static const INIT_SIZE:int = 100;
private static var UVCounter:int;
private static var UVPool:Array;
public function DynamicUVs()
{
super();
init();
}
private static function init() : void
{
var _loc2_:NumberUV = null;
UVPool = new Array(INIT_SIZE);
var _loc1_:int = INIT_SIZE;
while(--_loc1_ > -1)
{
_loc2_ = new NumberUV();
UVPool[_loc1_] = _loc2_;
}
UVCounter = INIT_SIZE;
}
public static function init_index() : void
{
UVCounter = INIT_SIZE;
}
public function getUV() : NumberUV
{
var _loc1_:int = 0;
var _loc2_:NumberUV = null;
var _loc3_:NumberUV = null;
if(UVCounter == 0)
{
_loc1_ = GROW_SIZE;
while(--_loc1_ > -1)
{
_loc2_ = new NumberUV();
UVPool.unshift(_loc2_);
}
UVCounter = GROW_SIZE;
return this.getUV();
}
return NumberUV(UVPool[--UVCounter]);
}
public function releaseAll() : void
{
this.returnAllVertices();
}
public function returnTriangle(param1:NumberUV) : void
{
var _loc2_:* = UVCounter++;
UVPool[_loc2_] = param1;
}
public function returnAllVertices() : void
{
UVCounter = UVPool.length;
}
}
}
|
package com.pfp.events
{
import flash.events.Event;
import flash.utils.ByteArray;
public class JPEGAsyncCompleteEvent extends Event
{
public static const JPEGASYNC_COMPLETE:String = "JPEGAsyncComplete";
public var ImageData:ByteArray;
public function JPEGAsyncCompleteEvent(data:ByteArray)
{
ImageData = data;
super(JPEGASYNC_COMPLETE);
}
}
} |
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
function whileBreak() {
var x:int = 10;
while (true) {
x++;
if (x > 50) {
x = 100;
break;
}
}
print(x);
}
whileBreak();
|
package visuals.ui.elements.stream
{
import com.playata.framework.display.Sprite;
import com.playata.framework.display.lib.flash.FlashDisplayObjectContainer;
import com.playata.framework.display.lib.flash.FlashSprite;
import flash.display.MovieClip;
public class SymbolPanelStreamElementBackgroundGeneric extends Sprite
{
private var _nativeObject:SymbolPanelStreamElementBackground = null;
public function SymbolPanelStreamElementBackgroundGeneric(param1:MovieClip = null)
{
if(param1)
{
_nativeObject = param1 as SymbolPanelStreamElementBackground;
}
else
{
_nativeObject = new SymbolPanelStreamElementBackground();
}
super(null,FlashSprite.fromNative(_nativeObject));
var _loc2_:FlashDisplayObjectContainer = _sprite as FlashDisplayObjectContainer;
}
public function setNativeInstance(param1:SymbolPanelStreamElementBackground) : void
{
FlashSprite.setNativeInstance(_sprite,param1);
_nativeObject = param1;
syncInstances();
}
public function syncInstances() : void
{
}
}
}
|
/*
* Temple Library for ActionScript 3.0
* Copyright © MediaMonks B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by MediaMonks B.V.
* 4. Neither the name of MediaMonks B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY MEDIAMONKS B.V. ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MEDIAMONKS B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Note: This license does not apply to 3rd party classes inside the Temple
* repository with their own license!
*/
package temple.facebook.api
{
import temple.facebook.data.vo.FacebookCommentFields;
import temple.facebook.service.IFacebookCall;
/**
* API for handling comments on Facebook.
*
* @see ../../../../readme.html Read me
*
* @see temple.facebook.api.IFacebookAPI#comments
* @see temple.facebook.api.FacebookAPI#comments
* @see temple.facebook.data.vo.IFacebookCommentData
* @see http://developers.facebook.com/docs/reference/api/Comment/
*
* @author Thijs Broerse
*/
public interface IFacebookCommentAPI
{
/**
* Get a single comment.
*
* If successful, the result contains an <code>IFacebookCommentData</code> object.
*
* @param commentId the id of the comment.
* @param callback a callback method which must be called when the data is ready. This callback must accept one (and only one) argument of type IFacebookResult. If the call was successful the success Boolean of the result is true and the photos are in the data property of the result object.
* @param fields a FacebookCommentFields object with all the requested fields set to true.
* @param params option params to send with the request.
* @param forceReload when caching is enabled you can force the service to reload the data and not get the cached data when setting this value to true.
*
* @see temple.facebook.data.vo.IFacebookCommentData
*/
function getComment(commentId:String, callback:Function = null, fields:FacebookCommentFields = null, params:Object = null, forceReload:Boolean = false):IFacebookCall;
/**
* Get all the comments on an object.
*
* If successful, the result contains an <code>Array</code> with <code>IFacebookCommentData</code> objects.
*
* @param objectId the id of the object with the comments
* @param callback a callback method which must be called when the data is ready. This callback must accept one (and only one) argument of type IFacebookResult. If the call was successful the success Boolean of the result is true and the photos are in the data property of the result object.
* @param offset the position of the first item in the list
* @param limit the maximum amount of items.
* @param fields a FacebookCommentFields object with all the requested fields set to true.
* @param params option params to send with the request.
* @param forceReload when caching is enabled you can force the service to reload the data and not get the cached data when setting this value to true.
*
* @see temple.facebook.data.vo.IFacebookCommentData
*/
function getComments(objectId:String, callback:Function = null, offset:Number = NaN, limit:Number = NaN, fields:FacebookCommentFields = null, params:Object = null, forceReload:Boolean = false):IFacebookCall;
/**
* Comment on the given object (if it has a /comments connection)
*/
function create(objectId:String, message:String, callback:Function = null):IFacebookCall;
}
}
|
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
package spine.attachments {
import spine.Bone;
import spine.Skeleton;
import spine.Slot;
public class VertexAttachment extends Attachment {
private static var nextID : int = 0;
public var bones : Vector.<int>;
public var vertices : Vector.<Number>;
public var worldVerticesLength : int;
public var id : int = nextID++;
public var deformAttachment : VertexAttachment;
public function VertexAttachment(name : String) {
super(name);
deformAttachment = this;
}
/** Transforms the attachment's local {@link #vertices} to world coordinates. If the slot's {@link Slot#deform} is
* not empty, it is used to deform the vertices.
*
* See [World transforms](http://esotericsoftware.com/spine-runtime-skeletons#World-transforms) in the Spine
* Runtimes Guide.
* @param start The index of the first {@link #vertices} value to transform. Each vertex has 2 values, x and y.
* @param count The number of world vertex values to output. Must be <= {@link #worldVerticesLength} - `start`.
* @param worldVertices The output world vertices. Must have a length >= `offset` + `count` *
* `stride` / 2.
* @param offset The `worldVertices` index to begin writing values.
* @param stride The number of `worldVertices` entries between the value pairs written. */
public function computeWorldVertices(slot : Slot, start : int, count : int, worldVertices : Vector.<Number>, offset : int, stride : int) : void {
count = offset + (count >> 1) * stride;
var skeleton : Skeleton = slot.skeleton;
var deformArray : Vector.<Number> = slot.deform;
var vertices : Vector.<Number> = this.vertices;
var bones : Vector.<int> = this.bones;
var deform : Vector.<Number>;
var v : int, w : int, n : int, i : int, skip : int, b : int, f : int;
var vx : Number, vy : Number;
var wx : Number, wy : Number;
var bone : Bone;
if (bones == null) {
if (deformArray.length > 0) vertices = deformArray;
bone = slot.bone;
var x : Number = bone.worldX;
var y : Number = bone.worldY;
var a : Number = bone.a, bb : Number = bone.b, c : Number = bone.c, d : Number = bone.d;
for (v = start, w = offset; w < count; v += 2, w += stride) {
vx = vertices[v]
,
vy = vertices[v + 1];
worldVertices[w] = vx * a + vy * bb + x;
worldVertices[w + 1] = vx * c + vy * d + y;
}
return;
}
v = 0
,
skip = 0;
for (i = 0; i < start; i += 2) {
n = bones[v];
v += n + 1;
skip += n;
}
var skeletonBones : Vector.<Bone> = skeleton.bones;
if (deformArray.length == 0) {
for (w = offset, b = skip * 3; w < count; w += stride) {
wx = 0
,
wy = 0;
n = bones[v++];
n += v;
for (; v < n; v++, b += 3) {
bone = skeletonBones[bones[v]];
vx = vertices[b];
vy = vertices[b + 1];
var weight : Number = vertices[b + 2];
wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
}
worldVertices[w] = wx;
worldVertices[w + 1] = wy;
}
} else {
deform = deformArray;
for (w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) {
wx = 0;
wy = 0;
n = bones[v++];
n += v;
for (; v < n; v++, b += 3, f += 2) {
bone = skeletonBones[bones[v]];
vx = vertices[b] + deform[f];
vy = vertices[b + 1] + deform[f + 1];
weight = vertices[b + 2];
wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
}
worldVertices[w] = wx;
worldVertices[w + 1] = wy;
}
}
}
public function copyTo(attachment : VertexAttachment) : void {
if (bones != null) {
attachment.bones = bones.concat();
} else
attachment.bones = null;
if (this.vertices != null) {
attachment.vertices = vertices.concat();
} else
attachment.vertices = null;
attachment.worldVerticesLength = worldVerticesLength;
attachment.deformAttachment = deformAttachment;
}
}
}
|
package com.google.i18n.phonenumbers
{
public class PhoneNumberDesc
{
protected var _hasNationalNumberPattern:Boolean = false;
protected var _nationalNumberPattern:String = "";
protected var _hasPossibleNumberPattern:Boolean = false;
protected var _possibleNumberPattern:String = "";
protected var _hasExampleNumber:Boolean = false;
protected var _exampleNumber:String = "";
public function PhoneNumberDesc(data:Array = null)
{
if(data != null)
setData(data);
}
public function setData(data:Array):void
{
for(var key:String in data) {
if(data.hasOwnProperty(key) && data[key]) {
switch(key) {
case '2': //national_number_pattern
setNationalNumberPattern(data[key]);
break;
case '3': //possible_number_pattern
setPossibleNumberPattern(data[key]);
break;
case '6': //example_number
setExampleNumber(data[key]);
break;
case '7': //national_number_matcher_data
break;
case '8': //possible_number_matcher_data
break;
}
}
}
}
public function hasNationalNumberPattern():Boolean
{
return _hasNationalNumberPattern;
}
public function getNationalNumberPattern():String
{
return _nationalNumberPattern;
}
public function setNationalNumberPattern(value:String):void
{
_hasNationalNumberPattern = true;
_nationalNumberPattern = value;
}
public function hasPossibleNumberPattern():Boolean
{
return _hasPossibleNumberPattern;
}
public function getPossibleNumberPattern():String
{
return _possibleNumberPattern;
}
public function setPossibleNumberPattern(value:String):void
{
_hasPossibleNumberPattern = true;
_possibleNumberPattern = value;
}
public function hasExampleNumber():Boolean
{
return _hasExampleNumber;
}
public function getExampleNumber():String
{
return _exampleNumber;
}
public function setExampleNumber(value:String):void
{
_hasExampleNumber = true;
_exampleNumber = value;
}
}
}
|
package com.ankamagames.dofus.network.messages.game.inventory.exchanges
{
import com.ankamagames.jerakine.network.CustomDataWrapper;
import com.ankamagames.jerakine.network.ICustomDataInput;
import com.ankamagames.jerakine.network.ICustomDataOutput;
import com.ankamagames.jerakine.network.INetworkMessage;
import com.ankamagames.jerakine.network.NetworkMessage;
import com.ankamagames.jerakine.network.utils.FuncTree;
import flash.utils.ByteArray;
public class ExchangeRequestedMessage extends NetworkMessage implements INetworkMessage
{
public static const protocolId:uint = 5525;
private var _isInitialized:Boolean = false;
public var exchangeType:int = 0;
public function ExchangeRequestedMessage()
{
super();
}
override public function get isInitialized() : Boolean
{
return this._isInitialized;
}
override public function getMessageId() : uint
{
return 5525;
}
public function initExchangeRequestedMessage(exchangeType:int = 0) : ExchangeRequestedMessage
{
this.exchangeType = exchangeType;
this._isInitialized = true;
return this;
}
override public function reset() : void
{
this.exchangeType = 0;
this._isInitialized = false;
}
override public function pack(output:ICustomDataOutput) : void
{
var data:ByteArray = new ByteArray();
this.serialize(new CustomDataWrapper(data));
writePacket(output,this.getMessageId(),data);
}
override public function unpack(input:ICustomDataInput, length:uint) : void
{
this.deserialize(input);
}
override public function unpackAsync(input:ICustomDataInput, length:uint) : FuncTree
{
var tree:FuncTree = new FuncTree();
tree.setRoot(input);
this.deserializeAsync(tree);
return tree;
}
public function serialize(output:ICustomDataOutput) : void
{
this.serializeAs_ExchangeRequestedMessage(output);
}
public function serializeAs_ExchangeRequestedMessage(output:ICustomDataOutput) : void
{
output.writeByte(this.exchangeType);
}
public function deserialize(input:ICustomDataInput) : void
{
this.deserializeAs_ExchangeRequestedMessage(input);
}
public function deserializeAs_ExchangeRequestedMessage(input:ICustomDataInput) : void
{
this._exchangeTypeFunc(input);
}
public function deserializeAsync(tree:FuncTree) : void
{
this.deserializeAsyncAs_ExchangeRequestedMessage(tree);
}
public function deserializeAsyncAs_ExchangeRequestedMessage(tree:FuncTree) : void
{
tree.addChild(this._exchangeTypeFunc);
}
private function _exchangeTypeFunc(input:ICustomDataInput) : void
{
this.exchangeType = input.readByte();
}
}
}
|
package com.videojs.structs{
public class ExternalEventName{
public static const ON_SRC_CHANGE:String = "onsrcchange";
public static const ON_START:String = "playing";
public static const ON_PAUSE:String = "pause";
public static const ON_RESUME:String = "play";
public static const ON_PLAYBACK_COMPLETE:String = "ended";
public static const ON_DURATION_CHANGE:String = "durationchange";
public static const ON_VOLUME_CHANGE:String = "volumechange";
public static const ON_STAGE_CLICK:String = "stageclick";
public static const ON_VAST_CREATIVE_VIEW:String = "vastcreativeview";
public static const ON_VAST_START:String = "vaststart";
public static const ON_VAST_FIRST_QUARTILE:String = "vastfirstquartile";
public static const ON_VAST_MIDPOINT:String = "vastmidpoint";
public static const ON_VAST_THIRD_QUARTILE:String = "vastthirdquartile";
public static const ON_VAST_COMPLETE:String = "vastcomplete";
public static const ON_VAST_IMPRESSION:String = "vastimpression";
public static const ON_VAST_CLICK_TRACKING:String = "vastclicktracking";
public static const ON_VAST_ACCEPT_INVITATION:String = "vastacceptinvitation";
public static const ON_VAST_COLLAPSE:String = "vastcollapse";
public static const ON_VAST_RESUME:String = "vastresume";
public static const ON_VAST_PAUSE:String = "vastpause";
public static const ON_VAST_REWIND:String = "vastrewind";
public static const ON_VAST_SKIP:String = "vastskip";
public static const ON_VAST_CLOSE_LINEAR:String = "vastcloselinear";
public static const ON_VAST_CLOSE:String = "vastclose";
public static const ON_VAST_MUTE:String = "vastmute";
public static const ON_VAST_UNMUTE:String = "vastunmute";
public static const ON_VAST_HANDSHAKE_VERSION:String = "vasthanshakeversion";
public static const ON_VAST_LOADED:String = "vastloaded";
public static const ON_WAITING:String = "waiting";
}
} |
package alternativa.engine3d.utils
{
import alternativa.engine3d.core.Object3D;
import alternativa.engine3d.core.Transform3D;
import alternativa.engine3d.alternativa3d;
use namespace alternativa3d;
/**
* ...
* @author Glenn Ko
*/
public class Object3DTransformUtil
{
public function Object3DTransformUtil()
{
}
public static function calculateLocalToGlobal(obj:Object3D):Transform3D {
if (obj.transformChanged) obj.composeTransforms();
var trm:Transform3D = obj.localToGlobalTransform;
trm.copy(obj.transform);
var root:Object3D = obj;
while (root.parent != null) {
root = root.parent;
if (root.transformChanged) root.composeTransforms();
trm.append(root.transform);
}
return trm;
}
public static function calculateGlobalToLocal(obj:Object3D):Transform3D {
if (obj.transformChanged) obj.composeTransforms();
var trm:Transform3D = obj.globalToLocalTransform;
trm.copy(obj.inverseTransform);
var root:Object3D = obj;
while (root.parent != null) {
root = root.parent;
if (root.transformChanged) root.composeTransforms();
trm.prepend(root.inverseTransform);
}
return trm;
}
public static function calculateLocalToGlobal2(obj:Object3D, trm:Transform3D=null):Transform3D {
if (obj.transformChanged) obj.composeTransforms();
trm = trm || new Transform3D();
trm.copy(obj.transform);
var root:Object3D = obj;
while (root.parent != null) {
root = root.parent;
if (root.transformChanged) root.composeTransforms();
trm.append(root.transform);
}
return trm;
}
public static function calculateGlobalToLocal2(obj:Object3D, trm:Transform3D=null):Transform3D {
if (obj.transformChanged) obj.composeTransforms();
trm = trm || new Transform3D();
trm.copy(obj.inverseTransform);
var root:Object3D = obj;
while (root.parent != null) {
root = root.parent;
if (root.transformChanged) root.composeTransforms();
trm.prepend(root.inverseTransform);
}
return trm;
}
}
} |
/*
* Copyright (c) 2009 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.robotlegs.core
{
import flash.system.ApplicationDomain;
/**
* The Robotlegs Injector contract
*/
public interface IInjector
{
/**
* When asked for an instance of the class <code>whenAskedFor</code>, always
* inject the supplied instance <code>useValue</code>.
*
* <p>Eager Loading. Registers an existing instance with the injector
* and <strong>treats it like a Singleton</strong>.</p>
*
* @param whenAskedFor A class or interface
* @param useValue An instance
* @param named An optional name (id)
*
* @return * A reference to the rule for this injection. To be used with <code>mapRule</code>
*/
function mapValue(whenAskedFor:Class, useValue:Object, named:String = ""):*;
/**
* When asked for an instance of the class <code>whenAskedFor</code>
* inject a new instance of <code>instantiateClass</code>.
*
* <p>Lazy Loading. This will create a <strong>new instance on demand for each injection.</strong></p>
*
* @param whenAskedFor A class or interface
* @param instantiateClass A class to instantiate
* @param named An optional name (id)
*
* @return * A reference to the rule for this injection. To be used with <code>mapRule</code>
*/
function mapClass(whenAskedFor:Class, instantiateClass:Class, named:String = ""):*;
/**
* When asked for an instance of the class <code>whenAskedFor</code>, always
* inject the same instance of <code>whenAskedFor</code>.
*
* <p>Lazy Loading. This will create an instance on the first injection, but
* <strong>will always supply that specific instance</strong> for subsequent injections.</p>
*
* @param whenAskedFor A class or interface
* @param named An optional name (id)
*
* @return * A reference to the rule for this injection. To be used with <code>mapRule</code>
*/
function mapSingleton(whenAskedFor:Class, named:String = ""):*;
/**
* When asked for an instance of the class <code>whenAskedFor</code>
* inject an instance of <code>useSingletonOf</code>.
*
* <p>Lazy Loading. This will create an instance on the first injection, but
* <strong> will always supply that specific instance</strong> for subsequent injections.</p>
*
* @param whenAskedFor A class or interface
* @param useSingletonOf A class to instantiate
* @param named An optional name (id)
*
* @return * A reference to the rule for this injection. To be used with <code>mapRule</code>
*/
function mapSingletonOf(whenAskedFor:Class, useSingletonOf:Class, named:String = ""):*;
/**
* When asked for an instance of the class <code>whenAskedFor</code>
* use rule <code>useRule</code> to determine the correct injection.
*
* <p>This will use whatever injection is set by the given injection rule as created using
* one of the other mapping methods.</p>
*
* @param whenAskedFor A class or interface
* @param useRule The rule to use for the injection
* @param named An optional name (id)
*
* @return * A reference to the rule for this injection. To be used with <code>mapRule</code>
*/
function mapRule(whenAskedFor:Class, useRule:*, named:String = ""):*;
/**
* Perform an injection into an object, satisfying all its dependencies
*
* <p>The <code>IInjector</code> should throw an <code>Error</code>
* if it can't satisfy all dependencies of the injectee.</p>
*
* @param target The object to inject into - the Injectee
*/
function injectInto(target:Object):void;
/**
* Create an object of the given class, supplying its dependencies as constructor parameters
* if the used DI solution has support for constructor injection
*
* <p>Adapters for DI solutions that don't support constructor injection should just create a new
* instance and perform setter and/ or method injection on that.</p>
*
* <p>NOTE: This method will always create a new instance. If you need to retrieve an instance
* consider using <code>getInstance</code></p>
*
* <p>The <code>IInjector</code> should throw an <code>Error</code>
* if it can't satisfy all dependencies of the injectee.</p>
*
* @param clazz The class to instantiate
* @return * The created instance
*/
function instantiate(clazz:Class):*;
/**
* Create or retrieve an instance of the given class
*
* @param clazz
* @param named An optional name (id)
* @return * An instance
*/
function getInstance(clazz:Class, named:String = ""):*;
/**
* Create an injector that inherits rules from its parent
*
* @return The injector
*/
function createChild(applicationDomain:ApplicationDomain = null):IInjector;
/**
* Remove a rule from the injector
*
* @param clazz A class or interface
* @param named An optional name (id)
*/
function unmap(clazz:Class, named:String = ""):void;
/**
* Does a rule exist to satsify such a request?
*
* @param clazz A class or interface
* @param named An optional name (id)
* @return Whether such a mapping exists
*/
function hasMapping(clazz:Class, named:String = ""):Boolean;
}
}
|
/*
* _________ __ __
* _/ / / /____ / /________ ____ ____ ___
* _/ / / __/ -_) __/ __/ _ `/ _ `/ _ \/ _ \
* _/________/ \__/\__/\__/_/ \_,_/\_, /\___/_//_/
* /___/
*
* Tetragon : Game Engine for multi-platform ActionScript projects.
* http://www.tetragonengine.com/ - Copyright (C) 2012 Sascha Balkau
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package tetragon.util.crypto
{
/**
* A fast SHA-1 hash generator.
*/
public final class SHA1
{
//-----------------------------------------------------------------------------------------
// Constants
//-----------------------------------------------------------------------------------------
/** @private */
private static const CHARMAP:String = "0123456789ABCDEF";
//-----------------------------------------------------------------------------------------
// Public Methods
//-----------------------------------------------------------------------------------------
/**
* Generates a SHA-1 hash string from the specified string.
*
* @param string String to generate hash from.
* @return A hexadecimal SHA-1 hash string.
*/
public static function hash(string:String):String
{
var a:Array = [];
var l:uint = string.length * 8;
var i:uint = 0;
/* Convert string to binary format. */
var mask:int = (1 << 8) - 1;
while (i < l)
{
a[i >> 5] |= (string.charCodeAt(i / 8) & mask) << (32 - 8 - i % 32);
i += 8;
}
var b1:int = 1732584193;
var b2:int = -271733879;
var b3:int = -1732584194;
var b4:int = 271733878;
var b5:int = -1009589776;
var op:Array = [];
a[l >> 5] |= 0x80 << (24 - l % 32);
a[((l + 64 >> 9) << 4) + 15] = l;
l = a.length;
i = 0;
while (i < l)
{
var s1:int = b1;
var s2:int = b2;
var s3:int = b3;
var s4:int = b4;
var s5:int = b5;
for (var j:uint = 0; j < 80; ++j)
{
if (j < 16)
{
op[j] = a[i + j];
}
else
{
var n:int = op[j - 3] ^ op[j - 8] ^ op[j - 14] ^ op[j - 16];
op[j] = (n << 1) | (n >>> (32 - 1));
}
b5 = b4;
b4 = b3;
b3 = (b2 << 30) | (b2 >>> (32 - 30));
b2 = b1;
b1 = safeAdd(safeAdd((b1 << 5) | (b1 >>> (32 - 5)),
fmod(j, b2, b3, b4)),
safeAdd(safeAdd(b5, op[j]), (j < 20) ? 0x5A827999 : (j < 40) ? 0x6ED9EBA1 : (j < 60) ? 0x8F1BBCDC : 0xCA62C1D6));
}
b1 = safeAdd(b1, s1);
b2 = safeAdd(b2, s2);
b3 = safeAdd(b3, s3);
b4 = safeAdd(b4, s4);
b5 = safeAdd(b5, s5);
i += 16;
}
/* Convert binary to hex format. */
string = "";
a = [b1, b2, b3, b4, b5];
i = 0;
while (i++ < 20)
{
string += CHARMAP.charAt((a[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF)
+ CHARMAP.charAt((a[i >> 2] >> ((3 - i % 4) * 8 )) & 0xF);
}
return string;
}
//-----------------------------------------------------------------------------------------
// Private Methods
//-----------------------------------------------------------------------------------------
/**
* Perform the appropriate triplet combination function for the current iteration.
* @private
*/
private static function fmod(t:int, b:int, c:int, d:int):int
{
if (t < 20) return (b & c) | ((~b) & d);
if (t < 40) return b ^ c ^ d;
if (t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/**
* @private
*/
private static function safeAdd(x:int, y:int):int
{
var lsw:uint = (x & 0xFFFF) + (y & 0xFFFF);
return ((x >> 16) + (y >> 16) + (lsw >> 16) << 16) | (lsw & 0xFFFF);
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
include "unicodeUtil.as";
include "unicodeNegativeUtil.as";
// var SECTION = "CJK Unified Ideographs";
// var VERSION = "ECMA_3";
// var TITLE = "Test String functions (search, match, split, replace) on all unicode characters";
var array = new Array();
var item = 0;
getTestCases();
var testcases = array;
function getTestCases():void {
// CJK Unified Ideographs
testUnicodeRange(0x8000, 0x8FFF);
negativeTestUnicodeRange(0x8000, 0x8FFF);
}
|
package HUDMenu_fla
{
import flash.display.MovieClip;
import flash.events.Event;
public dynamic class none2command_73 extends MovieClip
{
public var Down:MovieClip;
public var Left:MovieClip;
public var Right:MovieClip;
public var Up:MovieClip;
public function none2command_73()
{
super();
addFrameScript(0,this.frame1,5,this.frame6);
}
function frame1() : *
{
stop();
}
function frame6() : *
{
dispatchEvent(new Event("animationComplete"));
}
}
}
|
package myriadLands.components
{
import myriadLands.actions.GateCombatAction;
import myriadLands.combat.CombatManager;
import myriadLands.entities.CombatGround;
import myriadLands.entities.Entity;
import myriadLands.entities.EntityInternal;
import myriadLands.entities.EntityState;
import myriadLands.entities.Squad;
import myriadLands.events.CombatEvent;
import myriadLands.events.EntityEvent;
use namespace EntityInternal;
public class CombatComponent {
protected var _entity:Entity;
protected var _cbtMgr:CombatManager;
public function CombatComponent(entity:Entity, cbtMgr:CombatManager) {
_entity = entity;
if (_entity is Squad)
_entity.parentEntity = null;
_entity.state = EntityState.IN_COMBAT;
_cbtMgr = cbtMgr;
entity.setActions([GateCombatAction.ID]);
_cbtMgr.addEventListener(CombatEvent.ON_ROUND_ENDED, onRoundEnded, false, 0, true);
_entity.addEventListener(EntityEvent.ENTITY_DIED, onEntityDeath, false, 0, true);
}
public function destroy():void {
//Retutn to original state, or vault if is dead
if (_entity.lif <= 0) {
if (_entity is Squad) {
(_entity as Squad).detachUnits();
_entity.parentEntity = null;
}
//_entity.state = EntityState.IN_VAULT;
_entity.faction.addToVault(_entity);
} else
_entity.state = EntityState.IN_WORLD_MAP;
//Destroy
_cbtMgr.removeEventListener(CombatEvent.ON_ROUND_ENDED, onRoundEnded);
_entity.removeEventListener(EntityEvent.ENTITY_DIED, onEntityDeath);
_entity = null;
_cbtMgr = null;
}
//EVENTS
protected function onRoundEnded(e:CombatEvent):void {
//Means tha is there not place on terrain, or dead
if (_entity.parentEntity == null) return;
_entity.setAttibute("act", _entity.act + _entity.actrg);
(_entity.parentEntity as CombatGround).combatMapTile.addAnimatedText("+ " + String(_entity.actrg), "IncreaseActInfo");
}
protected function onEntityDeath(e:EntityEvent):void {
//modify entity
//var combatGround:CombatGround = e.entity.parentEntity as CombatGround;
(e.entity.parentEntity as CombatGround).entityOn = null;
//inform combat manager
_cbtMgr.entityDied(e.entity);
}
}
} |
package playerio{
/**
* Error object PlayerIO QuickConnect registration errors
* This class is auto generated
*/
public class PlayerIORegistrationError extends playerio.PlayerIOError{
/**
* The error for the username field, if any
*/
public var usernameError:String;
/**
* The error for the password field, if any
*/
public var passwordError:String;
/**
* The error for the email field, if any
*/
public var emailError:String;
/**
* The error for the captcha field, if any
*/
public var captchaError:String;
/**
* Creates a PlayerIORegistrationError
*/
function PlayerIORegistrationError(message:String, id:int, usernameError:String, passwordError:String, emailError:String, captchaError:String){
super(message, id);
this.usernameError = usernameError;
this.passwordError = passwordError;
this.emailError = emailError;
this.captchaError = captchaError;
}
}
}
|
package cmodule.lua_wrapper
{
public const _luaH_getn:int = regFunc(FSM_luaH_getn.start);
}
|
/*
* VERSION:3.0
* DATE:2014-10-15
* ACTIONSCRIPT VERSION: 3.0
* UPDATES AND DOCUMENTATION AT: http://www.wdmir.net
* MAIL:mir3@163.com
*/
package com.adobe.ac.mxeffects.effectClasses
{
import com.adobe.ac.mxeffects.Distortion;
import com.adobe.ac.mxeffects.Push;
public class PushInstance extends DistortBaseInstance
{
private var distort : Distortion;
private var distortBack : Distortion;
public function PushInstance( target:Object )
{
super( target );
}
override public function play() : void
{
if( direction == null ) direction = Push.defaultDirection;
if( buildMode == null ) buildMode = Push.defaultBuildMode;
super.play();
startAnimation();
}
private function startAnimation() : void
{
initializeNextTarget();
nextAnimation();
}
private function nextAnimation() : void
{
distortBack = new Distortion( currentTarget );
applyCoordSpaceChange( distortBack, getContainerChild( siblings[ currentSibling ] ) );
applyDistortionMode( distortBack );
distortBack.renderSides( 100, 100, 100, 100 );
initializeNextTarget();
startPush();
initializePreviousTarget();
}
private function startPush() : void
{
distort = new Distortion( currentTarget );
applyCoordSpaceChange( distort, getContainerChild( siblings[ currentSibling - 1 ] ) );
applyDistortionMode( distort );
applyBlur( distort.container );
var updateMethod : Function = updateAnimation;
animate( 0, 100, siblingDuration, updateMethod, endAnimation );
}
private function updateAnimation( value : Object ) : void
{
if( liveUpdate ) distortBack.renderSides( 100, 100, 100, 100 );
distort.push( Number( value ), direction, distortion );
}
private function updateWithLightingToWhite( value : Object ) : void
{
var updateValue : Number = Number( value );
updateAnimation( updateValue );
}
private function updateWithLightingFromBlack( value : Object ) : void
{
var updateValue : Number = Number( value );
updateAnimation( updateValue );
}
private function endAnimation( value : Object ) : void
{
distortBack.destroy( false );
distort.destroy();
currentSibling++;
var hasSiblings : Boolean = ( siblings.length > currentSibling + 1 );
if( hasSiblings )
{
currentSibling--;
startAnimation();
}
else
{
super.onTweenEnd( value );
}
}
}
}
|
/**
* Copyright (c) 2010 Johnson Center for Simulation at Pine Technical College
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package quickb2.physics.ai.controllers
{
import quickb2.math.general.*;
import quickb2.math.geo.*;
import flash.display.*;
import TopDown.objects.*;
/**
* ...
* @author Doug Koellmer
*/
public class qb2MouseCarController extends qb2MouseController
{
public var maxThrottleDistance:Number = 100;
public var brakeDistance:Number = 33;
public var brakeWithThrottle:Boolean = false;
public var variableThrottle:Boolean = true;
public function qb2MouseCarController(mouseSource:Stage)
{
super(mouseSource);
}
protected override function activated():void
{
if ( host is qb2CarBody )
{
brainPort.open = true;
super.activated();
}
else
{
brainPort.open = false;
}
}
protected override function update():void
{
super.update();
brainPort.clear();
var mousePosition:qb2GeoPoint = positionalSpace ? new qb2GeoPoint(positionalSpace.mouseX, positionalSpace.mouseY) : mouse.position;
var direction:qb2GeoVector = mousePosition.minus(host.position);
var pullLength:Number = variableThrottle ? direction.length : maxThrottleDistance;
direction.normalize();
lastDirection.copy(direction);
if ( pullLength <= brakeDistance && (brakeWithThrottle || !brakeWithThrottle && !mouseIsDown) )
{
brainPort.NUMBER_PORT_3 = qb2U_Math.constrain(1 - pullLength/brakeDistance, 0, 1);
}
if ( direction.calcLengthSquared() == 0 ) return;
var carNormal:qb2GeoVector = host.getNormal();
var maxTurnAngle:Number = (host as qb2CarBody).maxTurnAngle;
var turnAngle:Number = carNormal.signedAngleTo(direction);
var absTurnAngle:Number = Math.abs(turnAngle);
var absThrottle:Number = qb2U_Math.constrain(pullLength / maxThrottleDistance, 0, 1);
var upDown:Number = Math.abs(turnAngle) > qb2S_Math.PI - maxTurnAngle ? -absThrottle : absThrottle;
brainPort.NUMBER_PORT_1 = mouseIsDown ? upDown : 0;
if ( upDown > 0 )
{
brainPort.NUMBER_PORT_2 = qb2U_Math.constrain(turnAngle, -maxTurnAngle, maxTurnAngle);
}
else
{
brainPort.NUMBER_PORT_2 = qb2U_Math.constrain( (qb2U_Math.sign(turnAngle)*(qb2S_Math.PI-absTurnAngle)), -maxTurnAngle, maxTurnAngle);
}
}
}
} |
// Decompiled by AS3 Sorcerer 6.08
// www.as3sorcerer.com
//kabam.rotmg.assets.EmbeddedAssets_oryxHordeChars8x8Embed_
package kabam.rotmg.assets
{
import mx.core.BitmapAsset;
[Embed(source="EmbeddedAssets_oryxHordeChars8x8.png")]
public class EmbeddedAssets_oryxHordeChars8x8Embed_ extends BitmapAsset
{
}
}//package kabam.rotmg.assets
|
/**
* (c) VARIANTE <http://variante.io>
*
* This software is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
package io.variante.transitions.easing
{
import com.greensock.easing.Cubic;
import com.greensock.easing.Ease;
/**
* Wrapper class for Cubic easing.
*/
public class Cubic
{
/**
* @see com.greensock.easing.Cubic#easeOut
*/
public static var easeOut:Ease = com.greensock.easing.Cubic.easeOut;
/**
* @see com.greensock.easing.Cubic#easeIn
*/
public static var easeIn:Ease = com.greensock.easing.Cubic.easeIn;
/**
* @see com.greensock.easing.Cubic#easeInOut
*/
public static var easeInOut:Ease = com.greensock.easing.Cubic.easeInOut;
}
}
|
package pl.asria.tools.display
{
/**
* ...
* @author Piotr Paczkowski
*/
public interface IMultiState
{
function set baseState(value:String):void;
function set subState(value:String):void;
function gotoCurrentState():void;
function get baseState():String;
function get subState():String;
}
} |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import com.adobe.test.Assert;
// var SECTION = "7.3-11";
// var VERSION = "ECMA_1";
// var TITLE = "Comments";
var testcases = getTestCases();
function getTestCases() {
var array = new Array();
var item = 0;
array[item++] = Assert.expectEq(
"code following multiline comment",
"pass",
"pass");
////array[0].actual="fail";
return ( array );
}
|
/**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* 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.
*/
package com.deleidos.rtws.alertcontroller.services.repository.rest
{
public class ServiceConstants
{
private static const DEFAULT_SYSTEM_NAME:String = "athena";
private static const DEFAULT_USERID:String = "athena";
private static const DEFAULT_PASSWORD:String = "athena";
public static function getUserId(tenantName:String):String{
return tenantName == "FILL_IN_SYSTEM_NAME" ? DEFAULT_USERID : tenantName;
}
public static function getPassword(tenantName:String):String{
return tenantName == "FILL_IN_SYSTEM_NAME" ? DEFAULT_PASSWORD : tenantName;
}
public static function getTenantPath(tenantName:String):String{
return tenantName == "FILL_IN_SYSTEM_NAME" ? DEFAULT_SYSTEM_NAME : tenantName;
}
}
} |
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Igor Bukanov
* Ethan Hugg
* Milen Nankov
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
START("13.4.4.27 - XML parent()");
//TEST(1, true, XML.prototype.hasOwnProperty("parent"));
var x1 =
<alpha>
<bravo>one</bravo>
<charlie>
<bravo>two</bravo>
</charlie>
</alpha>;
var y1 = x1.bravo;
TEST(2, x1, y1.parent());
TEST(3, undefined, x1.parent());
x1 = new XML("<XML></XML>");
var a = new XML("text node");
var b = new XML("<foo>bar</foo>");
AddTestCase ("MYXML = new('<XML></XML>'), MYXML.parent()", undefined, x1.parent());
AddTestCase ("MYXML = new('text node'), MYXML.parent()", undefined, a.parent());
AddTestCase ("MYXML = new('<foo>bar</foo>'), MYXML.parent()", undefined, b.parent());
x1.appendChild (a);
x1.appendChild (b);
// Text node is a special case
AddTestCase ("a - orphan node after x.appendChild, a.parent()", undefined, a.parent());
AddTestCase ("b - orphan node after x.appendChild, b.parent()", x1, b.parent());
AddTestCase ("x1.children()[0].parent()", x1, x1.children()[0].parent());
AddTestCase ("x1.children()[1].parent()", x1, x1.children()[0].parent());
AddTestCase ("x1.children()[0].parent() === x1", true, (x1.children()[0].parent() === x1));
AddTestCase ("x1.children()[1].parent() === x1", true, (x1.children()[0].parent() === x1));
var xDoc = "<company><employee id='1'><name1>John</name1> <city>California</city> </employee><employee id='2'><name1>Mary</name1> <city>Texas</city> </employee></company>";
AddTestCase( "x1 = new XML(xDoc), x1.employee[0].parent() == x1", true, (x1 = new XML(xDoc), x1.employee[0].parent() == x1));
AddTestCase( "x1 = new XML(xDoc), x1.employee.name1[0].parent() == x1.employee[0]", true, (x1 = new XML(xDoc), x1.employee.name1[0].parent() == x1.employee[0]));
AddTestCase( "x1 = new XML(xDoc), x1.employee[0].attribute('id').parent() === x1.employee[0]", true, (x1 = new XML(xDoc), x1.employee[0].attribute('id').parent() === x1.employee[0]));
AddTestCase( "x1 = new XML(xDoc), x1.employee[1].parent() == x1", true, (x1 = new XML(xDoc), x1.employee[1].parent() == x1));
AddTestCase( "x1 = new XML(xDoc), x1.employee.name1[1].parent() == x1.employee[0]", true, (x1 = new XML(xDoc), x1.employee.name1[1].parent() == x1.employee[1]));
AddTestCase( "x1 = new XML(xDoc), x1.employee[1].attribute('id').parent() === x1.employee[1]", true, (x1 = new XML(xDoc), x1.employee[1].attribute('id').parent() === x1.employee[1]));
XML.ignoreComments = false;
XML.ignoreProcessingInstructions = false;
xDoc = "<simple><!-- comment --><?x-stylesheet href=\"classic.xsl\" type=\"text/x\"?></simple>";
// Tests comments and PI nodes
AddTestCase( "x1 = new XML(xDoc), x1.children()[0].parent() == x1", true, (x1 = new XML(xDoc), x1.children()[0].parent() == x1));
AddTestCase( "x1 = new XML(xDoc), x1.children()[1].parent() == x1", true, (x1 = new XML(xDoc), x1.children()[1].parent() == x1));
AddTestCase( "x1 = new XML(xDoc), x1.children().parent() == x1", true, (x1 = new XML(xDoc), x1.children().parent() == x1));
END();
|
package SJ.Game.activity
{
import SJ.Common.Constants.ConstResource;
import SJ.Game.CJModulePopupBase;
import SJ.Game.data.CJDataManager;
import SJ.Game.event.CJEvent;
import SJ.Game.event.CJEventDispatcher;
import SJ.Game.layer.CJLayerManager;
import SJ.Game.layer.CJLoadingLayer;
import engine_starling.utils.AssetManagerUtil;
import engine_starling.utils.FeatherControlUtils.SFeatherControlUtils;
/**
+------------------------------------------------------------------------------
*活跃度模块
+------------------------------------------------------------------------------
* @author caihua
* @email caihua.bj@gmail.com
* @date 2013-9-5 下午12:45:10
+------------------------------------------------------------------------------
*/
public class CJActivityModule extends CJModulePopupBase
{
/*资源标志符*/
private static const _RESOURCE_TYPE:String = "CJActivityModuleResource";
/*模块名*/
private static const _MOUDLE_NAME:String = "CJActivityModule";
private var _mainLayer:CJActivityLayer = null;
public function CJActivityModule()
{
super(_MOUDLE_NAME);
}
override protected function _onInit(params:Object=null):void
{
super._onInit(params);
}
override public function getPreloadResource():Array
{
return [ ConstResource.sResXmlItem_1];
}
/**
*进入模块,确定显示的layer
* @param params
*/
override protected function _onEnter(params:Object=null):void
{
super._onEnter(params);
this._loadResource();
}
/**
* 退出模块,销毁layer与资源数据
* @param params
*/
override protected function _onExit(params:Object=null):void
{
super._onExit(params);
CJLayerManager.o.removeFromLayerFadeout(_mainLayer);
_mainLayer = null;
AssetManagerUtil.o.disposeAssetsByGroup(_RESOURCE_TYPE);
}
private function _loadResource():void
{
AssetManagerUtil.o.loadPrepareInQueueWithArray(_RESOURCE_TYPE , getPreloadResource());
AssetManagerUtil.o.loadQueue(_loadingHandler);
}
private function _loadingHandler(progress:Number):void
{
CJLoadingLayer.loadingprogress = progress;
if(progress == 1)
{
CJLoadingLayer.close();
this._initUi();
}
}
private function _initUi():void
{
var sxml:XML = AssetManagerUtil.o.getObject("activity.sxml") as XML;
_mainLayer = SFeatherControlUtils.o.genLayoutFromXML(sxml , CJActivityLayer) as CJActivityLayer;
CJLayerManager.o.addToModuleLayerFadein(_mainLayer);
//处理指引
if(CJDataManager.o.DataOfFuncList.isIndicating)
{
CJEventDispatcher.o.dispatchEventWith(CJEvent.EVENT_INDICATE_NEXT_STEP);
}
}
public static function get RESOURCE_TYPE():String
{
return _RESOURCE_TYPE;
}
public static function get MOUDLE_NAME():String
{
return _MOUDLE_NAME;
}
}
} |
//@todo draw display
//@todo change initialization
package {
import mx.containers.Canvas;
import mx.controls.*;
import reader.*;
import writer.*;
public class UIClient extends Canvas {
public static var textArea:TextArea;
public static var display:Display;
private var imageLoader:Image;
private var connection:UIClientConnection;
private var dReader:UIDocumentReader;
private var dWriter:UIDocumentWriter;
public function UIClient() {
super();
init();
}
private function init():void {
//this.stage.scaleMode = StageScaleMode.NO_SCALE;
//this.stage.align = StageAlign.TOP_LEFT;
display = new Display(); //ComponentFactory.setDisplay(display);
connection = new UIClientConnection(display);
loadImage();
loadText();
loadDisplay();
}
private function loadImage():void {
imageLoader = new Image();
imageLoader.x = 0;
imageLoader.y = 0;
imageLoader.load("iPhone-mini copy cut.png");
addChild(imageLoader);
}
private function loadText():void {
textArea = new TextArea();
textArea.height = 550;
textArea.width = 600;
textArea.x = 395;
textArea.y = 0;
//textField.backgroundColor = 0x00FF00;
//textField.background = true;
//textField.scrollV = 1;
addChild(textArea);
}
private function loadDisplay():Display {
display.x = 35;
display.y = 120;
addChild(display);
return display;
}
public static function debug(message:String):void {
textArea.text = textArea.text + message;
}
}
} |
package cadet3D.components.core
{
import away3d.entities.Sprite3D;
import away3d.materials.TextureMaterial;
import cadet3D.components.materials.AbstractMaterialComponent;
import cadet3D.util.NullBitmapTexture;
public class Sprite3DComponent extends ObjectContainer3DComponent
{
private var _sprite3D:Sprite3D;
private var _materialComponent:AbstractMaterialComponent;
public function Sprite3DComponent()
{
_object3D = _sprite3D = new Sprite3D(new TextureMaterial( NullBitmapTexture.instance, true, true, true ), 128, 128);
}
[Serializable][Inspectable( priority="150" )]
public function get width():Number
{
return _sprite3D.width;
}
public function set width( value:Number ):void
{
_sprite3D.width = value;
}
[Serializable][Inspectable( priority="151" )]
public function get height():Number
{
return _sprite3D.height;
}
public function set height( value:Number ):void
{
_sprite3D.height = value;
}
[Serializable][Inspectable( priority="152", editor="ComponentList", scope="scene" )]
public function get materialComponent():AbstractMaterialComponent
{
return _materialComponent;
}
public function set materialComponent(value : AbstractMaterialComponent) : void
{
_materialComponent = value;
if ( _materialComponent ) {
_sprite3D.material = _materialComponent.material;
} else {
_sprite3D.material = null;
}
}
}
} |
////////////////////////////////////////////////////////////////////////////////
// Copyright 2010 Michael Schmalle - Teoti Graphix, LLC
//
// 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
//
// Author: Michael Schmalle, Principal Architect
// mschmalle at teotigraphix dot com
////////////////////////////////////////////////////////////////////////////////
package org.as3commons.asblocks.api
{
/**
* Member visibility modifiers.
*
* @author Michael Schmalle
* @copyright Teoti Graphix, LLC
* @productversion 1.0
*/
public final class Visibility
{
//--------------------------------------------------------------------------
//
// Public :: Constants
//
//--------------------------------------------------------------------------
public static const DEFAULT:Visibility = new Visibility("default");
public static const INTERNAL:Visibility = new Visibility("internal");
public static const PRIVATE:Visibility = new Visibility("private");
public static const PROTECTED:Visibility = new Visibility("protected");
public static const PUBLIC:Visibility = new Visibility("public");
private static var list:Array;
{
list =
[
DEFAULT,
INTERNAL,
PRIVATE,
PROTECTED,
PUBLIC
];
}
//--------------------------------------------------------------------------
//
// Public :: Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// name
//----------------------------------
/**
* @private
*/
private var _name:String;
/**
* The visibility modifier name.
*/
public function get name():String
{
return _name;
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* @private
*/
public function Visibility(name:String)
{
_name = name;
}
//--------------------------------------------------------------------------
//
// Public :: Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
public function toString():String
{
return _name;
}
/**
* @private
*/
public function equals(other:Visibility):Boolean
{
return _name == other.name;
}
//--------------------------------------------------------------------------
//
// Public Class :: Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
public static function create(name:String):Visibility
{
for each (var element:Visibility in list)
{
if (element.name == name)
return element;
}
var namespace:Visibility = new Visibility(name);
list.push(namespace);
return namespace;
}
/**
* @private
*/
public static function hasVisibility(visibility:String):Boolean
{
for each (var element:Visibility in list)
{
if (element.name == visibility)
return true;
}
return false;
}
/**
* @private
*/
public static function getVisibility(visibility:String):Visibility
{
for each (var element:Visibility in list)
{
if (element.name == visibility)
return element;
}
return null;
}
}
} |
package zen.geom.intersects {
import flash.geom.Vector3D;
import flash.geom.Matrix3D;
import zen.display.*;
import flash.events.Event;
import flash.utils.getTimer;
import flash.geom.*;
import zen.display.*;
import zen.utils.*;
import zen.geom.*;
import zen.display.*;
import zen.display.*;
import flash.events.*;
import flash.utils.*;
/** Calculates intersection of 3D objects and a 3D sphere. */
public class SphereIntersect {
private static const EPSILON:Number = 0.001;
private static var _dir:Vector3D = new Vector3D();
private static var _center:Vector3D = new Vector3D();
private static var _iDir:Vector3D = new Vector3D();
private static var _normal:Vector3D = new Vector3D();
private static var _f:Vector3D = new Vector3D();
private static var _o:Vector3D = new Vector3D();
private static var _sIPoint:Vector3D = new Vector3D();
private static var _pIPoint:Vector3D = new Vector3D();
private static var _dist0:Number;
private static var _dist1:Number;
private static var _dist2:Number;
private static var _length:Number;
private static var _global:Matrix3D = new Matrix3D();
private static var _planeOrigin:Vector3D = new Vector3D();
private static var _planeNormal:Vector3D = new Vector3D();
private static var _planeD:Number = 0;
private static var _posOut:Vector3D = new Vector3D();
private static var collisionDistance:Number;
private static var collisionMesh:ZenMesh;
private static var collisionPoly:Poly3D;
private static var sphereIntersectionPoint:Vector3D = new Vector3D();
private static var polyIntersectionPoint:Vector3D = new Vector3D();
private static var _q:Vector3D = new Vector3D();
private var _src:ZenObject;
private var _radius:Number;
private var _old:Vector3D;
private var _safe:Vector3D;
private var _mesh:Vector.<ZenMesh>;
private var _pos:Vector3D;
private var _offset:Vector3D;
private var _inv:Matrix3D;
private var _collided:Boolean;
private var _collisionTime:int;
public var data:Vector.<Intersection3D>;
private var pull:Vector.<Intersection3D>;
public function SphereIntersect(source:ZenObject, radius:Number = 1, offset:Vector3D = null) {
this._mesh = new Vector.<ZenMesh>();
this._pos = new Vector3D();
this._offset = new Vector3D();
this._inv = new Matrix3D();
this.data = new Vector.<Intersection3D>();
this.pull = new Vector.<Intersection3D>();
super();
this._src = source;
this._radius = radius;
this._old = source.getPosition();
this._safe = source.getPosition();
if (offset) {
this._offset = offset;
}
}
private static function raySphere(rO:Vector3D, rV:Vector3D, sO:Vector3D, sR:Number):Number {
_q.x = (rO.x - sO.x);
_q.y = (rO.y - sO.y);
_q.z = (rO.z - sO.z);
var _B:Number = _q.dotProduct(rV);
var _C:Number = (_q.dotProduct(_q) - (sR * sR));
var _D:Number = ((_B * _B) - _C);
return ((((_D > 0)) ? (-(_B) - Math.sqrt(_D)) : Number.NaN));
}
public function toString():String {
return ("[object SphereIntersect]");
}
public function addCollisionWith(pivot:ZenObject, includeChildren:Boolean = true):void {
var mesh:ZenMesh;
var s:ZenFace;
var c:ZenObject;
if ((pivot is ZenMesh)) {
if (pivot != this._src) {
mesh = (pivot as ZenMesh);
if (this._mesh.indexOf(mesh) == -1) {
for each (s in mesh.surfaces) {
s.buildPolys();
}
this._mesh.push(mesh);
}
}
}
if (includeChildren) {
for each (c in pivot.children) {
this.addCollisionWith(c, includeChildren);
}
}
}
private function unloadEvent(e:Event):void {
this.removeCollisionWith((e.target as ZenObject), false);
}
public function removeCollisionWith(pivot:ZenObject, includeChildren:Boolean = true):void {
var mesh:ZenMesh;
var index:int;
var c:ZenObject;
if ((pivot is ZenMesh)) {
mesh = (pivot as ZenMesh);
index = this._mesh.indexOf(mesh);
if (index != -1) {
this._mesh.splice(index, 1);
}
}
if (includeChildren) {
for each (c in pivot.children) {
this.removeCollisionWith(c, includeChildren);
}
}
}
public function reset():void {
this._old.x = this._src.x;
this._old.y = this._src.y;
this._old.z = this._src.z;
this._safe.copyFrom(this._old);
}
public function fixed():Boolean {
this._collisionTime = getTimer();
this._src.setTranslation(this._offset.x, this._offset.y, this._offset.z);
while (this.data.length) {
this.pull.push(this.data.pop());
}
this.updateFixed();
if (this._collided) {
V3D.sub(this._old, sphereIntersectionPoint, _normal);
_normal.normalize();
this._src.x = (polyIntersectionPoint.x + (_normal.x * (this._radius + EPSILON)));
this._src.y = (polyIntersectionPoint.y + (_normal.y * (this._radius + EPSILON)));
this._src.z = (polyIntersectionPoint.z + (_normal.z * (this._radius + EPSILON)));
this.addInfo(collisionMesh, collisionPoly, polyIntersectionPoint, _normal);
}
this._old.x = this._src.x;
this._old.y = this._src.y;
this._old.z = this._src.z;
this._collisionTime = (getTimer() - this._collisionTime);
this._src.setTranslation(-(this._offset.x), -(this._offset.y), -(this._offset.z));
return (this._collided);
}
public function intersect():Boolean {
this._collisionTime = getTimer();
this._src.setTranslation(this._offset.x, this._offset.y, this._offset.z);
while (this.data.length) {
this.pull.push(this.data.pop());
}
this.updateFixed();
if (this._collided) {
V3D.sub(this._old, sphereIntersectionPoint, _normal);
_normal.normalize();
this.addInfo(collisionMesh, collisionPoly, polyIntersectionPoint, _normal);
}
this._old.x = this._src.x;
this._old.y = this._src.y;
this._old.z = this._src.z;
this._collisionTime = (getTimer() - this._collisionTime);
this._src.setTranslation(-(this._offset.x), -(this._offset.y), -(this._offset.z));
return (this._collided);
}
public function slider(precision:int = 2):Boolean {
var i:Intersection3D;
var from:Vector3D;
this._collisionTime = getTimer();
this._src.setTranslation(this._offset.x, this._offset.y, this._offset.z);
if (precision < 2) {
precision = 2;
}
var b:Boolean;
while (this.data.length) {
this.pull.push(this.data.pop());
}
do {
this.updateSlider();
if (this._collided) {
b = true;
this._pos.x = this._src.x;
this._pos.y = this._src.y;
this._pos.z = this._src.z;
V3D.sub(this._pos, sphereIntersectionPoint, _normal);
_normal.normalize();
_planeOrigin = polyIntersectionPoint;
_planeNormal = _normal;
_planeD = -(_planeNormal.dotProduct(_planeOrigin));
from = this._src.getPosition();
_dist0 = (((-(((((_planeNormal.x * from.x) + (_planeNormal.y * from.y)) + (_planeNormal.z * from.z)) + _planeD)) / (((_planeNormal.x * _normal.x) + (_planeNormal.y * _normal.y)) + (_planeNormal.z * _normal.z))) + this._radius) + EPSILON);
this._src.x = (this._src.x + (_normal.x * _dist0));
this._src.y = (this._src.y + (_normal.y * _dist0));
this._src.z = (this._src.z + (_normal.z * _dist0));
i = this.addInfo(collisionMesh, collisionPoly, polyIntersectionPoint, _normal);
}
--precision;
} while ((((precision >= 0)) && (this._collided)));
this._old.x = this._src.x;
this._old.y = this._src.y;
this._old.z = this._src.z;
if (!(this._collided)) {
this._safe.copyFrom(this._old);
} else {
this._src.setPosition(this._safe.x, this._safe.y, this._safe.z);
}
this._collisionTime = (getTimer() - this._collisionTime);
this._src.setTranslation(-(this._offset.x), -(this._offset.y), -(this._offset.z));
this._collided = b;
return (this._collided);
}
private function updateFixed():void {
var mesh:ZenMesh;
var bounds:Cube3D;
var s:ZenFace;
var polys:Vector.<Poly3D>;
var length:int;
var pn:int;
var p:Poly3D;
this._collided = false;
collisionDistance = Number.MAX_VALUE;
for each (mesh in this._mesh) {
_global = mesh.world;
this._inv = mesh.invWorld;
M3D.transformVector(this._inv, this._old, _o);
M3D.transformVector(this._inv, this._src.getPosition(), _f);
V3D.sub(_f, _o, _dir);
_length = _dir.length;
_dir.normalize();
_iDir.copyFrom(_dir);
_iDir.negate();
bounds = mesh.bounds;
if (bounds) {
_center.x = ((_o.x + _f.x) * 0.5);
_center.y = ((_o.y + _f.y) * 0.5);
_center.z = ((_o.z + _f.z) * 0.5);
if (Vector3D.distance(_center, bounds.center) > (((_length / 2) + this._radius) + bounds.radius)) {
//unresolved jump
}
}
for each (s in mesh.surfaces) {
_center.x = ((_o.x + _f.x) * 0.5);
_center.y = ((_o.y + _f.y) * 0.5);
_center.z = ((_o.z + _f.z) * 0.5);
if (Vector3D.distance(_center, s.bounds.center) > (((_length / 2) + this._radius) + s.bounds.radius)) {
} else {
polys = s.polys;
length = s.numTriangles;
if (length == -1) {
length = polys.length;
}
pn = (s.firstIndex / 3);
while (pn < length) {
p = polys[pn];
_dist1 = ((((p.normal.x * _o.x) + (p.normal.y * _o.y)) + (p.normal.z * _o.z)) + p.plane);
_dist2 = ((((p.normal.x * _f.x) + (p.normal.y * _f.y)) + (p.normal.z * _f.z)) + p.plane);
if ((((_dist1 > 0)) && ((_dist2 < this._radius)))) {
_sIPoint.x = (_o.x - (p.normal.x * this._radius));
_sIPoint.y = (_o.y - (p.normal.y * this._radius));
_sIPoint.z = (_o.z - (p.normal.z * this._radius));
_dist0 = (-(((((p.normal.x * _sIPoint.x) + (p.normal.y * _sIPoint.y)) + (p.normal.z * _sIPoint.z)) + p.plane)) / (((p.normal.x * _dir.x) + (p.normal.y * _dir.y)) + (p.normal.z * _dir.z)));
_pIPoint.x = (_sIPoint.x + (_dir.x * _dist0));
_pIPoint.y = (_sIPoint.y + (_dir.y * _dist0));
_pIPoint.z = (_sIPoint.z + (_dir.z * _dist0));
if (!(p.isPoint(_pIPoint.x, _pIPoint.y, _pIPoint.z))) {
p.closetPoint(_pIPoint, _pIPoint);
_dist0 = raySphere(_pIPoint, _iDir, _o, this._radius);
if (_dist0 > 0) {
_sIPoint.x = (_pIPoint.x + (_iDir.x * _dist0));
_sIPoint.y = (_pIPoint.y + (_iDir.y * _dist0));
_sIPoint.z = (_pIPoint.z + (_iDir.z * _dist0));
}
}
if ((((((_dist0 < collisionDistance)) && ((_dist0 >= 0)))) && ((_dist0 < _length)))) {
M3D.transformVector(_global, _sIPoint, sphereIntersectionPoint);
M3D.transformVector(_global, _pIPoint, polyIntersectionPoint);
this._collided = true;
collisionDistance = _dist0;
collisionPoly = p;
collisionMesh = mesh;
}
}
pn++;
}
}
}
}
}
private function updateSlider():void {
var d:Number;
var dx:Number;
var dy:Number;
var dz:Number;
var mesh:ZenMesh;
var bounds:Cube3D;
var s:ZenFace;
var polys:Vector.<Poly3D>;
var length:int;
var pn:int;
var p:Poly3D;
this._collided = false;
collisionDistance = Number.MAX_VALUE;
for each (mesh in this._mesh) {
_global = mesh.world;
this._inv = mesh.invWorld;
M3D.transformVector(this._inv, this._old, _o);
M3D.transformVector(this._inv, this._src.getPosition(true, _posOut), _f);
V3D.sub(_f, _o, _dir);
_length = _dir.length;
bounds = mesh.bounds;
if (bounds) {
_center.x = ((_o.x + _f.x) * 0.5);
_center.y = ((_o.y + _f.y) * 0.5);
_center.z = ((_o.z + _f.z) * 0.5);
if (V3D.length(_center, bounds.center) > (((_length / 2) + this._radius) + bounds.radius)) {
//unresolved jump
}
}
for each (s in mesh.surfaces) {
_center.x = ((_o.x + _f.x) * 0.5);
_center.y = ((_o.y + _f.y) * 0.5);
_center.z = ((_o.z + _f.z) * 0.5);
if (V3D.length(_center, s.bounds.center) > (((_length / 2) + this._radius) + s.bounds.radius)) {
} else {
polys = s.polys;
length = s.numTriangles;
if (length == -1) {
length = polys.length;
}
length = (length + (s.firstIndex / 3));
pn = (s.firstIndex / 3);
for (; pn < length; pn++) {
p = polys[pn];
_dist0 = (-(((((p.normal.x * _f.x) + (p.normal.y * _f.y)) + (p.normal.z * _f.z)) + p.plane)) + this._radius);
if ((((_dist0 < (_length + this._radius))) && ((_dist0 > 0)))) {
d = (_dist0 - this._radius);
_pIPoint.x = (_f.x + (p.normal.x * d));
_pIPoint.y = (_f.y + (p.normal.y * d));
_pIPoint.z = (_f.z + (p.normal.z * d));
if (!(p.isPoint(_pIPoint.x, _pIPoint.y, _pIPoint.z))) {
p.closetPoint(_pIPoint, _pIPoint);
dx = (_f.x - _pIPoint.x);
dy = (_f.y - _pIPoint.y);
dz = (_f.z - _pIPoint.z);
if ((((dx * dx) + (dy * dy)) + (dz * dz)) > (this._radius * this._radius)) {
continue;
}
_dir.x = (_f.x - _pIPoint.x);
_dir.y = (_f.y - _pIPoint.y);
_dir.z = (_f.z - _pIPoint.z);
_dir.normalize();
_sIPoint.x = (_f.x - (_dir.x * this._radius));
_sIPoint.y = (_f.y - (_dir.y * this._radius));
_sIPoint.z = (_f.z - (_dir.z * this._radius));
_dist0 = Vector3D.distance(_sIPoint, _pIPoint);
} else {
_sIPoint.x = (_f.x - (p.normal.x * this._radius));
_sIPoint.y = (_f.y - (p.normal.y * this._radius));
_sIPoint.z = (_f.z - (p.normal.z * this._radius));
}
if ((this._radius - _dist0) < collisionDistance) {
M3D.transformVector(_global, _sIPoint, sphereIntersectionPoint);
M3D.transformVector(_global, _pIPoint, polyIntersectionPoint);
this._collided = true;
collisionDistance = (this._radius - _dist0);
collisionPoly = p;
collisionMesh = mesh;
}
}
}
}
}
}
}
private function addInfo(mesh:ZenMesh, poly:Poly3D, point:Vector3D, normal:Vector3D):Intersection3D {
var i:Intersection3D = ((this.pull.length) ? this.pull.pop() : new Intersection3D());
i.mesh = mesh;
i.poly = poly;
i.point.copyFrom(point);
i.normal.copyFrom(normal);
i.u = poly.getPointU();
i.v = poly.getPointV();
this.data.push(i);
return (i);
}
public function get offset():Vector3D {
return (this._offset);
}
public function set offset(value:Vector3D):void {
this._offset = value;
this.reset();
}
public function get collided():Boolean {
return (this._collided);
}
public function get collisionTime():int {
return (this._collisionTime);
}
public function get collisionCount():int {
return (this._mesh.length);
}
public function get radius():Number {
return (this._radius);
}
public function set radius(value:Number):void {
this._radius = value;
}
public function get source():ZenObject {
return (this._src);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2009 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package spark.automation.delegates.components
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.ui.Keyboard;
import flash.utils.getTimer;
import mx.automation.Automation;
import mx.automation.AutomationIDPart;
import mx.automation.IAutomationObject;
import mx.automation.IAutomationObjectHelper;
import mx.automation.IAutomationTabularData;
import mx.core.IVisualElement;
import mx.core.mx_internal;
import mx.utils.StringUtil;
import spark.automation.delegates.components.supportClasses.SparkSkinnableContainerBaseAutomationImpl;
import spark.automation.events.SparkDataGridItemSelectEvent;
import spark.automation.tabularData.SparkDataGridTabularData;
import spark.components.DataGrid;
import spark.components.gridClasses.IGridItemRenderer;
import spark.events.GridEvent;
use namespace mx_internal;
[Mixin]
/**
*
* Defines methods and properties required to perform instrumentation for the
* DataGrid class.
*
* @see spark.components.DataGrid
*
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class SparkDataGridAutomationImpl extends SparkSkinnableContainerBaseAutomationImpl
{
include "../../../core/Version.as";
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
/**
* Registers the delegate class for a component class with automation manager.
*
* @param root The SystemManger of the application.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public static function init(root:DisplayObject):void
{
Automation.registerDelegateClass(spark.components.DataGrid, SparkDataGridAutomationImpl);
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
* @param obj DataGrid object to be automated.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function SparkDataGridAutomationImpl(obj:spark.components.DataGrid)
{
super(obj);
obj.addEventListener(Event.ADDED, childAddedHandler, false, 0, true);
obj.addEventListener(GridEvent.GRID_DOUBLE_CLICK, recordAutomatableEvent, false, 0 , true);
obj.addEventListener(GridEvent.SEPARATOR_MOUSE_UP, columnStretchHandler, false, 0, true);
obj.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false, 0, true);
obj.addEventListener(FocusEvent.KEY_FOCUS_CHANGE,keyFocusChangeHandler, false, 1000, true);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @private
*/
protected var shiftKeyDown:Boolean = false;
/**
* @private
*/
protected var ctrlKeyDown:Boolean = false;
/**
* @private
*/
mx_internal var itemAutomationNameFunction:Function = getItemAutomationValue;
private var itemUnderMouse:IGridItemRenderer;
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/**
* @private
* storage for the owner component
*/
protected function get grid():spark.components.DataGrid
{
return uiComponent as spark.components.DataGrid;
}
//--------------------------------------------------------------------------
//
// Overridden Properties
//
//--------------------------------------------------------------------------
/**
* A matrix of the automationValues of each item in the grid. The return value
* is an array of rows, each of which is an array of item renderers (row-major).
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
override public function get automationTabularData():Object
{
return new SparkDataGridTabularData(grid);
}
/**
* @private
*/
override public function get numAutomationChildren():int
{
var listItems:Array = getCompleteRenderersArray();
if (listItems.length == 0)
return 0;
var result:int = listItems.length * grid.columns.length;
return result;
}
override protected function componentInitialized():void
{
super.componentInitialized();
updateItemRenderers();
grid.grid.addEventListener(GridEvent.GRID_MOUSE_UP, gridMouseUpHandler, false, 1001, true);
grid.columnHeaderGroup.addEventListener(GridEvent.GRID_CLICK, gridClickHandler, false, 0 , true);
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
protected function compare(labels:Array, values:Array):Boolean
{
if (labels.length != values.length)
return false;
var n:int = labels.length;
for (var i:int = 0; i < n; i++)
{
if (labels[i] != values[i])
return false;
}
return true;
}
/**
* @private
*/
protected function updateItemRenderers():void
{
var items:Array = getCompleteRenderersArray();
if (items.length == 0)
return ;
var rows:uint = items.length;
var cols:uint = grid.columns.length;
for (var i:int = 0; i < rows; ++i)
{
for (var j:int = 0; j < cols; ++j)
{
var item:IGridItemRenderer = items[i][j];
if (item)
{
item.owner = grid;
}
}
}
}
/**
* @private
*/
protected function recordDGItemSelectEvent(item:IGridItemRenderer,
trigger:Event,
cacheable:Boolean=false):void
{
var selectionType:String = SparkDataGridItemSelectEvent.SELECT;
var keyEvent:KeyboardEvent = trigger as KeyboardEvent;
var mouseEvent:MouseEvent = trigger as MouseEvent;
var indexSelection:Boolean = false;
if (!Automation.automationManager || !Automation.automationManager.automationEnvironment
|| !Automation.automationManager.recording)
return ;
var event:SparkDataGridItemSelectEvent = new SparkDataGridItemSelectEvent(selectionType);
event.itemRenderer = item;
event.triggerEvent = trigger;
if (keyEvent)
{
event.ctrlKey = keyEvent.ctrlKey;
event.shiftKey = keyEvent.shiftKey;
event.altKey = keyEvent.altKey;
}
else if (mouseEvent)
{
event.ctrlKey = mouseEvent.ctrlKey;
event.shiftKey = mouseEvent.shiftKey;
event.altKey = mouseEvent.altKey;
}
recordAutomatableEvent(event, cacheable);
}
/**
* @private
*/
protected function recordDGHeaderClickEvent(item:IGridItemRenderer,
trigger:Event,
cacheable:Boolean=false):void
{
//recordAutomatableEvent(event, cacheable);
}
/**
* @private
* Plays back MouseEvent.CLICK on the item renderer.
*/
protected function replayMouseClickOnItem(item:IGridItemRenderer,
ctrlKey:Boolean = false,
shiftKey:Boolean = false,
altKey:Boolean = false):Boolean
{
var me:MouseEvent = new MouseEvent(MouseEvent.CLICK);
me.ctrlKey = ctrlKey;
me.altKey = altKey;
me.shiftKey = shiftKey;
var help:IAutomationObjectHelper = Automation.automationObjectHelper;
return help.replayClick(item, me);
}
/**
* @private
* Plays back MouseEvent.DOUBLE_CLICK on the item renderer.
*/
protected function replayMouseDoubleClickOnItem(item:IGridItemRenderer):Boolean
{
var me:MouseEvent = new MouseEvent(MouseEvent.DOUBLE_CLICK);
var help:IAutomationObjectHelper = Automation.automationObjectHelper;
return help.replayMouseEvent(item, me);
}
/**
* @private
*/
protected function getItemRendererForEvent(lise:SparkDataGridItemSelectEvent):IGridItemRenderer
{
var rowIndex:int = lise.itemIndex;
//rowIndex = rowIndex < grid.lockedRowCount ? rowIndex : rowIndex - grid.verticalScrollPosition;
return grid.grid.getItemRendererAt(rowIndex, 0) as IGridItemRenderer;
}
/**
* @private
*/
protected function fillItemRendererIndex(item:IGridItemRenderer, event:SparkDataGridItemSelectEvent):void
{
var listItems:Array = getCompleteRenderersArray();
var startRow:int = 0;
//This portion is commented out as now the rowHeaders are separated
/*
if(grid.headerVisible)
++startRow;
*/
var n:int = listItems.length;
for (var i:int = startRow; i < n; i++)
{
var n1:int = listItems[i].length;
for (var j:int = 0; j < n1; j++)
{
if (listItems[i][j] == item)
{
event.itemIndex = i + grid.grid.verticalScrollPosition - 1;
}
}
}
}
/**
* @private
*/
public function getVisibleRenderersArray():Array
{
const visibleRowIndices:Vector.<int> = grid.grid.getVisibleRowIndices();
const visibleColumnIndices:Vector.<int> = grid.grid.getVisibleColumnIndices();
const renderers:Array = new Array(visibleRowIndices.length);
for each (var rowIndex:int in visibleRowIndices)
{
renderers[rowIndex] = new Array(visibleColumnIndices.length);
for each (var columnIndex:int in visibleColumnIndices)
renderers[rowIndex][columnIndex] = grid.grid.getItemRendererAt(rowIndex, columnIndex);
}
return renderers;
}
/**
* @private
*/
public function getCompleteRenderersArray():Array
{
var rowCount:int = 0;
if(grid.dataProvider)
rowCount = grid.dataProvider.length;
var columnCount:int = 0;
if(grid.columns)
columnCount = grid.columns.length;
const renderers:Array = new Array(rowCount+1);
renderers[0] = new Array(columnCount);
for (var col:int = 0; col < columnCount; col++)
{
renderers[0][col] = grid.columnHeaderGroup.getHeaderRendererAt(col);
}
for (var rowIndex:int = 0; rowIndex < rowCount; rowIndex++)
{
renderers[rowIndex+1] = new Array(columnCount);
for (var columnIndex:int = 0; columnIndex < columnCount; columnIndex++)
renderers[rowIndex+1][columnIndex] = grid.grid.getItemRendererAt(rowIndex, columnIndex);
}
return renderers;
}
/**
* @private
*/
protected function trimArray(val:Array):void
{
var n:int = val.length;
for (var i:int = 0; i <n; i++)
{
val[i] = StringUtil.trim(val[i]);
}
}
/**
* @private
*/
protected function findItemRenderer(selectEvent:SparkDataGridItemSelectEvent):Boolean
{
if (selectEvent.itemAutomationValue && selectEvent.itemAutomationValue.length)
{
var itemLabel:String = selectEvent.itemAutomationValue;
var tabularData:IAutomationTabularData = automationTabularData as IAutomationTabularData;
var values:Array = tabularData.getValues(0, tabularData.numRows);
var length:int = values.length;
var part:AutomationIDPart = new AutomationIDPart();
part.automationName = itemLabel;
var labels:Array = itemLabel.split("|");
trimArray(labels);
var index:int = 0;
for each (var a:Array in values)
{
values[index] = [];
trimArray(a);
for each (var b:String in a)
{
var splitArray:Array = b.split("|");
for each ( var c:String in splitArray)
values[index].push(c);
}
trimArray(values[index]);
++index;
}
var n:int = labels.length;
var i:int;
for (i = 0; i < n; i++)
{
var lString:String = labels[i];
if (lString.charAt(0) == "*" && lString.charAt(lString.length-1) == "*")
labels[i] = lString.substr(1, lString.length-2);
}
for (i = 0; i < length; i++)
{
if(compare(labels, values[i]))
{
grid.ensureCellIsVisible(i);
var ao:IAutomationObject = Automation.automationManager.resolveIDPartToSingleObject(uiAutomationObject, part);
if (ao)
{
selectEvent.itemRenderer = ao as IGridItemRenderer;
return true;
}
}
}
}
return false;
}
/**
* @private
*/
public function getItemAutomationValue(item:IAutomationObject):String
{
return getItemAutomationNameOrValueHelper(item, false);
}
/**
* @private
*/
public function getItemAutomationName(item:IAutomationObject):String
{
return getItemAutomationNameOrValueHelper(item, true);
}
/**
* @private
*/
public function getItemAutomationIndex(delegate:IAutomationObject):String
{
var item:Object = delegate;
if (item == grid.itemEditorInstance && grid.editor &&
(grid.editor.editorRowIndex >= 0) && (grid.editor.editorColumnIndex >= 0))
item = grid.editor.editedItemRenderer;
var row:int = item.rowIndex;
if(row >= 0 && item.column)
{
return (item.column.dataField + ":" + row);
}
return getItemAutomationName(delegate);
}
/**
* @private
*/
private function getItemAutomationNameOrValueHelper(delegate:IAutomationObject,
useName:Boolean):String
{
var result:Array = [];
var item:Object = delegate;
if (item == grid.itemEditorInstance)
item = grid.editor.editedItemRenderer;
var row:int = item.rowIndex;
var isHeader:Boolean = false;
if (row == int.MIN_VALUE)
{
// return null; -- this is commented after the header related
// changes in DG.
// now for the headers also , it cmes as min_value
// so we cannot make out header or invalid renderer
//isHeader = grid.headerVisible;
}
/*row = row < grid.lockedRowCount ?
row :
row - grid.verticalScrollPosition; */
if (row >= 0)
{
row = row + 1;
}
else
{
row = 0;
}
var listItems:Array = getCompleteRenderersArray();
//var listItems:Array = grid.rendererArray; .. changed as above to take care of the
// locked row and locked column changed handling of DG
// this varaible is added, since we are proceeding
// even if the itemRendererToIndex is returning int.MIN_VALUE
// we are assuming that the user clicked the header in this case
// But we need to find whether this is valid
// this is found by checking whether we get the clicked item
// in one of the column header renderer
var validItemRendererFound:Boolean = false;
var tabData:IAutomationTabularData = automationTabularData as IAutomationTabularData;
var firstVisibleRowIndex:int = tabData.firstVisibleRow;
for (var col:int = 0; col < listItems[row].length; col++)
{
var i:IVisualElement = listItems[row][col];
if(i != null) //can be null if column is not visible
{
if(i == grid.editor.editedItemRenderer)
i = grid.itemEditorInstance;
var itemDelegate:IAutomationObject = i as IAutomationObject;
var s:String = (useName
? itemDelegate.automationName
: itemDelegate.automationValue.join(" | "));
if ( i == item )
{
// we got a valid item renderer
s= "*" + s + "*";
validItemRendererFound= true;
}
result.push(s);
}
}
if(isHeader && (validItemRendererFound==false))
{
// we got the itemRendererToIndex(item) as int.MIN_VALUE
// so we considered it as a header row
// but no element on the header row match with the
// current item renderer. Hence returning null
return null;
}
return (isHeader
? "[" + result.join("] | [") + "]"
: result.join(" | "));
}
/**
* private
*/
protected function addScrollers(chilArray:Array):Array
{
var count:int = grid.numChildren;
for (var i:int=0; i<count; i++)
{
var obj:Object = grid.getChildAt(i);
// here if are getting scrollers, we need to add the scrollbars. we dont need to
// consider the view port contents as the data content is handled using the renderes.
if(obj is spark.components.Scroller)
{
var scroller:spark.components.Scroller = obj as spark.components.Scroller;
if(scroller.horizontalScrollBar && scroller.horizontalScrollBar.visible)
chilArray.push(scroller.horizontalScrollBar);
if(scroller.verticalScrollBar && scroller.verticalScrollBar.visible)
chilArray.push(scroller.verticalScrollBar);
}
}
var scrollBars:Array = getScrollBars(grid,null);
var n:int = scrollBars? scrollBars.length : 0;
for ( i=0; i<n ; i++)
{
chilArray.push(scrollBars[i]);
}
return chilArray;
}
//--------------------------------------------------------------------------------
//
// Overridden Methods
//
//--------------------------------------------------------------------------------
/**
* @private
*/
override public function createAutomationIDPart(child:IAutomationObject):Object
{
var help:IAutomationObjectHelper = Automation.automationObjectHelper;
return (help
? help.helpCreateIDPart(uiAutomationObject, child, itemAutomationNameFunction,
getItemAutomationIndex)
: null);
}
/**
* @private
*/
override public function createAutomationIDPartWithRequiredProperties(child:IAutomationObject, properties:Array):Object
{
var help:IAutomationObjectHelper = Automation.automationObjectHelper;
return (help
? help.helpCreateIDPartWithRequiredProperties(uiAutomationObject, child, properties,itemAutomationNameFunction,
getItemAutomationIndex)
: null);
}
/**
* @private
*/
override public function resolveAutomationIDPart(part:Object):Array
{
var help:IAutomationObjectHelper = Automation.automationObjectHelper;
return help ? help.helpResolveIDPart(uiAutomationObject, part) : null;
}
/**
* @private
*/
override public function replayAutomatableEvent(interaction:Event):Boolean
{
var help:IAutomationObjectHelper = Automation.automationObjectHelper;
var mouseEvent:MouseEvent;
switch (interaction.type)
{
case GridEvent.GRID_CLICK:
{
var colIndex:int = GridEvent(interaction).columnIndex;
var rect:Rectangle = grid.columnHeaderGroup.getHeaderBounds(colIndex);
MouseEvent(interaction).localX = rect.left + rect.width/2;
MouseEvent(interaction).localY = rect.top + rect.height/2;
return help.replayClick(grid.columnHeaderGroup, MouseEvent(interaction));
}
case GridEvent.GRID_DOUBLE_CLICK:
{
var clickEvent:GridEvent = GridEvent(interaction);
return replayMouseDoubleClickOnItem(grid.grid.getItemRendererAt(clickEvent.rowIndex, clickEvent.columnIndex) as IGridItemRenderer);
}
case KeyboardEvent.KEY_DOWN:
{
grid.setFocus();
return help.replayKeyDownKeyUp(uiComponent, KeyboardEvent(interaction).keyCode, KeyboardEvent(interaction).ctrlKey, KeyboardEvent(interaction).shiftKey, KeyboardEvent(interaction).altKey);
}
case SparkDataGridItemSelectEvent.SELECT_INDEX:
case SparkDataGridItemSelectEvent.SELECT:
{
var completeTime:Number = getTimer() + grid.getStyle("selectionDuration");
help.addSynchronization(function():Boolean
{
return getTimer() >= completeTime;
});
var lise:SparkDataGridItemSelectEvent = SparkDataGridItemSelectEvent(interaction);
if (interaction.type == SparkDataGridItemSelectEvent.SELECT_INDEX)
{
/*grid.grid.scrollToIndex(lise.itemIndex);
lise.itemRenderer = getItemRendererForEvent(lise);*/
}
else
{
if (!lise.itemRenderer)
findItemRenderer(lise);
}
// keyboard and mouse are currently treated the same
if (lise.triggerEvent is MouseEvent)
{
return replayMouseClickOnItem(lise.itemRenderer,
lise.ctrlKey,
lise.shiftKey,
lise.altKey);
}
else if (lise.triggerEvent is KeyboardEvent)
{
return help.replayKeyDownKeyUp(lise.itemRenderer,
Keyboard.SPACE,
lise.ctrlKey,
lise.shiftKey,
lise.altKey);
}
else
{
throw new Error();
}
}
case "editNext":
{
if(grid.itemEditorInstance)
{
var focusEvent:FocusEvent = new FocusEvent(FocusEvent.KEY_FOCUS_CHANGE);
focusEvent.keyCode = Keyboard.TAB;
grid.itemEditorInstance.dispatchEvent(focusEvent);
grid.startItemEditorSession(grid.grid.caretRowIndex, grid.grid.caretColumnIndex);
return true;
}
return false;
}
/*case "headerShift":
{
var icEvent:IndexChangedEvent = IndexChangedEvent(interaction);
grid.shiftColumns(icEvent.oldIndex, icEvent.newIndex);
return true;
}
case DataGridEvent.HEADER_RELEASE:
{
var listItems:Array = getCompleteRenderersArray();
//var listItems:Array = grid.rendererArray; .. changed as above to take care of the
// locked row and locked column changed handling of DG
var c:IListItemRenderer = listItems[0][DataGridEvent(interaction).columnIndex];
return help.replayClick(c);
}*/
case GridEvent.SEPARATOR_MOUSE_UP:
{
var s:IGridItemRenderer = grid.columnHeaderGroup.getHeaderRendererAt(GridEvent(interaction).columnIndex);
//s.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_DOWN, true, false, 0, 0));
// localX needs to be passed in the constructor
// to get stageX value computed.
mouseEvent = new MouseEvent(MouseEvent.MOUSE_DOWN, true, false, s.width, 10);
help.replayMouseEvent(s, mouseEvent);
mouseEvent = new MouseEvent(MouseEvent.MOUSE_MOVE, true, false, GridEvent(interaction).localX, 10);
help.replayMouseEvent(grid, mouseEvent);
mouseEvent = new MouseEvent(MouseEvent.MOUSE_UP,
true, // bubble
false, // cancellable
GridEvent(interaction).localX,
10 // dummy value
);
help.replayMouseEvent(grid, mouseEvent);
mouseEvent = new MouseEvent(MouseEvent.CLICK,
true, // bubble
false, // cancellable
GridEvent(interaction).localX,
10 // dummy value
);
return help.replayMouseEvent(grid, mouseEvent);
}
/*case DataGridEvent.ITEM_EDIT_BEGIN:
{
var de:DataGridEvent = new DataGridEvent(DataGridEvent.ITEM_EDIT_BEGINNING);
var input:DataGridEvent = interaction as DataGridEvent;
de.itemRenderer = input.itemRenderer;
de.rowIndex = input.rowIndex;
de.columnIndex = input.columnIndex;
uiComponent.dispatchEvent(de);
}*/
default:
{
return super.replayAutomatableEvent(interaction);
}
}
}
/**
* @private
*/
override public function getAutomationChildAt(index:int):IAutomationObject
{
var listItems:Array = getCompleteRenderersArray();
//var listItems:Array = grid.rendererArray; .. changed as above to take care of the
// locked row and locked column changed handling of DG
var numCols:int = grid.columns.length;
var row:uint = uint(numCols == 0 ? 0 : index / numCols);
var col:uint = uint(numCols == 0 ? index : index % numCols);
var item:IGridItemRenderer = listItems[row][col];
if (grid.itemEditorInstance && grid.editor &&
(grid.editor.editorRowIndex >= 0) && (grid.editor.editorColumnIndex >= 0) &&
item == grid.editor.editedItemRenderer)
{
return grid.itemEditorInstance as IAutomationObject;
}
return item as IAutomationObject;
}
/**
* @private
*/
override public function getAutomationChildren():Array
{
var childrenList:Array = new Array();
var listItems:Array = getCompleteRenderersArray();
// we get this as the 2 dim array of row and columns
// we need to make this as single element array
//while (!listItems[row][col]
var rowcount:int = listItems?listItems.length:0;
if (rowcount != 0)
{
var colCount:int = grid.columns.length;
/*if ((listItems[0]) is Array)
coulumcount = (listItems[0] as Array).length;*/
for (var i:int = 0; i < rowcount ; i++)
{
for (var j:int = 0; j < colCount ; j++)
{
var item:IGridItemRenderer = listItems[i][j];
if (item)
{
if (grid.itemEditorInstance && grid.editor &&
(grid.editor.editorRowIndex >= 0) && (grid.editor.editorColumnIndex >= 0) &&
item == grid.editor.editedItemRenderer)
childrenList.push(grid.itemEditorInstance as IAutomationObject);
else
childrenList.push(item as IAutomationObject);
}
}
}
}
childrenList = addScrollers(childrenList);
return childrenList;
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
private function keyFocusChangeHandler(event:FocusEvent):void
{
if(grid.itemEditorInstance)
{
recordAutomatableEvent(new Event("editNext"));
}
}
/**
* @private
*/
protected function gridClickHandler(event:GridEvent):void
{
if (!Automation.automationManager || !Automation.automationManager.automationEnvironment
|| !Automation.automationManager.recording)
return;
var item:IGridItemRenderer = grid.columnHeaderGroup.getHeaderRendererAt(event.columnIndex);
recordAutomatableEvent(event, true);
}
/**
* @private
*/
protected function gridMouseUpHandler(event:GridEvent):void
{
if (!Automation.automationManager || !Automation.automationManager.automationEnvironment
|| !Automation.automationManager.recording)
return;
var gbPt:Point = event.target.localToGlobal(new Point(event.localX, event.localY));
var locPt:Point = grid.grid.globalToLocal(gbPt);
var item:IGridItemRenderer = grid.grid.getItemRendererAt(grid.grid.getRowIndexAt(locPt.x, locPt.y),
grid.grid.getColumnIndexAt(locPt.x, locPt.y)) as IGridItemRenderer;
if (item && item == itemUnderMouse)
{
// take the key modifiers from the mouseDown event because
// they were used by List for making the selection
if(event.itemRenderer != item || (grid.editor && item == grid.editor.editedItemRenderer))
return;
else
{
event.ctrlKey = ctrlKeyDown;
event.shiftKey = shiftKeyDown;
recordDGItemSelectEvent(item, event);
}
}
}
/**
* @private
*/
public function childAddedHandler(event:Event):void
{
var child:Object = event.target;
if (child is IGridItemRenderer && child.parent == grid.grid)
{
IGridItemRenderer(child).owner = grid;
}
}
/**
* @private
*/
protected function mouseDownHandler(event:MouseEvent):void
{
ctrlKeyDown = event.ctrlKey;
shiftKeyDown = event.shiftKey;
var gbPt:Point = event.target.localToGlobal(new Point(event.localX, event.localY));
var locPt:Point = grid.grid.globalToLocal(gbPt);
itemUnderMouse = grid.grid.getItemRendererAt(grid.grid.getRowIndexAt(locPt.x, locPt.y),
grid.grid.getColumnIndexAt(locPt.x, locPt.y)) as IGridItemRenderer;
}
/**
* @private
*/
override protected function keyDownHandler(event:KeyboardEvent):void
{
if (//grid.itemEditorInstance ||
event.target != event.currentTarget)
return;
if (event.keyCode == Keyboard.SPACE)
{
var caretRowIndex:int = grid.grid.caretRowIndex;
if (caretRowIndex != -1)
{
var caretColumnIndex:int = grid.grid.caretColumnIndex;
if(caretColumnIndex == -1)
caretColumnIndex = 0;
var item:IGridItemRenderer = grid.grid.getItemRendererAt(caretRowIndex,caretColumnIndex) as IGridItemRenderer;
recordDGItemSelectEvent(item, event);
}
}
else if (event.keyCode != Keyboard.SPACE &&
event.keyCode != Keyboard.CONTROL &&
event.keyCode != Keyboard.SHIFT &&
event.keyCode != Keyboard.TAB)
{
recordAutomatableEvent(event);
}
}
/**
* @private
*/
private function columnStretchHandler(event:GridEvent):void
{
recordAutomatableEvent(event);
}
/**
* @private
*/
/*private function headerReleaseHandler(event:DataGridEvent):void
{
recordAutomatableEvent(event);
}*/
/**
* @private
*/
/*private function headerShiftHandler(event:IndexChangedEvent):void
{
if (event.triggerEvent)
recordAutomatableEvent(event);
}*/
/**
* @private
*/
/*private function itemEditHandler(event:DataGridEvent):void
{
recordAutomatableEvent(event, true);
}*/
/**
* @private
*/
/*protected function dragDropHandler(event:DragEvent):void
{
if(dragScrollEvent)
{
recordAutomatableEvent(dragScrollEvent);
dragScrollEvent=null;
}
var am:IAutomationManager = Automation.automationManager;
var index:int = grid.calculateDropIndex(event);
var drag:AutomationDragEvent = new AutomationDragEvent(event.type);
drag.action = event.action;
if (grid.dataProvider && index != grid.dataProvider.length)
{
//increment the index if headers are being shown
if(grid.headerVisible)
++index;
if (index >= grid.lockedRowCount)
index -= grid.verticalScrollPosition;
var completeListitems:Array = getCompleteRenderersArray();
//var rc:Number = grid.rendererArray.length;
var rc:Number = completeListitems.length;
if (index >= rc)
index = rc - 1;
if (index < 0)
index = 0;
//if(grid.rendererArray && grid.rendererArray[0] && grid.rendererArray[0].length)
//index = index * grid.rendererArray[0].length;
if(completeListitems && completeListitems[0] && completeListitems[0].length)
index = index * completeListitems[0].length;
drag.draggedItem = getAutomationChildAt(index);
}
preventDragDropRecording = false;
am.recordAutomatableEvent(uiAutomationObject, drag);
preventDragDropRecording = true;
}*/
}
}
|
package com.jankuester.pdfviewertests.utils
{
import com.jankuester.pdfviewer.core.model.PDFConstants;
import com.jankuester.pdfviewer.utils.ByteArrayUtils;
import com.jankuester.pdfviewer.utils.PdfBinaryUtils;
import flash.utils.ByteArray;
import flexunit.framework.Assert;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
public class PDFBinaryUtilsTest
{
[Before]
public function setUp():void
{
}
[After]
public function tearDown():void
{
}
[BeforeClass]
public static function setUpBeforeClass():void
{
}
[AfterClass]
public static function tearDownAfterClass():void
{
}
[Test]
public function testFindStreamPositions():void
{
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("stream");
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("endstream");
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("stream");
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("endstream");
var streams:Array = PdfBinaryUtils.findStreamPositions(ba);
Assert.assertNotNull(streams);
Assert.assertEquals(streams.length,4);
Assert.assertEquals("ABCDE",ByteArrayUtils.readStringFromTo(ba,streams[0],streams[1],true));
Assert.assertEquals(12, streams[0] );
Assert.assertEquals(streams[1], 17);
Assert.assertEquals("A",ByteArrayUtils.readString(ba,streams[0],1,true));
Assert.assertEquals(streams[2], 39);
Assert.assertEquals(streams[3], 44);
Assert.assertEquals("ABCDE",ByteArrayUtils.readStringFromTo(ba,streams[2],streams[3],true));
}
[Test]
public function testPurgeStreamChars():void
{
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("stream");
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("endstream");
var streams:Array = PdfBinaryUtils.findStreamPositions(ba);
var start:int = PdfBinaryUtils.purgeStreamChars(ba, streams[0]);
var end:int = PdfBinaryUtils.purgeEndstreamChars(ba, streams[1]);
Assert.assertEquals(0,start);
Assert.assertEquals(0,end);
ba = new ByteArray();
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("stream\n");
ba.writeUTFBytes("ABCDE\n");
ba.writeUTFBytes("endstream\n");
streams = PdfBinaryUtils.findStreamPositions(ba);
start = PdfBinaryUtils.purgeStreamChars(ba, streams[0]-2);
end = PdfBinaryUtils.purgeEndstreamChars(ba, streams[1]+3);
Assert.assertEquals(2,start);
Assert.assertEquals(3,end);
start = PdfBinaryUtils.purgeStreamChars(ba, streams[0]-7);
end = PdfBinaryUtils.purgeEndstreamChars(ba, streams[1]+10);
Assert.assertEquals(7,start);
Assert.assertEquals(10,end);
}
[Test]
public function getStreamDefTest():void
{
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes("ABCDEFG");
var type:String = PdfBinaryUtils.getStreamDef(ba, ba.length);
assertEquals("none",type);
ba.writeUTFBytes(PDFConstants.DEFLATE);
ba.writeUTFBytes("ABCDEFG");
ba.writeUTFBytes("ABCDEFG");
type = PdfBinaryUtils.getStreamDef(ba, ba.length);
assertEquals(PDFConstants.DEFLATE, type);
ba.writeUTFBytes(PDFConstants.DCT);
ba.writeUTFBytes("ABCDEFG");
ba.writeUTFBytes("ABCDEFG");
type = PdfBinaryUtils.getStreamDef(ba, ba.length);
assertEquals(PDFConstants.DCT, type);
}
[Test]
public function testReadStream():void
{
var pattern:String="helloworld";
var origin:ByteArray = new ByteArray();
origin.writeUTFBytes("ABCDEF");
origin.writeUTFBytes(PDFConstants.DEFLATE);
origin.writeUTFBytes("stream\n");
var toCompress:ByteArray = new ByteArray();
toCompress.writeUTFBytes(pattern);
toCompress.compress();
//trace("to compress: "+toCompress.length);
//trace("origin before write: "+origin.length);
origin.writeBytes(toCompress, 0,18);
//trace("origin after write: "+origin.length);
origin.writeUTFBytes("\nendstream");
//trace("origin after 2. write: "+origin.length);
var uncompressed:ByteArray = PdfBinaryUtils.decodeStream(toCompress,0,toCompress.length);
Assert.assertNotNull(uncompressed);
var compressed:String = ByteArrayUtils.readString(toCompress);
//trace("-------------------- origin -------------------");
//trace(ByteArrayUtils.readString(origin));
var streams:Array = PdfBinaryUtils.findStreamPositions(origin);
//trace("------------------ readstream ----------------");
//trace(streams[0]+" "+streams[1]);
var result:ByteArray = PdfBinaryUtils.decodeStream(origin, streams[0], streams[1]);
var resString:String = ByteArrayUtils.readString(result);
//trace(resString);
var expectedRes:String ="ABCDEFflatedecodestream\nhelloworld\nendstream";
assertNotNull(result);
assertEquals(pattern.length, resString.length);
assertEquals(pattern,resString);
}
[Test]
public function getXREFTest():void
{
}
}
} |
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2009 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
package mx.olap
{
import mx.core.mx_internal;
use namespace mx_internal;
/**
* The OLAPResult class represents the result of a query on an OLAP cube.
*
* @see mx.olap.IOLAPResult
* @see mx.olap.OLAPQuery
* @see mx.olap.OLAPQueryAxis
* @see mx.olap.IOLAPResultAxis
* @see mx.olap.OLAPResultAxis
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public class OLAPResult implements IOLAPResult
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Class constants
//
//--------------------------------------------------------------------------
/**
* Specifies a column axis.
* Use this property as a value of the <code>axisOrdinal</code> argument
* to the <code>getAxis()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static var COLUMN_AXIS:int = 0;
/**
* Specifies a row axis.
* Use this property as a value of the <code>axisOrdinal</code> argument
* to the <code>getAxis()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static var ROW_AXIS:int = 1;
/**
* Specifies a slicer axis.
* Use this property as a value of the <code>axisOrdinal</code> argument
* to the <code>getAxis()</code> method.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static var SLICER_AXIS:int = 2;
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* An Array of Arrays that contains the value of each cell of the result.
* A cell is an intersection of a row and a column axis position.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
protected var cellData:Array = [];
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// axes
//----------------------------------
private var _axes:Array = [];
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get axes():Array
{
return _axes;
}
//----------------------------------
// query
//----------------------------------
private var _query:IOLAPQuery;
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function get query():IOLAPQuery
{
return _query;
}
/**
* @private
*/
public function set query(q:IOLAPQuery):void
{
_query = q;
}
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getAxis(axisOrdinal:int):IOLAPResultAxis
{
return axes[axisOrdinal];
}
/**
* @private
* Sets an axis of the query result.
*
* @param axisOrdinal Specify <code>OLAPResult.COLUMN AXIS</code> for a column axis,
* <code>OLAPResult.ROW_AXIS</code> for a row axis,
* and <code>OLAPResult.SLICER_AXIS</code> for a slicer axis.
*
* @param axis The IOLAPResultAxis instance.
*/
mx_internal function setAxis(axisOrdinal:int, axis:IOLAPResultAxis):void
{
axes[axisOrdinal] = axis;
}
/**
* @inheritDoc
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function getCell(x:int, y:int):IOLAPCell
{
if (cellData[x])
return new OLAPCell(cellData[x][y]);
return new OLAPCell(NaN);
}
/**
* private
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
mx_internal function setCell(x:int, y:int, value:Number):void
{
if (!cellData[x])
cellData[x] = [];
cellData[x][y] = value;
}
/**
* Returns <code>true</code> if the row contains data.
*
* @param rowIndex The index of the row in the result.
*
* @return <code>true</code> if the row contains data,
* and <code>false</code> if not.
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public function hasRowData(rowIndex:int):Boolean
{
return cellData[rowIndex] != undefined;
}
/**
* @private
* Removes a row of data from the result.
*
* @param y The index of the row in the result.
*/
mx_internal function removeRowData(y:int):void
{
cellData.splice(y, 1);
}
/**
* @private
* Removes a column of data from the result.
*
* @param x The index of the column in the result.
*/
mx_internal function removeColumnData(x:int):void
{
for each (var a:Array in cellData)
{
a.splice(x, 1);
}
}
}
} |
package kabam.rotmg.constants {
public class GeneralConstants {
public static const MAXIMUM_INTERACTION_DISTANCE:int = 1;
public static const NUM_EQUIPMENT_SLOTS:int = 4;
public static const NUM_INVENTORY_SLOTS:int = 8;
public function GeneralConstants() {
super();
}
}
}
|
/*
Feathers
Copyright 2012-2021 Bowler Hat LLC. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
package feathers.controls
{
import feathers.controls.supportClasses.IScreenNavigatorItem;
import starling.display.DisplayObject;
/**
* Data for an individual screen that will be displayed by a
* <code>ScreenNavigator</code> component.
*
* <p>The following example creates a new <code>ScreenNavigatorItem</code>
* using the <code>SettingsScreen</code> class to instantiate the screen
* instance. When the screen is shown, its <code>settings</code> property
* will be set. When the screen instance dispatches
* <code>Event.COMPLETE</code>, the <code>ScreenNavigator</code> will
* navigate to a screen with the ID <code>"mainMenu"</code>.</p>
*
* <listing version="3.0">
* var settingsData:Object = { volume: 0.8, difficulty: "hard" };
* var item:ScreenNavigatorItem = new ScreenNavigatorItem( SettingsScreen );
* item.properties.settings = settingsData;
* item.setScreenIDForEvent( Event.COMPLETE, "mainMenu" );
* navigator.addScreen( "settings", item );</listing>
*
* @see ../../../help/screen-navigator.html How to use the Feathers ScreenNavigator component
* @see feathers.controls.ScreenNavigator
*
* @productversion Feathers 1.0.0
*/
public class ScreenNavigatorItem implements IScreenNavigatorItem
{
/**
* Constructor.
*/
public function ScreenNavigatorItem(screen:Object = null, events:Object = null, properties:Object = null)
{
this._screen = screen;
this._events = events ? events : {};
this._properties = properties ? properties : {};
}
/**
* @private
*/
protected var _screen:Object;
/**
* The screen to be displayed by the <code>ScreenNavigator</code>. It
* may be one of several possible types:
*
* <ul>
* <li>a <code>Class</code> that may be instantiated to create a <code>DisplayObject</code></li>
* <li>a <code>Function</code> that returns a <code>DisplayObject</code></li>
* <li>a Starling <code>DisplayObject</code> that is already instantiated</li>
* </ul>
*
* <p>If the screen is a <code>Class</code> or a <code>Function</code>,
* a new instance of the screen will be instantiated every time that it
* is shown by the <code>ScreenNavigator</code>. The screen's state
* will not be saved automatically. The screen's state may be saved in
* <code>properties</code>, if needed.</p>
*
* <p>If the screen is a <code>DisplayObject</code>, the same instance
* will be reused every time that it is shown by the
* <code>ScreenNavigator</code>. When the screen is shown again, its
* state will remain the same as when it was previously hidden. However,
* the screen will also be kept in memory even when it isn't visible,
* limiting the resources that are available for other screens.</p>
*
* @default null
*/
public function get screen():Object
{
return this._screen;
}
/**
* @private
*/
public function set screen(value:Object):void
{
this._screen = value;
}
/**
* @private
*/
protected var _events:Object;
/**
* A set of key-value pairs representing actions that should be
* triggered when events are dispatched by the screen when it is shown.
* A pair's key is the event type to listen for (or the property name of
* an <code>ISignal</code> instance), and a pair's value is one of two
* possible types. When this event is dispatched, and a pair's value
* is a <code>String</code>, the <code>ScreenNavigator</code> will show
* another screen with an ID equal to the string value. When this event
* is dispatched, and the pair's value is a <code>Function</code>, the
* function will be called as if it were a listener for the event.
*
* @see #setFunctionForEvent()
* @see #setScreenIDForEvent()
*/
public function get events():Object
{
return this._events;
}
/**
* @private
*/
public function set events(value:Object):void
{
if(!value)
{
value = {};
}
this._events = value;
}
/**
* @private
*/
protected var _properties:Object;
/**
* A set of key-value pairs representing properties to be set on the
* screen when it is shown. A pair's key is the name of the screen's
* property, and a pair's value is the value to be passed to the
* screen's property.
*/
public function get properties():Object
{
return this._properties;
}
/**
* @private
*/
public function set properties(value:Object):void
{
if(!value)
{
value = {};
}
this._properties = value;
}
/**
* @inheritDoc
*/
public function get canDispose():Boolean
{
return !(this._screen is DisplayObject);
}
/**
* @private
*/
protected var _transitionDelayEvent:String = null;
/**
* @inheritDoc
*/
public function get transitionDelayEvent():String
{
return this._transitionDelayEvent;
}
/**
* @private
*/
public function set transitionDelayEvent(value:String):void
{
this._transitionDelayEvent = value;
}
/**
* Specifies a function to call when an event is dispatched by the
* screen.
*
* <p>If the screen is currently being displayed by a
* <code>ScreenNavigator</code>, and you call
* <code>setFunctionForEvent()</code> on the <code>ScreenNavigatorItem</code>,
* the <code>ScreenNavigator</code> won't listen for the event until
* the next time that the screen is shown.</p>
*
* @see #setScreenIDForEvent()
* @see #clearEvent()
* @see #events
*/
public function setFunctionForEvent(eventType:String, action:Function):void
{
this._events[eventType] = action;
}
/**
* Specifies another screen to navigate to when an event is dispatched
* by this screen. The other screen should be specified by its ID that
* is registered with the <code>ScreenNavigator</code>.
*
* <p>If the screen is currently being displayed by a
* <code>ScreenNavigator</code>, and you call
* <code>setScreenIDForEvent()</code> on the <code>ScreenNavigatorItem</code>,
* the <code>ScreenNavigator</code> won't listen for the event until the
* next time that the screen is shown.</p>
*
* @see #setFunctionForEvent()
* @see #clearEvent()
* @see #events
*/
public function setScreenIDForEvent(eventType:String, screenID:String):void
{
this._events[eventType] = screenID;
}
/**
* Cancels the action previously registered to be triggered when the
* screen dispatches an event.
*
* @see #events
*/
public function clearEvent(eventType:String):void
{
delete this._events[eventType];
}
/**
* @inheritDoc
*/
public function getScreen():DisplayObject
{
var screenInstance:DisplayObject;
if(this._screen is Class)
{
var ScreenType:Class = Class(this._screen);
screenInstance = new ScreenType();
}
else if(this._screen is Function)
{
screenInstance = DisplayObject((this._screen as Function)());
}
else
{
screenInstance = DisplayObject(this._screen);
}
if(!(screenInstance is DisplayObject))
{
throw new ArgumentError("ScreenNavigatorItem \"getScreen()\" must return a Starling display object.");
}
if(this._properties)
{
for(var propertyName:String in this._properties)
{
screenInstance[propertyName] = this._properties[propertyName];
}
}
return screenInstance;
}
}
} |
/**
* VERSION: 12.01
* DATE: 2012-07-28
* AS3
* UPDATES AND DOCS AT: http://www.greensock.com
**/
package com.greensock.plugins {
import com.greensock.*;
import com.greensock.core.*;
import flash.display.*;
import flash.geom.ColorTransform;
import flash.geom.Transform;
/**
* [AS3/AS2 only] To change a DisplayObject's tint/color, set this to the hex value of the tint you'd like
* to end up at (or begin at if you're using <code>TweenMax.from()</code>). An example hex value would be <code>0xFF0000</code>.
*
* <p>To remove a tint completely, set the tint to <code>null</code></p>
*
* <p><b>USAGE:</b></p>
* <listing version="3.0">
import com.greensock.TweenLite;
import com.greensock.plugins.TweenPlugin;
import com.greensock.plugins.TintPlugin;
TweenPlugin.activate([TintPlugin]); //activation is permanent in the SWF, so this line only needs to be run once.
TweenLite.to(mc, 1, {tint:0xFF0000});
</listing>
*
* <p><strong>Copyright 2008-2013, GreenSock. All rights reserved.</strong> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for <a href="http://www.greensock.com/club/">Club GreenSock</a> members, the software agreement that was issued with the membership.</p>
*
* @author Jack Doyle, jack@greensock.com
*/
public class TintPlugin extends TweenPlugin {
/** @private **/
public static const API:Number = 2; //If the API/Framework for plugins changes in the future, this number helps determine compatibility
/** @private **/
protected static var _props:Array = ["redMultiplier","greenMultiplier","blueMultiplier","alphaMultiplier","redOffset","greenOffset","blueOffset","alphaOffset"];
/** @private **/
protected var _transform:Transform;
/** @private **/
public function TintPlugin() {
super("tint,colorTransform,removeTint");
}
/** @private **/
override public function _onInitTween(target:Object, value:*, tween:TweenLite):Boolean {
if (!(target is DisplayObject)) {
return false;
}
var end:ColorTransform = new ColorTransform();
if (value != null && tween.vars.removeTint != true) {
end.color = uint(value);
}
_transform = DisplayObject(target).transform;
var ct:ColorTransform = _transform.colorTransform;
end.alphaMultiplier = ct.alphaMultiplier;
end.alphaOffset = ct.alphaOffset;
_init(ct, end);
return true;
}
/** @private **/
public function _init(start:ColorTransform, end:ColorTransform):void {
var i:int = _props.length,
p:String;
while (--i > -1) {
p = _props[i];
if (start[p] != end[p]) {
_addTween(start, p, start[p], end[p], "tint");
}
}
}
/** @private **/
override public function setRatio(v:Number):void {
var ct:ColorTransform = _transform.colorTransform, //don't just use _ct because if alpha changes are made separately, they won't get applied properly.
pt:PropTween = _firstPT;
while (pt) {
ct[pt.p] = pt.c * v + pt.s;
pt = pt._next;
}
_transform.colorTransform = ct;
}
}
} |
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import starling.display.DisplayObject;
import starling.display.Image;
import starling.textures.Texture;
/**
* Container for Movie and Image symbols created by the Flump exporter.
*/
public interface Library
{
/** @return the names of all Movie symbols in the Library */
function get movieSymbols () :Vector.<String>;
/** @return the names of all Image symbols in the Library */
function get imageSymbols () :Vector.<String>;
/** @return true if the symbols within the library have a namespace prefix due to being combined
* from multiple source FLAs. */
function get isNamespaced () :Boolean;
/**
* Creates a movie for the given symbol.
*
* @param symbolName the symbol name of the movie to be created
*
* @return a Movie instance for the symbol
*
* @throws Error if there is no such symbol in these resources, or if the symbol isn't a Movie.
*/
function createMovie (symbolName :String) :Movie;
/**
* Creates an image for the given symbol.
*
* @param symbolName the symbol name of the image to be created
*
* @return an Image instance for the symbol
*
* @throws Error if there is no such symbol in these resources, or if the symbol isn't an Image.
*/
function createImage (symbolName :String) :Image;
/**
* @return the Texture associated with the given Image symbol
*
* @throws Error if there is no such symbol in these resources, or if the symbol isn't an Image.
*/
function getImageTexture (symbolName :String) :Texture;
/** Creates an instance of the given Movie or Image symbol */
function createDisplayObject (symbolName :String) :DisplayObject;
/**
* Disposes of all GPU resources associated with this Library. It's an error to use a Library
* that's been disposed.
*/
function dispose () :void;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.