commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
ad1c55e6bcb8a8286f6378bf196f237b4a4f1e48
src/aerys/minko/scene/node/AbstractSceneNode.as
src/aerys/minko/scene/node/AbstractSceneNode.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.shader.part.phong.attenuation.MatrixShadowMapAttenuationShaderPart; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import flash.utils.setTimeout; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _transform : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _transformController : TransformController; private var _added : Signal; private var _removed : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; private var _visibilityChanged : Signal; private var _computedVisibilityChanged : Signal; private var _localToWorldChanged : Signal; final public function get x() : Number { return _transform.translationX; } final public function set x(value : Number) : void { _transform.translationX = value; } final public function get y() : Number { return _transform.translationX; } final public function set y(value : Number) : void { _transform.translationY = value; } final public function get z() : Number { return _transform.translationX; } final public function set z(value : Number) : void { _transform.translationZ = value; } final public function get rotationX() : Number { return _transform.rotationX; } final public function set rotationX(value : Number) : void { _transform.rotationX = value; } final public function get rotationY() : Number { return _transform.rotationY; } final public function set rotationY(value : Number) : void { _transform.rotationY = value; } final public function get rotationZ() : Number { return _transform.rotationZ; } final public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } final public function get scaleX() : Number { return _transform.scaleX; } final public function set scaleX(value : Number) : void { _transform.scaleX = value; } final public function get scaleY() : Number { return _transform.scaleY; } final public function set scaleY(value : Number) : void { _transform.scaleY = value; } final public function get scaleZ() : Number { return _transform.scaleZ; } final public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } final public function get parent() : Group { return _parent; } final public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice(oldParent.getChildIndex(this), 1); parent._numChildren--; _parent = null; _removed.execute(this, oldParent); oldParent.descendantRemoved.execute(oldParent, this); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _added.execute(this, _parent); _parent.descendantAdded.execute(_parent, this); } } final public function get scene() : Scene { return _root as Scene; } final public function get root() : ISceneNode { return _root; } final public function get transform() : Matrix4x4 { return _transform; } final public function get added() : Signal { return _added; } final public function get removed() : Signal { return _removed; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function get localToWorldTransformChanged() : Signal { return _localToWorldChanged; } public function AbstractSceneNode() { initialize(); } protected function initialize() : void { _name = getDefaultSceneName(this); _transform = new Matrix4x4(); _controllers = new <AbstractController>[]; _root = this; initializeSignals(); initializeSignalHandlers(); initializeContollers(); initializeDataProviders(); } protected function initializeSignals() : void { _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _visibilityChanged = new Signal('AbstractSceneNode.visibilityChanged'); _computedVisibilityChanged = new Signal('AbstractSceneNode.computedVisibilityChanged'); _localToWorldChanged = new Signal('AbstractSceneNode.localToWorldChanged'); } protected function initializeSignalHandlers() : void { _added.add(addedHandler); _removed.add(removedHandler); } protected function initializeContollers() : void { _transformController = new TransformController(); addController(_transformController); } protected function initializeDataProviders() : void { // nothing } private function addedHandler(child : ISceneNode, ancestor : Group) : void { _root = _parent ? _parent.root : this; } private function removedHandler(child : ISceneNode, ancestor : Group) : void { _root = _parent ? _parent.root : this; } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; var controllerId : int = _controllers.indexOf(controller); if (controllerId < 0) throw new Error('The controller is not on the node.'); _controllers[controllerId] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } minko_scene function getLocalToWorldTransformUnsafe(forceUpdate : Boolean = false) : Matrix4x4 { return _transformController.getLocalToWorldTransform(this, forceUpdate); } minko_scene function getWorldToLocalTransformUnsafe(forceUpdate : Boolean = false) : Matrix4x4 { return _transformController.getWorldToLocalTransform(this, forceUpdate); } public function getLocalToWorldTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { output ||= new Matrix4x4(); output.copyFrom(_transformController.getLocalToWorldTransform(this, forceUpdate)); return output; } public function getWorldToLocalTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { output ||= new Matrix4x4(); output.copyFrom(_transformController.getWorldToLocalTransform(this, forceUpdate)); return output; } public function localToWorld(inputVector : Vector4, outputVector : Vector4 = null, skipTranslation : Boolean = false, forceLocalToWorldTransformUpdate : Boolean = false) : Vector4 { var localToWorld : Matrix4x4 = getLocalToWorldTransformUnsafe( forceLocalToWorldTransformUpdate ); return skipTranslation ? localToWorld.deltaTransformVector(inputVector, outputVector) : localToWorld.transformVector(inputVector, outputVector); } public function worldToLocal(inputVector : Vector4, outputVector : Vector4 = null, skipTranslation : Boolean = false, forceWorldToLocalTransformUpdate : Boolean = false) : Vector4 { var worldToLocal : Matrix4x4 = getWorldToLocalTransformUnsafe( forceWorldToLocalTransformUpdate ); return skipTranslation ? worldToLocal.deltaTransformVector(inputVector, outputVector) : worldToLocal.transformVector(inputVector, outputVector); } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.shader.part.phong.attenuation.MatrixShadowMapAttenuationShaderPart; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import flash.utils.setTimeout; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _transform : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _transformController : TransformController; private var _added : Signal; private var _removed : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; private var _visibilityChanged : Signal; private var _computedVisibilityChanged : Signal; private var _localToWorldChanged : Signal; final public function get x() : Number { return _transform.translationX; } final public function set x(value : Number) : void { _transform.translationX = value; } final public function get y() : Number { return _transform.translationX; } final public function set y(value : Number) : void { _transform.translationY = value; } final public function get z() : Number { return _transform.translationX; } final public function set z(value : Number) : void { _transform.translationZ = value; } final public function get rotationX() : Number { return _transform.rotationX; } final public function set rotationX(value : Number) : void { _transform.rotationX = value; } final public function get rotationY() : Number { return _transform.rotationY; } final public function set rotationY(value : Number) : void { _transform.rotationY = value; } final public function get rotationZ() : Number { return _transform.rotationZ; } final public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } final public function get scaleX() : Number { return _transform.scaleX; } final public function set scaleX(value : Number) : void { _transform.scaleX = value; } final public function get scaleY() : Number { return _transform.scaleY; } final public function set scaleY(value : Number) : void { _transform.scaleY = value; } final public function get scaleZ() : Number { return _transform.scaleZ; } final public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } final public function get parent() : Group { return _parent; } final public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice(oldParent.getChildIndex(this), 1); parent._numChildren--; _parent = null; _removed.execute(this, oldParent); oldParent.descendantRemoved.execute(oldParent, this); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _added.execute(this, _parent); _parent.descendantAdded.execute(_parent, this); } } final public function get scene() : Scene { return _root as Scene; } final public function get root() : ISceneNode { return _root; } final public function get transform() : Matrix4x4 { return _transform; } final public function get added() : Signal { return _added; } final public function get removed() : Signal { return _removed; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function get localToWorldTransformChanged() : Signal { return _localToWorldChanged; } public function AbstractSceneNode() { initialize(); } protected function initialize() : void { _name = getDefaultSceneName(this); _transform = new Matrix4x4(); _controllers = new <AbstractController>[]; _root = this; initializeSignals(); initializeSignalHandlers(); initializeContollers(); initializeDataProviders(); } protected function initializeSignals() : void { _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _visibilityChanged = new Signal('AbstractSceneNode.visibilityChanged'); _computedVisibilityChanged = new Signal('AbstractSceneNode.computedVisibilityChanged'); _localToWorldChanged = new Signal('AbstractSceneNode.localToWorldChanged'); } protected function initializeSignalHandlers() : void { _added.add(addedHandler); _removed.add(removedHandler); } protected function initializeContollers() : void { _transformController = new TransformController(); addController(_transformController); } protected function initializeDataProviders() : void { // nothing } private function addedHandler(child : ISceneNode, ancestor : Group) : void { _root = _parent ? _parent.root : this; } private function removedHandler(child : ISceneNode, ancestor : Group) : void { _root = _parent ? _parent.root : this; } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; var controllerId : int = _controllers.indexOf(controller); if (controllerId < 0) throw new Error('The controller is not on the node.'); _controllers[controllerId] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } minko_scene function getLocalToWorldTransformUnsafe(forceUpdate : Boolean = false) : Matrix4x4 { var transformController : TransformController = _root ? (_root is AbstractSceneNode ? (_root as AbstractSceneNode)._transformController : _root.getControllersByType(TransformController)[0] as TransformController) : _transformController; return transformController.getLocalToWorldTransform(this, forceUpdate); } minko_scene function getWorldToLocalTransformUnsafe(forceUpdate : Boolean = false) : Matrix4x4 { var transformController : TransformController = _root ? (_root is AbstractSceneNode ? (_root as AbstractSceneNode)._transformController : _root.getControllersByType(TransformController)[0] as TransformController) : _transformController; return transformController.getWorldToLocalTransform(this, forceUpdate); } public function getLocalToWorldTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { var transformController : TransformController = _root ? (_root is AbstractSceneNode ? (_root as AbstractSceneNode)._transformController : _root.getControllersByType(TransformController)[0] as TransformController) : _transformController; output ||= new Matrix4x4(); output.copyFrom(transformController.getLocalToWorldTransform(this, forceUpdate)); return output; } public function getWorldToLocalTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { var transformController : TransformController = _root ? (_root is AbstractSceneNode ? (_root as AbstractSceneNode)._transformController : _root.getControllersByType(TransformController)[0] as TransformController) : _transformController; output ||= new Matrix4x4(); output.copyFrom(transformController.getWorldToLocalTransform(this, forceUpdate)); return output; } public function localToWorld(inputVector : Vector4, outputVector : Vector4 = null, skipTranslation : Boolean = false, forceLocalToWorldTransformUpdate : Boolean = false) : Vector4 { var localToWorld : Matrix4x4 = getLocalToWorldTransformUnsafe( forceLocalToWorldTransformUpdate ); return skipTranslation ? localToWorld.deltaTransformVector(inputVector, outputVector) : localToWorld.transformVector(inputVector, outputVector); } public function worldToLocal(inputVector : Vector4, outputVector : Vector4 = null, skipTranslation : Boolean = false, forceWorldToLocalTransformUpdate : Boolean = false) : Vector4 { var worldToLocal : Matrix4x4 = getWorldToLocalTransformUnsafe( forceWorldToLocalTransformUpdate ); return skipTranslation ? worldToLocal.deltaTransformVector(inputVector, outputVector) : worldToLocal.transformVector(inputVector, outputVector); } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
fix AbstractSceneNode transforms get* methods to get the TransformController as fast as possible
fix AbstractSceneNode transforms get* methods to get the TransformController as fast as possible
ActionScript
mit
aerys/minko-as3
a45614a5fcabed1501bf1dd8349f285b57158b31
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _changes : Object = {}; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (value) for (var bindingName : String in _changes) { setParameter(bindingName, _changes[bindingName]); delete _changes[bindingName]; } } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { // if (_bindings != null) // unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { _changes = {}; for (var parameter : String in _bindings) { if (meshBindings.hasCallback(parameter, parameterChangedHandler)) meshBindings.removeCallback(parameter, parameterChangedHandler); else if (sceneBindings.hasCallback(parameter, parameterChangedHandler)) sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { if (!_enabled) { _changes[name] = value; return ; } var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _changes : Object = {}; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (value) for (var bindingName : String in _changes) { setParameter(bindingName, _changes[bindingName]); delete _changes[bindingName]; } } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { // if (_bindings != null) // unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { _changes = {}; for (var parameter : String in _bindings) { if (meshBindings.hasCallback(parameter, parameterChangedHandler)) meshBindings.removeCallback(parameter, parameterChangedHandler); else if (sceneBindings.hasCallback(parameter, parameterChangedHandler)) sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); if (!sceneBindings.hasCallback(parameter, parameterChangedHandler)) sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { if (!_enabled) { _changes[name] = value; return ; } var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
fix DrawCall.setBindings() to avoid listening to the same scene binding twice
fix DrawCall.setBindings() to avoid listening to the same scene binding twice
ActionScript
mit
aerys/minko-as3
07a4b41d38e91ca28962993fee182c05bc192bd5
src/aerys/minko/scene/node/Mesh.as
src/aerys/minko/scene/node/Mesh.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.mesh.MeshController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.Ray; use namespace minko_scene; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractVisibleSceneNode implements ITaggable { public static const DEFAULT_MATERIAL : Material = new BasicMaterial(); private var _ctrl : MeshController; private var _properties : DataProvider; private var _material : Material; private var _bindings : DataBindings; private var _visibility : MeshVisibilityController; private var _cloned : Signal; private var _tag : uint = 1; /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : Material { return _material; } public function set material(value : Material) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); var oldMaterial : Material = _material; _material = value; if (value) _bindings.addProvider(value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _ctrl.geometry; } public function set geometry(value : Geometry) : void { _ctrl.geometry = value; } public function get tag() : uint { return _tag; } public function set tag(value : uint) : void { if (_tag != value) { _tag = value; _properties.setProperty('tag', value); } } /** * Whether the mesh in inside the camera frustum or not. * @return * */ public function get insideFrustum() : Boolean { return _visibility.insideFrustum; } override public function get computedVisibility() : Boolean { return scene ? super.computedVisibility && _visibility.computedVisibility : super.computedVisibility; } public function get frustumCulling() : uint { return _visibility.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibility.frustumCulling = value; } public function get cloned() : Signal { return _cloned; } public function get frame() : uint { return _ctrl.frame; } public function set frame(value : uint) : void { _ctrl.frame = value; } public function Mesh(geometry : Geometry = null, material : Material = null, name : String = null, tag : uint = 1) { super(); initializeMesh(geometry, material, name, tag); } override protected function initialize() : void { _bindings = new DataBindings(this); this.properties = new DataProvider( properties, 'meshProperties', DataProviderUsage.EXCLUSIVE ); super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _cloned = new Signal('Mesh.cloned'); } override protected function initializeContollers():void { super.initializeContollers(); _ctrl = new MeshController(); addController(_ctrl); _visibility = new MeshVisibilityController(); _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); } protected function initializeMesh(geometry : Geometry, material : Material, name : String, tag : uint) : void { if (name) this.name = name; this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; _tag = tag; } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY, tag : uint = 1) : Number { if (!(_tag & tag)) return -1; return _ctrl.geometry.boundingBox.testRay( ray, getWorldToLocalTransform(), maxDistance ); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Mesh = new Mesh(); clone.name = name; clone.geometry = _ctrl.geometry; clone.properties = DataProvider(_properties.clone()); clone._bindings.copySharedProvidersFrom(_bindings); clone.transform.copyFrom(transform); clone.material = _material; this.cloned.execute(this, clone); return clone; } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.material.Material; import aerys.minko.render.material.basic.BasicMaterial; import aerys.minko.scene.controller.mesh.MeshController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.enum.FrustumCulling; import aerys.minko.type.math.Ray; use namespace minko_scene; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractVisibleSceneNode implements ITaggable { public static const DEFAULT_MATERIAL : Material = new BasicMaterial(); private var _ctrl : MeshController; private var _properties : DataProvider; private var _material : Material; private var _bindings : DataBindings; private var _visibility : MeshVisibilityController; private var _cloned : Signal; private var _tag : uint = 1; /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : Material { return _material; } public function set material(value : Material) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); var oldMaterial : Material = _material; _material = value; if (value) _bindings.addProvider(value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _ctrl.geometry; } public function set geometry(value : Geometry) : void { _ctrl.geometry = value; } public function get tag() : uint { return _tag; } public function set tag(value : uint) : void { if (_tag != value) { _tag = value; _properties.setProperty('tag', value); } } /** * Whether the mesh in inside the camera frustum or not. * @return * */ public function get insideFrustum() : Boolean { return _visibility.insideFrustum; } override public function get computedVisibility() : Boolean { return scene ? super.computedVisibility && _visibility.computedVisibility : super.computedVisibility; } public function get frustumCulling() : uint { return _visibility.frustumCulling; } public function set frustumCulling(value : uint) : void { _visibility.frustumCulling = value; } public function get cloned() : Signal { return _cloned; } public function get frame() : uint { return _ctrl.frame; } public function set frame(value : uint) : void { _ctrl.frame = value; } public function Mesh(geometry : Geometry = null, material : Material = null, name : String = null, tag : uint = 1) { super(); initializeMesh(geometry, material, name, tag); } override protected function initialize() : void { _bindings = new DataBindings(this); this.properties = new DataProvider( properties, 'meshProperties', DataProviderUsage.EXCLUSIVE ); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _cloned = new Signal('Mesh.cloned'); } override protected function initializeContollers() : void { super.initializeContollers(); _ctrl = new MeshController(); addController(_ctrl); _visibility = new MeshVisibilityController(); _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); } protected function initializeMesh(geometry : Geometry, material : Material, name : String, tag : uint) : void { if (name) this.name = name; this.geometry = geometry; this.material = material || DEFAULT_MATERIAL; _tag = tag; } public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY, tag : uint = 1) : Number { if (!(_tag & tag)) return -1; return _ctrl.geometry.boundingBox.testRay( ray, getWorldToLocalTransform(), maxDistance ); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Mesh = new Mesh(); clone.name = name; clone.geometry = _ctrl.geometry; clone.properties = DataProvider(_properties.clone()); clone._bindings.copySharedProvidersFrom(_bindings); clone.transform.copyFrom(transform); clone.material = _material; this.cloned.execute(this, clone); return clone; } } }
fix coding style
fix coding style
ActionScript
mit
aerys/minko-as3
34775377fa3408c173a4cdc8fd525b7c5b3208e1
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2016 Esri. All Rights Reserved. // // 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.esri.builder.controllers.supportClasses { import com.esri.builder.model.CustomWidgetType; import com.esri.builder.model.WidgetType; import com.esri.builder.supportClasses.FileUtil; import com.esri.builder.supportClasses.LogUtil; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import modules.IBuilderModule; import modules.supportClasses.CustomXMLModule; import mx.core.FlexGlobals; import mx.events.ModuleEvent; import mx.logging.ILogger; import mx.logging.Log; import mx.modules.IModuleInfo; import mx.modules.ModuleManager; public class WidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader); internal static var loadedModuleInfos:Array = []; private var swf:File; private var config:File; //need reference when loading to avoid being garbage collected before load completes private var moduleInfo:IModuleInfo; //requires either swf or config public function WidgetTypeLoader(swf:File = null, config:File = null) { this.swf = swf; this.config = config; } public function get name():String { var fileName:String; if (swf && swf.exists) { fileName = FileUtil.getFileName(swf); } else if (config && config.exists) { fileName = FileUtil.getFileName(config); } return fileName; } public function load():void { if (swf && swf.exists) { loadModule(); } else if (config && config.exists) { loadConfigModule(); } else { dispatchError(); } } private function loadConfigModule():void { if (Log.isInfo()) { LOG.info('Loading XML module: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); if (moduleConfig) { var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig); if (customWidgetType) { dispatchComplete(customWidgetType); return; } } dispatchError(); } private function loadModule():void { if (Log.isInfo()) { LOG.info('Loading SWF module: {0}', swf.url); } moduleInfo = ModuleManager.getModule(swf.url); if (moduleInfo.ready) { if (Log.isInfo()) { LOG.info('Unloading module: {0}', swf.url); } moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); moduleInfo.release(); moduleInfo.unload(); } else { if (Log.isInfo()) { LOG.info('Loading module: {0}', swf.url); } var fileBytes:ByteArray = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(swf, FileMode.READ); fileStream.readBytes(fileBytes); fileStream.close(); //Use ModuleEvent.PROGRESS instead of ModuleEvent.READY to avoid the case where the latter is never dispatched. moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory); } } private function moduleInfo_progressHandler(event:ModuleEvent):void { if (event.bytesLoaded == event.bytesTotal) { var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); FlexGlobals.topLevelApplication.callLater(processModuleInfo, [ moduleInfo ]); } } private function moduleInfo_unloadHandler(event:ModuleEvent):void { if (Log.isInfo()) { LOG.info('Module unloaded: {0}', swf.url); } var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo); if (moduleInfoIndex > -1) { loadedModuleInfos.splice(moduleInfoIndex, 1); } this.moduleInfo = null; FlexGlobals.topLevelApplication.callLater(loadModule); } private function processModuleInfo(moduleInfo:IModuleInfo):void { if (Log.isInfo()) { LOG.info('Module loaded: {0}', swf.url); } if (config && config.exists) { if (Log.isInfo()) { LOG.info('Reading module config: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); } const builderModule:IBuilderModule = moduleInfo.factory.create() as IBuilderModule; if (builderModule) { if (Log.isInfo()) { LOG.info('Widget type created for module: {0}', swf.url); } var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig); } loadedModuleInfos.push(moduleInfo); this.moduleInfo = null; dispatchComplete(widgetType); } private function dispatchComplete(widgetType:WidgetType):void { if (Log.isInfo()) { LOG.info('Module load complete: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType)); } private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType { var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url; var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1); if (moduleConfig) { var configXML:XML = moduleConfig.configuration[0]; var version:String = moduleConfig.widgetversion[0]; } return isCustomModule ? new CustomWidgetType(builderModule, version, configXML) : new WidgetType(builderModule); } private function readModuleConfig(configFile:File):XML { var configXML:XML; var fileStream:FileStream = new FileStream(); try { fileStream.open(configFile, FileMode.READ); configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); } catch (e:Error) { //ignore if (Log.isInfo()) { LOG.info('Could not read module config: {0}', e.toString()); } } finally { fileStream.close(); } return configXML; } private function moduleInfo_errorHandler(event:ModuleEvent):void { var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); this.moduleInfo = null; dispatchError(); } private function dispatchError():void { if (Log.isInfo()) { LOG.info('Module load failed: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR)); } private function parseCustomWidgetType(configXML:XML):CustomWidgetType { if (Log.isInfo()) { LOG.info('Creating widget type from XML: {0}', configXML); } var customModule:CustomXMLModule = new CustomXMLModule(); customModule.widgetName = configXML.name; customModule.isOpenByDefault = (configXML.openbydefault == 'true'); var widgetLabel:String = configXML.label[0]; var widgetDescription:String = configXML.description[0]; var widgetHelpURL:String = configXML.helpurl[0]; var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>; var widgetVersion:String = configXML.widgetversion[0]; customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName); customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName; customModule.widgetDescription = widgetDescription ? widgetDescription : ""; customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : ""; return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration); } private function createWidgetIconPath(iconPath:String, widgetName:String):String { var widgetIconPath:String; if (iconPath) { widgetIconPath = "widgets/" + widgetName + "/" + iconPath; } else { widgetIconPath = "assets/images/i_widget.png"; } return widgetIconPath; } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2016 Esri. All Rights Reserved. // // 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.esri.builder.controllers.supportClasses { import com.esri.builder.model.CustomWidgetType; import com.esri.builder.model.WidgetType; import com.esri.builder.supportClasses.FileUtil; import com.esri.builder.supportClasses.LogUtil; import flash.events.EventDispatcher; import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import modules.IBuilderModule; import modules.supportClasses.CustomXMLModule; import mx.core.FlexGlobals; import mx.events.ModuleEvent; import mx.logging.ILogger; import mx.logging.Log; import mx.modules.IModuleInfo; import mx.modules.ModuleManager; public class WidgetTypeLoader extends EventDispatcher { private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader); internal static var loadedModuleInfos:Array = []; private var swf:File; private var config:File; //need reference when loading to avoid being garbage collected before load completes private var moduleInfo:IModuleInfo; //requires either swf or config public function WidgetTypeLoader(swf:File = null, config:File = null) { this.swf = swf; this.config = config; } public function get name():String { var fileName:String; if (swf && swf.exists) { fileName = FileUtil.getFileName(swf); } else if (config && config.exists) { fileName = FileUtil.getFileName(config); } return fileName; } public function load():void { if (swf && swf.exists) { loadModule(); } else if (config && config.exists) { loadConfigModule(); } else { dispatchError(); } } private function loadConfigModule():void { if (Log.isInfo()) { LOG.info('Loading XML module: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); if (moduleConfig) { var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig); if (customWidgetType) { dispatchComplete(customWidgetType); return; } } dispatchError(); } private function loadModule():void { if (Log.isInfo()) { LOG.info('Loading SWF module: {0}', swf.url); } moduleInfo = ModuleManager.getModule(swf.url); if (moduleInfo.ready) { if (Log.isInfo()) { LOG.info('Unloading module: {0}', swf.url); } moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); moduleInfo.release(); moduleInfo.unload(); } else { if (Log.isInfo()) { LOG.info('Loading module: {0}', swf.url); } var fileBytes:ByteArray = new ByteArray(); var fileStream:FileStream = new FileStream(); fileStream.open(swf, FileMode.READ); fileStream.readBytes(fileBytes); fileStream.close(); //Use ModuleEvent.PROGRESS instead of ModuleEvent.READY to avoid the case where the latter is never dispatched. moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory); } } private function moduleInfo_progressHandler(event:ModuleEvent):void { if (event.bytesLoaded == event.bytesTotal) { var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo; moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); FlexGlobals.topLevelApplication.callLater(processModuleInfo, [ moduleInfo ]); } } private function moduleInfo_unloadHandler(event:ModuleEvent):void { if (Log.isInfo()) { LOG.info('Module unloaded: {0}', swf.url); } var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler); var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo); if (moduleInfoIndex > -1) { loadedModuleInfos.splice(moduleInfoIndex, 1); } this.moduleInfo = null; FlexGlobals.topLevelApplication.callLater(loadModule); } private function processModuleInfo(moduleInfo:IModuleInfo):void { if (Log.isInfo()) { LOG.info('Module loaded: {0}', swf.url); } if (config && config.exists) { if (Log.isInfo()) { LOG.info('Reading module config: {0}', config.url); } var moduleConfig:XML = readModuleConfig(config); } const builderModule:IBuilderModule = moduleInfo.factory.create() as IBuilderModule; if (builderModule) { if (Log.isInfo()) { LOG.info('Widget type created for module: {0}', swf.url); } var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig); } loadedModuleInfos.push(moduleInfo); this.moduleInfo = null; dispatchComplete(widgetType); } private function dispatchComplete(widgetType:WidgetType):void { if (Log.isInfo()) { LOG.info('Module load complete: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType)); } private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType { var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url; var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1); if (moduleConfig) { var configXML:XML = moduleConfig.configuration[0]; var version:String = moduleConfig.widgetversion[0]; } return isCustomModule ? new CustomWidgetType(builderModule, version, configXML) : new WidgetType(builderModule); } private function readModuleConfig(configFile:File):XML { var configXML:XML; var fileStream:FileStream = new FileStream(); try { fileStream.open(configFile, FileMode.READ); configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable)); } catch (e:Error) { //ignore if (Log.isInfo()) { LOG.info('Could not read module config: {0}', e.toString()); } } finally { fileStream.close(); } return configXML; } private function moduleInfo_errorHandler(event:ModuleEvent):void { var moduleInfo:IModuleInfo = event.module; moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler); moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler); this.moduleInfo = null; dispatchError(); } private function dispatchError():void { if (Log.isInfo()) { LOG.info('Module load failed: {0}', name); } dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR)); } private function parseCustomWidgetType(configXML:XML):CustomWidgetType { if (Log.isInfo()) { LOG.info('Creating widget type from XML: {0}', configXML); } var customModule:CustomXMLModule = new CustomXMLModule(); customModule.widgetName = configXML.name; customModule.isOpenByDefault = (configXML.openbydefault == 'true'); var widgetLabel:String = configXML.label[0]; var widgetDescription:String = configXML.description[0]; var widgetHelpURL:String = configXML.helpurl[0]; var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>; var widgetVersion:String = configXML.widgetversion[0]; customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName); customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName; customModule.widgetDescription = widgetDescription ? widgetDescription : ""; customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : ""; return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration); } private function createWidgetIconPath(iconPath:String, widgetName:String):String { var widgetIconPath:String; if (iconPath) { widgetIconPath = "widgets/" + widgetName + "/" + iconPath; } else { widgetIconPath = "assets/images/i_widget.png"; } return widgetIconPath; } } }
Remove extra newline.
Remove extra newline.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
eb92af6710fbe5782123335c9cb0a524176d1905
frameworks/projects/Core/as/src/org/apache/flex/events/MouseEvent.as
frameworks/projects/Core/as/src/org/apache/flex/events/MouseEvent.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.events { COMPILE::AS3 { import flash.events.MouseEvent; } import org.apache.flex.core.IUIBase; import org.apache.flex.geom.Point; import org.apache.flex.utils.PointUtils; /** * Mouse events * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class MouseEvent extends Event { public static const MOUSE_DOWN:String = "mouseDown"; public static const MOUSE_MOVE:String = "mouseMove"; public static const MOUSE_UP:String = "mouseUp"; public static const MOUSE_OUT:String = "mouseOut"; public static const MOUSE_OVER:String = "mouseOver"; public static const ROLL_OVER:String = "rollOver"; public static const ROLL_OUT:String = "rollOut"; public static const CLICK:String = "click"; /** * Constructor. * * @param type The name of the event. * @param bubbles Whether the event bubbles. * @param cancelable Whether the event can be canceled. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function MouseEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, localX:Number = NaN, localY:Number = NaN, relatedObject:Object = null, ctrlKey:Boolean = false, altKey:Boolean = false, shiftKey:Boolean = false, buttonDown:Boolean = false, delta:int = 0, commandKey:Boolean = false, controlKey:Boolean = false, clickCount:int = 0) { COMPILE::AS3 { super(type, bubbles, cancelable); } COMPILE::JS { super(type); } this.localX = localX; this.localY = localY; this.relatedObject = relatedObject; this.ctrlKey = ctrlKey; this.altKey = altKey; this.shiftKey = shiftKey; this.buttonDown = buttonDown; this.delta = delta; this.commandKey = commandKey; this.controlKey = controlKey; this.clickCount = clickCount; } private var _localX:Number; public function get localX():Number { return _localX; } public function set localX(value:Number):void { _localX = value; _stagePoint = null; } private var _localY:Number; public function get localY():Number { return _localY; } public function set localY(value:Number):void { _localY = value; _stagePoint = null; } public var relatedObject:Object; public var ctrlKey:Boolean; public var altKey:Boolean; public var shiftKey:Boolean; public var buttonDown:Boolean; public var delta:int; public var commandKey:Boolean; public var controlKey:Boolean; public var clickCount:int; // these map directly to JS MouseEvent fields. public function get clientX():Number { return screenX; } public function set clientX(value:Number):void { localX = value; } public function get clientY():Number { return screenY; } public function set clientY(value:Number):void { localY = value; } private var _stagePoint:Point; public function get screenX():Number { if (!target) return localX; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.x; } public function get screenY():Number { if (!target) return localY; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.y; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.events { COMPILE::AS3 { import flash.events.MouseEvent; } COMPILE::JS { import window.MouseEvent; } import org.apache.flex.core.IUIBase; import org.apache.flex.geom.Point; import org.apache.flex.utils.PointUtils; /** * Mouse events * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class MouseEvent extends Event { private static function platformConstant(s:String):String { COMPILE::AS3 { return s; } COMPILE::JS { return s.toLowerCase(); } } public static const MOUSE_DOWN:String = platformConstant("mouseDown"); public static const MOUSE_MOVE:String = platformConstant("mouseMove"); public static const MOUSE_UP:String = platformConstant("mouseUp"); public static const MOUSE_OUT:String = platformConstant("mouseOut"); public static const MOUSE_OVER:String = platformConstant("mouseOver"); public static const ROLL_OVER:String = platformConstant("rollOver"); public static const ROLL_OUT:String = platformConstant("rollOut"); public static const CLICK:String = "click"; /** * Constructor. * * @param type The name of the event. * @param bubbles Whether the event bubbles. * @param cancelable Whether the event can be canceled. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function MouseEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false, localX:Number = NaN, localY:Number = NaN, relatedObject:Object = null, ctrlKey:Boolean = false, altKey:Boolean = false, shiftKey:Boolean = false, buttonDown:Boolean = false, delta:int = 0, commandKey:Boolean = false, controlKey:Boolean = false, clickCount:int = 0) { COMPILE::AS3 { super(type, bubbles, cancelable); } COMPILE::JS { super(type); } this.localX = localX; this.localY = localY; this.relatedObject = relatedObject; this.ctrlKey = ctrlKey; this.altKey = altKey; this.shiftKey = shiftKey; this.buttonDown = buttonDown; this.delta = delta; this.commandKey = commandKey; this.controlKey = controlKey; this.clickCount = clickCount; } private var _localX:Number; public function get localX():Number { return _localX; } public function set localX(value:Number):void { _localX = value; _stagePoint = null; } private var _localY:Number; public function get localY():Number { return _localY; } public function set localY(value:Number):void { _localY = value; _stagePoint = null; } public var relatedObject:Object; public var ctrlKey:Boolean; public var altKey:Boolean; public var shiftKey:Boolean; public var buttonDown:Boolean; public var delta:int; public var commandKey:Boolean; public var controlKey:Boolean; public var clickCount:int; // these map directly to JS MouseEvent fields. public function get clientX():Number { return screenX; } public function set clientX(value:Number):void { localX = value; } public function get clientY():Number { return screenY; } public function set clientY(value:Number):void { localY = value; } private var _stagePoint:Point; public function get screenX():Number { if (!target) return localX; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.x; } public function get screenY():Number { if (!target) return localY; if (!_stagePoint) { var localPoint:Point = new Point(localX, localY); _stagePoint = PointUtils.localToGlobal(localPoint, target); } return _stagePoint.y; } /** * @private */ COMPILE::JS private static function installRollOverMixin():Boolean { window.addEventListener(MOUSE_OVER, mouseOverHandler, false); return true; } /** * @param e The event. * RollOver/RollOut is entirely implemented in mouseOver because * when a parent and child share an edge, you only get a mouseout * for the child and not the parent and you need to send rollout * to both. A similar issue exists for rollover. */ COMPILE::JS private static function mouseOverHandler(e:MouseEvent):void { var j:int; var m:int; var outs:Array; var me:window.MouseEvent; var parent:Object; var target:Object = e.target.flexjs_wrapper; if (target == null) return; // probably over the html tag var targets:Array = MouseEvent.targets; var index:int = targets.indexOf(target); if (index != -1) { // get all children outs = targets.slice(index + 1); m = outs.length; for (j = 0; j < m; j++) { me = makeMouseEvent( ROLL_OUT, e); outs[j].element.dispatchEvent(me); } MouseEvent.targets = targets.slice(0, index + 1); } else { var newTargets:Array = [target]; if (!('parent' in target)) parent = null; else parent = target.parent; while (parent) { index = targets.indexOf(parent); if (index == -1) { newTargets.unshift(parent); if (!('parent' in parent)) break; parent = parent.parent; } else { outs = targets.slice(index + 1); m = outs.length; for (j = 0; j < m; j++) { me = makeMouseEvent( ROLL_OUT, e); outs[j].element.dispatchEvent(me); } targets = targets.slice(0, index + 1); break; } } var n:int = newTargets.length; for (var i:int = 0; i < n; i++) { me = makeMouseEvent( ROLL_OVER, e); newTargets[i].element.dispatchEvent(me); } MouseEvent.targets = targets.concat(newTargets); } } /** */ COMPILE::JS private static var rollOverMixin:Boolean = installRollOverMixin(); /** */ COMPILE::JS private static var targets:Array = []; /** * @param {string} type The event type. * @param {Event} e The mouse event. * @return {MouseEvent} The new event. */ COMPILE::JS private static function makeMouseEvent(type:String, e:window.MouseEvent):window.MouseEvent { var out:window.MouseEvent = new window.MouseEvent(type); out.initMouseEvent(type, false, false, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget); return out; }; } }
fix rollovers and other mouseevents
fix rollovers and other mouseevents
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
6709805e5b77d5ab6d30ecf417ad4a7dd5189ead
Arguments/src/classes/Language.as
Arguments/src/classes/Language.as
package classes { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.ByteArray; import mx.controls.Alert; import org.osmf.layout.AbsoluteLayoutFacet; public class Language { //I will set the language to either GERMAN, RUSSIAN or ENGLISH //based on this, you could read the values into the variables //by default, the language is EN-US public static const GERMAN:String = "GER"; public static const ENGLISH:String = "EN-US"; public static const RUSSIAN:String = "RUS"; public static var language:String = ENGLISH; public static var xml:XML; private static var ready:Boolean=false; public static function init():void { [Embed(source="translation.xml", mimeType="application/octet-stream")] const MyData:Class; var byteArray:ByteArray = new MyData() as ByteArray; var x:XML = new XML(byteArray.readUTFBytes(byteArray.length)); xml = x; ready=true; } /**The key function. Use this to look up a label from the translation document according to the set language.*/ public static function lookup(label:String):String{ if(!ready){ init(); } trace("Now looking up:" + label); var lbl:XMLList = xml.descendants(label); var lang:XMLList = lbl.descendants(language); var output:String = lang.attribute("text"); trace("Output is: " + output); return output; } } }
package classes { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.ByteArray; import mx.controls.Alert; import org.osmf.layout.AbsoluteLayoutFacet; public class Language { //I will set the language to either GERMAN, RUSSIAN or ENGLISH //based on this, you could read the values into the variables //by default, the language is EN-US public static const GERMAN:String = "GER"; public static const ENGLISH:String = "EN-US"; public static const RUSSIAN:String = "RUS"; public static var language:String = ENGLISH; public static var xml:XML; private static var ready:Boolean=false; public static function init():void { [Embed(source="../../../translation.xml", mimeType="application/octet-stream")] const MyData:Class; var byteArray:ByteArray = new MyData() as ByteArray; var x:XML = new XML(byteArray.readUTFBytes(byteArray.length)); xml = x; ready=true; } /**The key function. Use this to look up a label from the translation document according to the set language.*/ public static function lookup(label:String):String{ if(!ready){ init(); } trace("Now looking up:" + label); var lbl:XMLList = xml.descendants(label); var lang:XMLList = lbl.descendants(language); var output:String = lang.attribute("text"); trace("Output is: " + output); return output; } } }
Fix the transcoding issue. Apparently it was partially cached on the other computer and was erroring on a fresh build.
Fix the transcoding issue. Apparently it was partially cached on the other computer and was erroring on a fresh build.
ActionScript
agpl-3.0
MichaelHoffmann/AGORA,mbjornas3/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
df49a8a5122778f0c8d9e40250bafe68d4d09d58
src/PlayState.as
src/PlayState.as
package { import flash.display.BlendMode; import org.flixel.*; // The main coordinator: part config list, part asset list. // Handles all of the character animations. // TODO, offload animation logic to PlayerDelegate interface. public class PlayState extends FlxState { // Tileset that works with AUTO mode (best for thin walls) [Embed(source='data/auto_tiles.png')]private static var auto_tiles:Class; // Tileset that works with OFF mode (do what you want mode) [Embed(source='data/empty_tiles.png')]private static var empty_tiles:Class; [Embed(source='data/player.png')]private static var player_img:Class; [Embed(source='data/bg-1.png')]private static var bg1_img:Class; [Embed(source='data/bg-2.png')]private static var bg2_img:Class; [Embed(source='data/bg-3.png')]private static var bg3_img:Class; [Embed(source='data/bg-4.png')]private static var bg4_img:Class; [Embed(source='data/bg-5.png')]private static var bg5_img:Class; [Embed(source='data/bg-6.png')]private static var bg6_img:Class; [Embed(source='data/bg-7.png')]private static var bg7_img:Class; [Embed(source='data/bg-8.png')]private static var bg8_img:Class; [Embed(source='data/bg-9.png')]private static var bg9_img:Class; [Embed(source='data/bg-10.png')]private static var bg10_img:Class; [Embed(source='data/bg-11.png')]private static var bg11_img:Class; [Embed(source='data/bg-12.png')]private static var bg12_img:Class; // The dynamically generated and extended FlxTilemap. private var platform:Platform; // Ledge controls, in tiles. // The extend FlxSprite. private const PLAYER_WIDTH:uint = 72; private const PLAYER_HEIGHT:uint = 72; private var player:Player; // The background with parallax. private var bg:Background; // Some game switches. private var fallChecking:Boolean; // Flixel Methods // -------------- override public function create():void { // Globals. FlxG.framerate = 30; FlxG.flashFramerate = 30; fallChecking = false; // Start our setup chain. setupPlatform(); // For now, we add things in order to get correct layering. // TODO - offload to draw method? add(bg); add(platform); add(player); } override public function update():void { // Start our update chain. updatePlatform(); super.update(); } override public function draw():void { super.draw(); } // Setup Routines // -------------- // Since the observer pattern is too slow, we'll just name our functions to be like hooks. // The platform is the first thing that gets set up. private function setupPlatform():void { // Load our scenery. bg = new Background(); bg.bounds.x = 0; bg.bounds.y = 0; bg.parallax_factor = 1; // Our bg is part "foreground". bg.parallax_buffer = 1.7; bg.addImage(bg12_img); bg.addImage(bg11_img); bg.addImage(bg10_img); bg.addImage(bg9_img); bg.addImage(bg8_img); bg.addImage(bg7_img); bg.addImage(bg6_img); bg.addImage(bg5_img); bg.addImage(bg4_img); bg.addImage(bg3_img); bg.addImage(bg2_img); bg.addImage(bg1_img); bg.layout(); // Creates a new tilemap with no arguments. platform = new Platform(); // Customize our tile generation. platform.tileWidth = 32; platform.tileHeight = 32; platform.minLedgeSize = 3; platform.maxLedgeSize = 6; platform.minLedgeSpacing = new FlxPoint(4, 2); platform.maxLedgeSpacing = new FlxPoint(8, 4); platform.ledgeThickness = 2; // Set the bounds based on the background. // TODO - Account for parallax. platform.bounds = new FlxRect(bg.bounds.x, bg.bounds.y, bg.bounds.width, bg.bounds.height); // Make our platform. platform.makeMap(auto_tiles); setupPlatformAfter(); } // Hooks. private function setupPlatformAfter():void { // Draw player at the bottom. var start:FlxPoint = new FlxPoint(); var floorHeight:Number = PLAYER_HEIGHT; start.x = (FlxG.width - PLAYER_HEIGHT) / 2; start.y = platform.height - (PLAYER_HEIGHT + floorHeight); // start.x = 0; // start.y = 0; setupPlayer(start); // Move until we don't overlap. while (platform.overlaps(player)) { if (player.x <= 0) { player.x = FlxG.width; } player.x -= platform.tileWidth; } setupPlatformAndPlayerAfter(); } private function setupPlatformAndPlayerAfter():void { setupCamera(); } // Hooked routines. private function setupPlayer(start:FlxPoint):void { // Find start position for player. player = new Player(start.x, start.y); player.loadGraphic(player_img, true, true, 72); // Bounding box tweaks. player.height = player.frameWidth / 2; player.offset.y = player.frameWidth - player.height; player.tailOffset.x = 35; player.headOffset.x = 10; player.width = player.frameWidth - player.tailOffset.x; player.face(FlxObject.RIGHT); // Basic player physics. player.drag.x = 1000; // friction player.acceleration.y = 500; // gravity player.maxVelocity.x = 200; player.maxVelocity.y = 1500; // Player jump physics. player.jumpVelocity.y = -420; // Animations. // Make sure to add end transitions, otherwise the last frame is skipped if framerate is low. player.addAnimation('still',[17], 12); player.addAnimation('idle', [], 12, false); player.addAnimation('run', [0,1,2,3,4,5,6,7,8,9,10,11], 24); player.addAnimation('stop', [12,13,14,15,16,17], 24, false); player.addAnimation('start',[17,16,15,14,13,12], 24, false); player.addAnimation('jump', [18,19,20,21,22,23,24,25,26,27,28,29,30,31], 24, false); player.addAnimation('fall', [31]); player.addAnimation('land', [32,33,18,17], 12, false); } private function setupCamera():void { FlxG.camera.follow(player); platform.follow(); } // Update Routines // --------------- private function updatePlatform():void { updatePlatformAfter(); } // Hooks. private function updatePlatformAfter():void { // Tilemaps can be collided just like any other FlxObject, and flixel // automatically collides each individual tile with the object. FlxG.collide(player, platform); wrapToStage(player); updatePlayer(); updatePlatformAndPlayerAfter(); } private function updatePlatformAndPlayerAfter():void { updateCamera(player.justFell()); } // Hooked routines. private function updatePlayer():void { player.moveWithInput(); if (player.willJump) // We only need to play the jump animation once. { player.play('jump'); } else if (player.justFell()) { player.play('land'); } else if (!player.rising && player.finished) { if (player.falling) { player.play('fall'); } else if (player.willStop) { player.play('stop'); } else if (player.velocity.x == 0 || (player.x == 0 || player.x >= (platform.width - player.width)) ) { player.play('still'); } else if (player.willStart) { player.play('start'); player.willStart = false; // TODO - Hack. } else { player.play('run'); } } } private function updateCamera(playerJustFell:Boolean):void { if (fallChecking && playerJustFell) { FlxG.camera.shake( 0.01, 0.1, null, true, FlxCamera.SHAKE_VERTICAL_ONLY ); } } // Helpers // ------- private function wrapToStage(obj:FlxSprite):void { obj.x = FlxU.bound(obj.x, 0, (platform.width - obj.width)); obj.y = FlxU.bound(obj.y, 0, (platform.height - obj.height)); } } }
package { import flash.display.BlendMode; import org.flixel.*; // The main coordinator: part config list, part asset list. // Handles all of the character animations. // TODO, offload animation logic to PlayerDelegate interface. public class PlayState extends FlxState { // Tileset that works with AUTO mode (best for thin walls) [Embed(source='data/auto_tiles.png')]private static var auto_tiles:Class; // Tileset that works with OFF mode (do what you want mode) [Embed(source='data/empty_tiles.png')]private static var empty_tiles:Class; [Embed(source='data/player.png')]private static var player_img:Class; [Embed(source='data/bg-1.png')]private static var bg1_img:Class; [Embed(source='data/bg-2.png')]private static var bg2_img:Class; [Embed(source='data/bg-3.png')]private static var bg3_img:Class; [Embed(source='data/bg-4.png')]private static var bg4_img:Class; [Embed(source='data/bg-5.png')]private static var bg5_img:Class; [Embed(source='data/bg-6.png')]private static var bg6_img:Class; [Embed(source='data/bg-7.png')]private static var bg7_img:Class; [Embed(source='data/bg-8.png')]private static var bg8_img:Class; [Embed(source='data/bg-9.png')]private static var bg9_img:Class; [Embed(source='data/bg-10.png')]private static var bg10_img:Class; [Embed(source='data/bg-11.png')]private static var bg11_img:Class; [Embed(source='data/bg-12.png')]private static var bg12_img:Class; // The dynamically generated and extended FlxTilemap. private var platform:Platform; // Ledge controls, in tiles. // The extend FlxSprite. private const PLAYER_WIDTH:uint = 72; private const PLAYER_HEIGHT:uint = 72; private var player:Player; // The background with parallax. private var bg:Background; // Some game switches. private var fallChecking:Boolean; // Flixel Methods // -------------- override public function create():void { FlxG.mouse.hide(); // Globals. FlxG.framerate = 30; FlxG.flashFramerate = 30; fallChecking = false; // Start our setup chain. setupPlatform(); // For now, we add things in order to get correct layering. // TODO - offload to draw method? add(bg); add(platform); add(player); } override public function update():void { // Start our update chain. updatePlatform(); super.update(); } override public function draw():void { super.draw(); } // Setup Routines // -------------- // Since the observer pattern is too slow, we'll just name our functions to be like hooks. // The platform is the first thing that gets set up. private function setupPlatform():void { // Load our scenery. bg = new Background(); bg.bounds.x = 0; bg.bounds.y = 0; bg.parallax_factor = 1; // Our bg is part "foreground". bg.parallax_buffer = 1.7; bg.addImage(bg12_img); bg.addImage(bg11_img); bg.addImage(bg10_img); bg.addImage(bg9_img); bg.addImage(bg8_img); bg.addImage(bg7_img); bg.addImage(bg6_img); bg.addImage(bg5_img); bg.addImage(bg4_img); bg.addImage(bg3_img); bg.addImage(bg2_img); bg.addImage(bg1_img); bg.layout(); // Creates a new tilemap with no arguments. platform = new Platform(); // Customize our tile generation. platform.tileWidth = 32; platform.tileHeight = 32; platform.minLedgeSize = 3; platform.maxLedgeSize = 6; platform.minLedgeSpacing = new FlxPoint(4, 2); platform.maxLedgeSpacing = new FlxPoint(8, 4); platform.ledgeThickness = 2; // Set the bounds based on the background. // TODO - Account for parallax. platform.bounds = new FlxRect(bg.bounds.x, bg.bounds.y, bg.bounds.width, bg.bounds.height); // Make our platform. platform.makeMap(auto_tiles); setupPlatformAfter(); } // Hooks. private function setupPlatformAfter():void { // Draw player at the bottom. var start:FlxPoint = new FlxPoint(); var floorHeight:Number = PLAYER_HEIGHT; start.x = (FlxG.width - PLAYER_HEIGHT) / 2; start.y = platform.height - (PLAYER_HEIGHT + floorHeight); // start.x = 0; // start.y = 0; setupPlayer(start); // Move until we don't overlap. while (platform.overlaps(player)) { if (player.x <= 0) { player.x = FlxG.width; } player.x -= platform.tileWidth; } setupPlatformAndPlayerAfter(); } private function setupPlatformAndPlayerAfter():void { setupCamera(); } // Hooked routines. private function setupPlayer(start:FlxPoint):void { // Find start position for player. player = new Player(start.x, start.y); player.loadGraphic(player_img, true, true, 72); // Bounding box tweaks. player.height = player.frameWidth / 2; player.offset.y = player.frameWidth - player.height; player.tailOffset.x = 35; player.headOffset.x = 10; player.width = player.frameWidth - player.tailOffset.x; player.face(FlxObject.RIGHT); // Basic player physics. player.drag.x = 1000; // friction player.acceleration.y = 500; // gravity player.maxVelocity.x = 200; player.maxVelocity.y = 1500; // Player jump physics. player.jumpVelocity.y = -420; // Animations. // Make sure to add end transitions, otherwise the last frame is skipped if framerate is low. player.addAnimation('still',[17], 12); player.addAnimation('idle', [], 12, false); player.addAnimation('run', [0,1,2,3,4,5,6,7,8,9,10,11], 24); player.addAnimation('stop', [12,13,14,15,16,17], 24, false); player.addAnimation('start',[17,16,15,14,13,12], 24, false); player.addAnimation('jump', [18,19,20,21,22,23,24,25,26,27,28,29,30,31], 24, false); player.addAnimation('fall', [31]); player.addAnimation('land', [32,33,18,17], 12, false); } private function setupCamera():void { FlxG.camera.follow(player); platform.follow(); } // Update Routines // --------------- private function updatePlatform():void { updatePlatformAfter(); } // Hooks. private function updatePlatformAfter():void { // Tilemaps can be collided just like any other FlxObject, and flixel // automatically collides each individual tile with the object. FlxG.collide(player, platform); wrapToStage(player); updatePlayer(); updatePlatformAndPlayerAfter(); } private function updatePlatformAndPlayerAfter():void { updateCamera(player.justFell()); } // Hooked routines. private function updatePlayer():void { player.moveWithInput(); if (player.willJump) // We only need to play the jump animation once. { player.play('jump'); } else if (player.justFell()) { player.play('land'); } else if (!player.rising && player.finished) { if (player.falling) { player.play('fall'); } else if (player.willStop) { player.play('stop'); } else if (player.velocity.x == 0 || (player.x == 0 || player.x >= (platform.width - player.width)) ) { player.play('still'); } else if (player.willStart) { player.play('start'); player.willStart = false; // TODO - Hack. } else { player.play('run'); } } } private function updateCamera(playerJustFell:Boolean):void { if (fallChecking && playerJustFell) { FlxG.camera.shake( 0.01, 0.1, null, true, FlxCamera.SHAKE_VERTICAL_ONLY ); } } // Helpers // ------- private function wrapToStage(obj:FlxSprite):void { obj.x = FlxU.bound(obj.x, 0, (platform.width - obj.width)); obj.y = FlxU.bound(obj.y, 0, (platform.height - obj.height)); } } }
Hide cursor on play state.
Hide cursor on play state.
ActionScript
artistic-2.0
hlfcoding/morning-stroll
4bd8bc201e4c170237bf46766970d3cb163c4ea2
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSNetLoader.as
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSNetLoader.as
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSDVRTimeTrait; import com.kaltura.hls.HLSDVRTrait; import com.kaltura.hls.HLSMetadataNamespaces; import flash.net.NetConnection; import flash.net.NetStream; import flash.events.NetStatusEvent; import org.osmf.events.DVRStreamInfoEvent; import org.osmf.media.MediaResourceBase; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.metadata.MetadataNamespaces; import org.osmf.net.NetStreamLoadTrait; import org.osmf.net.NetStreamCodes; import org.osmf.net.httpstreaming.HLSHTTPNetStream; import org.osmf.net.httpstreaming.HTTPStreamingFactory; import org.osmf.net.httpstreaming.HTTPStreamingNetLoader; import org.osmf.net.httpstreaming.dvr.DVRInfo; import org.osmf.traits.LoadState; import org.osmf.net.NetStreamSwitchManagerBase import org.osmf.net.metrics.BandwidthMetric; import org.osmf.net.DynamicStreamingResource; import org.osmf.net.httpstreaming.DefaultHTTPStreamingSwitchManager; import org.osmf.net.metrics.MetricType; import org.osmf.net.rules.BandwidthRule; /** * Factory to identify and process MPEG2 TS via OSMF. */ public class M2TSNetLoader extends HTTPStreamingNetLoader { private var netStream:HLSHTTPNetStream; override public function canHandleResource( resource:MediaResourceBase ):Boolean { var metadata:Object = resource.getMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA ); if ( metadata != null && metadata == true ) return true; return false; } override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream { var factory:HTTPStreamingFactory = new M2TSStreamingFactory(); var httpNetStream:HLSHTTPNetStream = new HLSHTTPNetStream(connection, factory, resource); return httpNetStream; } override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource):NetStreamSwitchManagerBase { var switcher:DefaultHTTPStreamingSwitchManager = super.createNetStreamSwitchManager(connection, netStream, dsResource) as DefaultHTTPStreamingSwitchManager; // Since our segments are large, switch rapidly. // First, try to bias the bandwidth metric itself. var weights:Vector.<Number> = new Vector.<Number>; weights.push(1.0); weights.push(0.0); weights.push(0.0); var bw:BandwidthMetric = switcher.metricRepository.getMetric(MetricType.BANDWIDTH, weights) as BandwidthMetric; trace("Tried to override BandwidthMetric to N=1, and N=" + bw.weights.length); // Second, bias the bandwidthrule. for(var i:int=0; i<switcher.normalRules.length; i++) { var bwr:BandwidthRule = switcher.normalRules[i] as BandwidthRule; if(!bwr) continue; bwr.weights.length = 3; bwr.weights[0] = 1.0; bwr.weights[1] = 0.0; bwr.weights[2] = 0.0; trace("Adjusted BandwidthRule"); } return switcher; } override protected function processFinishLoading(loadTrait:NetStreamLoadTrait):void { // Set up DVR state updating. var resource:URLResource = loadTrait.resource as URLResource; if (!dvrMetadataPresent(resource)) { updateLoadTrait(loadTrait, LoadState.READY); return; } netStream = loadTrait.netStream as HLSHTTPNetStream; netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); netStream.DVRGetStreamInfo(null); function onDVRStreamInfo(event:DVRStreamInfoEvent):void { netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); loadTrait.setTrait(new HLSDVRTrait(loadTrait.connection, netStream, event.info as DVRInfo)); loadTrait.setTrait(new HLSDVRTimeTrait(loadTrait.connection, netStream, event.info as DVRInfo)); updateLoadTrait(loadTrait, LoadState.READY); } } private function dvrMetadataPresent(resource:URLResource):Boolean { var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata; return (metadata != null); } } }
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSDVRTimeTrait; import com.kaltura.hls.HLSDVRTrait; import com.kaltura.hls.HLSMetadataNamespaces; import flash.net.NetConnection; import flash.net.NetStream; import flash.events.NetStatusEvent; import org.osmf.events.DVRStreamInfoEvent; import org.osmf.media.MediaResourceBase; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.metadata.MetadataNamespaces; import org.osmf.net.NetStreamLoadTrait; import org.osmf.net.NetStreamCodes; import org.osmf.net.httpstreaming.HLSHTTPNetStream; import org.osmf.net.httpstreaming.HTTPStreamingFactory; import org.osmf.net.httpstreaming.HTTPStreamingNetLoader; import org.osmf.net.httpstreaming.dvr.DVRInfo; import org.osmf.traits.LoadState; import org.osmf.net.NetStreamSwitchManagerBase import org.osmf.net.metrics.BandwidthMetric; import org.osmf.net.DynamicStreamingResource; import org.osmf.net.httpstreaming.DefaultHTTPStreamingSwitchManager; import org.osmf.net.metrics.MetricType; import org.osmf.net.rules.BandwidthRule; /** * Factory to identify and process MPEG2 TS via OSMF. */ public class M2TSNetLoader extends HTTPStreamingNetLoader { private var netStream:HLSHTTPNetStream; override public function canHandleResource( resource:MediaResourceBase ):Boolean { var metadata:Object = resource.getMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA ); if ( metadata != null && metadata == true ) return true; return false; } override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream { var factory:HTTPStreamingFactory = new M2TSStreamingFactory(); var httpNetStream:HLSHTTPNetStream = new HLSHTTPNetStream(connection, factory, resource); return httpNetStream; } override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource):NetStreamSwitchManagerBase { var switcher:DefaultHTTPStreamingSwitchManager = super.createNetStreamSwitchManager(connection, netStream, dsResource) as DefaultHTTPStreamingSwitchManager; // Since our segments are large, switch rapidly. // First, try to bias the bandwidth metric itself. var weights:Vector.<Number> = new Vector.<Number>; weights.push(1.0); weights.push(0.0); weights.push(0.0); var bw:BandwidthMetric = switcher.metricRepository.getMetric(MetricType.BANDWIDTH, weights) as BandwidthMetric; trace("Tried to override BandwidthMetric to N=1, and N=" + bw.weights.length); // Second, bias the bandwidthrule. for(var i:int=0; i<switcher.normalRules.length; i++) { var bwr:BandwidthRule = switcher.normalRules[i] as BandwidthRule; if(!bwr) continue; bwr.weights.length = 3; bwr.weights[0] = 1.0; bwr.weights[1] = 0.0; bwr.weights[2] = 0.0; trace("Adjusted BandwidthRule"); } // Third, adjust the switch logic to be less restrictive. switcher.maxReliabilityRecordSize = 3; switcher.maxUpSwitchLimit = -1; switcher.maxDownSwitchLimit = -1; return switcher; } override protected function processFinishLoading(loadTrait:NetStreamLoadTrait):void { // Set up DVR state updating. var resource:URLResource = loadTrait.resource as URLResource; if (!dvrMetadataPresent(resource)) { updateLoadTrait(loadTrait, LoadState.READY); return; } netStream = loadTrait.netStream as HLSHTTPNetStream; netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); netStream.DVRGetStreamInfo(null); function onDVRStreamInfo(event:DVRStreamInfoEvent):void { netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); loadTrait.setTrait(new HLSDVRTrait(loadTrait.connection, netStream, event.info as DVRInfo)); loadTrait.setTrait(new HLSDVRTimeTrait(loadTrait.connection, netStream, event.info as DVRInfo)); updateLoadTrait(loadTrait, LoadState.READY); } } private function dvrMetadataPresent(resource:URLResource):Boolean { var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata; return (metadata != null); } } }
Tweak switching logic settings.
Tweak switching logic settings.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
4d4b55b42d886d96566eec56ba7a6a88aa13a6e9
test/trace/trace_properties.as
test/trace/trace_properties.as
#if __SWF_VERSION__ == 5 // create a _global object, since it doesn't have one, these are ver 6 values _global = new_empty_object (); _global.ASSetNative = ASSetNative; _global.ASSetNativeAccessor = ASSetNativeAccessor; _global.ASSetPropFlags = ASSetPropFlags; _global.ASconstructor = ASconstructor; _global.ASnative = ASnative; _global.Accessibility = Accessibility; _global.Array = Array; _global.AsBroadcaster = AsBroadcaster; _global.AsSetupError = AsSetupError; _global.Boolean = Boolean; _global.Button = Button; _global.Camera = Camera; _global.Color = Color; _global.ContextMenu = ContextMenu; _global.ContextMenuItem = ContextMenuItem; _global.Date = Date; _global.Error = Error; _global.Function = Function; _global.Infinity = Infinity; _global.Key = Key; _global.LoadVars = LoadVars; _global.LocalConnection = LocalConnection; _global.Math = Math; _global.Microphone = Microphone; _global.Mouse = Mouse; _global.MovieClip = MovieClip; _global.MovieClipLoader = MovieClipLoader; _global.NaN = NaN; _global.NetConnection = NetConnection; _global.NetStream = NetStream; _global.Number = Number; _global.Object = Object; _global.PrintJob = PrintJob; _global.RemoteLSOUsage = RemoteLSOUsage; _global.Selection = Selection; _global.SharedObject = SharedObject; _global.Sound = Sound; _global.Stage = Stage; _global.String = String; _global.System = System; _global.TextField = TextField; _global.TextFormat = TextFormat; _global.TextSnapshot = TextSnapshot; _global.Video = Video; _global.XML = XML; _global.XMLNode = XMLNode; _global.XMLSocket = XMLSocket; _global.clearInterval = clearInterval; _global.clearTimeout = clearTimeout; _global.enableDebugConsole = enableDebugConsole; _global.escape = escape; _global.flash = flash; _global.isFinite = isFinite; _global.isNaN = isNaN; _global.o = o; _global.parseFloat = parseFloat; _global.parseInt = parseInt; _global.setInterval = setInterval; _global.setTimeout = setTimeout; _global.showRedrawRegions = showRedrawRegions; _global.textRenderer = textRenderer; _global.trace = trace; _global.unescape = unescape; _global.updateAfterEvent = updateAfterEvent; #endif function new_empty_object () { var hash = new Object (); ASSetPropFlags (hash, null, 0, 7); for (var prop in hash) { hash[prop] = "to-be-deleted"; delete hash[prop]; } return hash; } function hasOwnProperty_inner (o, prop) { if (o.hasOwnProperty != undefined) return o.hasOwnProperty (prop); o.hasOwnProperty = ASnative (101, 5); var result = o.hasOwnProperty (prop); delete o.hasOwnProperty; return result; } function hasOwnProperty (o, prop) { var result = hasOwnProperty_inner (o, prop); #if __SWF_VERSION__ != 6 if (result == false) { ASSetPropFlags (o, prop, 0, 256); result = hasOwnProperty_inner (o, prop); if (result) ASSetPropFlags (o, prop, 256); } #endif return result; } function new_info () { return new_empty_object (); } function set_info (info, prop, id, value) { info[prop + "_-_" + id] = value; } function get_info (info, prop, id) { return info[prop + "_-_" + id]; } function is_blaclisted (o, prop) { if (prop == "mySecretId" || prop == "globalSecretId") return true; if (o == _global.Camera && prop == "names") return true; if (o == _global.Microphone && prop == "names") return true; return false; } function trace_properties_recurse (o, prefix, identifier, level) { // to collect info about different properties var info = new_info (); // calculate indentation var indentation = ""; for (var j = 0; j < level; j++) { indentation = indentation + " "; } // mark the ones that are not hidden for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) set_info (info, prop, "hidden", false); } } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); var hidden = new Array (); for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) { all.push (prop); if (get_info (info, prop, "hidden") != false) { set_info (info, prop, "hidden", true); hidden.push (prop); } } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, hidden, 1, 0); if (all.length == 0) { trace (indentation + "no children"); return nextSecretId; } #if __SWF_VERSION__ != 6 for (var i = 0; i < all.length; i++) { var prop = all[i]; // try changing value if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop)) { set_info (info, prop, "not6", true); } else { set_info (info, prop, "not6", false); } } #endif for (var i = 0; i < all.length; i++) { var prop = all[i]; if (typeof (o[prop]) == "undefined") { ASSetPropFlags (o, prop, 0, 5248); if (typeof (o[prop]) != "undefined") { set_info (info, prop, "newer", true); // don't set the flags back } else { set_info (info, prop, "newer", false); } } else { set_info (info, prop, "newer", false); } } for (var i = 0; i < all.length; i++) { var prop = all[i]; // try changing value var old = o[prop]; var val = "hello " + o[prop]; o[prop] = val; if (o[prop] != val) { set_info (info, prop, "constant", true); // try changing value after removing constant propflag ASSetPropFlags (o, prop, 0, 4); o[prop] = val; if (o[prop] != val) { set_info (info, prop, "superconstant", true); } else { set_info (info, prop, "superconstant", false); o[prop] = old; } ASSetPropFlags (o, prop, 4); } else { set_info (info, prop, "constant", false); set_info (info, prop, "superconstant", false); o[prop] = old; } } for (var i = 0; i < all.length; i++) { var prop = all[i]; // remove constant flag ASSetPropFlags (o, prop, 0, 4); // try deleting var old = o[prop]; delete o[prop]; if (hasOwnProperty (o, prop)) { set_info (info, prop, "permanent", true); } else { set_info (info, prop, "permanent", false); o[prop] = old; } // put constant flag back, if it was set if (get_info (info, prop, "constant") == true) ASSetPropFlags (o, prop, 4); } for (var i = 0; i < all.length; i++) { var prop = all[i]; // format propflags var flags = ""; if (get_info (info, prop, "hidden") == true) { flags += "h"; } if (get_info (info, prop, "superpermanent") == true) { flags += "P"; } else if (get_info (info, prop, "permanent") == true) { flags += "p"; } if (get_info (info, prop, "superconstant") == true) { flags += "C"; } else if (get_info (info, prop, "constant") == true) { flags += "c"; } if (get_info (info, prop, "not6") == true) { flags += "6"; } if (get_info (info, prop, "newer") == true) { flags += "n"; } if (flags != "") flags = " (" + flags + ")"; var value = ""; // add value depending on the type if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") { value += " : " + o[prop]; } else if (typeof (o[prop]) == "string") { value += " : \"" + o[prop] + "\""; } // recurse if it's object or function and this is the place it has been // named after if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop == o[prop]["mySecretId"]) { trace (indentation + prop + flags + " = " + typeof (o[prop])); trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop, level + 1); } else { trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]); } } else { trace (indentation + prop + flags + " = " + typeof (o[prop]) + value); } } } function generate_names (o, prefix, identifier) { // mark the ones that are not hidden var nothidden = new Array (); for (var prop in o) { nothidden.push (prop); } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); for (var prop in o) { if (is_blaclisted (o, prop) == false) { // only get the ones that are not only in the __proto__ if (hasOwnProperty (o, prop) == true) { all.push (prop); } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, null, 1, 0); ASSetPropFlags (o, nothidden, 0, 1); for (var i = 0; i < all.length; i++) { var newer = false; var prop = all[i]; if (typeof (o[prop]) == "undefined") { ASSetPropFlags (o, prop, 0, 5248); if (typeof (o[prop]) != "undefined") newer = true; } if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (hasOwnProperty (o[prop], "mySecretId")) { all[i] = null; // don't recurse to it again } else { o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier + "." + prop; } } if (newer == true) ASSetPropFlags (o, prop, 5248); } for (var i = 0; i < all.length; i++) { var prop = all[i]; if (prop != null) { var newer = false; if (typeof (o[prop]) == "undefined") { ASSetPropFlags (o, prop, 0, 5248); if (typeof (o[prop]) != "undefined") newer = true; } if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") generate_names (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop); if (newer == true) ASSetPropFlags (o, prop, 5248); } } } function trace_properties (o, prefix, identifier) { _global["mySecretId"] = "_global"; _global.Object["mySecretId"] = "_global.Object"; _global.Function["mySecretId"] = "_global.Function"; _global.Function.prototype["mySecretId"] = "_global.Function.prototype"; _global.XMLNode["mySecretId"] = "_global.XMLNode"; generate_names (_global.Object, "_global", "Object"); generate_names (_global.Function, "_global", "Function"); generate_names (_global.Function.prototype, "_global", "Function.prototype"); generate_names (_global.XMLNode, "_global", "XMLNode"); generate_names (_global, "", "_global"); if (typeof (o) == "object" || typeof (o) == "function") { if (!o.hasOwnProperty ("mySecretId")) { o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier; generate_names (o, prefix, identifier); } if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"]) { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o)); } else { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + o["mySecretId"]); } trace_properties_recurse (o, prefix, identifier, 1); } else { var value = ""; if (typeof (o) == "number" || typeof (o) == "boolean") { value += " : " + o; } else if (typeof (o) == "string") { value += " : \"" + o + "\""; } trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o) + value); } }
#if __SWF_VERSION__ == 5 // create a _global object, since it doesn't have one, these are ver 6 values _global = new_empty_object (); _global.ASSetNative = ASSetNative; _global.ASSetNativeAccessor = ASSetNativeAccessor; _global.ASSetPropFlags = ASSetPropFlags; _global.ASconstructor = ASconstructor; _global.ASnative = ASnative; _global.Accessibility = Accessibility; _global.Array = Array; _global.AsBroadcaster = AsBroadcaster; _global.AsSetupError = AsSetupError; _global.Boolean = Boolean; _global.Button = Button; _global.Camera = Camera; _global.Color = Color; _global.ContextMenu = ContextMenu; _global.ContextMenuItem = ContextMenuItem; _global.Date = Date; _global.Error = Error; _global.Function = Function; _global.Infinity = Infinity; _global.Key = Key; _global.LoadVars = LoadVars; _global.LocalConnection = LocalConnection; _global.Math = Math; _global.Microphone = Microphone; _global.Mouse = Mouse; _global.MovieClip = MovieClip; _global.MovieClipLoader = MovieClipLoader; _global.NaN = NaN; _global.NetConnection = NetConnection; _global.NetStream = NetStream; _global.Number = Number; _global.Object = Object; _global.PrintJob = PrintJob; _global.RemoteLSOUsage = RemoteLSOUsage; _global.Selection = Selection; _global.SharedObject = SharedObject; _global.Sound = Sound; _global.Stage = Stage; _global.String = String; _global.System = System; _global.TextField = TextField; _global.TextFormat = TextFormat; _global.TextSnapshot = TextSnapshot; _global.Video = Video; _global.XML = XML; _global.XMLNode = XMLNode; _global.XMLSocket = XMLSocket; _global.clearInterval = clearInterval; _global.clearTimeout = clearTimeout; _global.enableDebugConsole = enableDebugConsole; _global.escape = escape; _global.flash = flash; _global.isFinite = isFinite; _global.isNaN = isNaN; _global.o = o; _global.parseFloat = parseFloat; _global.parseInt = parseInt; _global.setInterval = setInterval; _global.setTimeout = setTimeout; _global.showRedrawRegions = showRedrawRegions; _global.textRenderer = textRenderer; _global.trace = trace; _global.unescape = unescape; _global.updateAfterEvent = updateAfterEvent; #endif function new_empty_object () { var hash = new Object (); ASSetPropFlags (hash, null, 0, 7); for (var prop in hash) { hash[prop] = "to-be-deleted"; delete hash[prop]; } return hash; } function hasOwnProperty_inner (o, prop) { if (o.hasOwnProperty != undefined) return o.hasOwnProperty (prop); o.hasOwnProperty = ASnative (101, 5); var result = o.hasOwnProperty (prop); delete o.hasOwnProperty; return result; } function hasOwnProperty (o, prop) { var result = hasOwnProperty_inner (o, prop); #if __SWF_VERSION__ != 6 if (result == false) { ASSetPropFlags (o, prop, 0, 256); result = hasOwnProperty_inner (o, prop); if (result) ASSetPropFlags (o, prop, 256); } #endif return result; } function new_info () { return new_empty_object (); } function set_info (info, prop, id, value) { info[prop + "_-_" + id] = value; } function get_info (info, prop, id) { return info[prop + "_-_" + id]; } function is_blaclisted (o, prop) { if (prop == "mySecretId" || prop == "globalSecretId") return true; if (o == _global.Camera && prop == "names") return true; if (o == _global.Microphone && prop == "names") return true; return false; } function trace_properties_recurse (o, prefix, identifier, level) { // to collect info about different properties var info = new_info (); // calculate indentation var indentation = ""; for (var j = 0; j < level; j++) { indentation = indentation + " "; } // mark the ones that are not hidden for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) set_info (info, prop, "hidden", false); } } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); var hidden = new Array (); for (var prop in o) { // only get the ones that are not only in the __proto__ if (is_blaclisted (o, prop) == false) { if (hasOwnProperty (o, prop) == true) { all.push (prop); if (get_info (info, prop, "hidden") != false) { set_info (info, prop, "hidden", true); hidden.push (prop); } } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, hidden, 1, 0); if (all.length == 0) { trace (indentation + "no children"); return nextSecretId; } #if __SWF_VERSION__ != 6 for (var i = 0; i < all.length; i++) { var prop = all[i]; // try changing value if (!hasOwnProperty_inner(o, prop) && hasOwnProperty(o, prop)) { set_info (info, prop, "not6", true); } else { set_info (info, prop, "not6", false); } } #endif for (var i = 0; i < all.length; i++) { var prop = all[i]; if (typeof (o[prop]) == "undefined") { ASSetPropFlags (o, prop, 0, 5248); if (typeof (o[prop]) != "undefined") { set_info (info, prop, "newer", true); // don't set the flags back } else { set_info (info, prop, "newer", false); } } else { set_info (info, prop, "newer", false); } } for (var i = 0; i < all.length; i++) { var prop = all[i]; // try changing value var old = o[prop]; var val = "hello " + o[prop]; o[prop] = val; if (o[prop] != val) { set_info (info, prop, "constant", true); // try changing value after removing constant propflag ASSetPropFlags (o, prop, 0, 4); o[prop] = val; if (o[prop] != val) { set_info (info, prop, "superconstant", true); } else { set_info (info, prop, "superconstant", false); o[prop] = old; } ASSetPropFlags (o, prop, 4); } else { set_info (info, prop, "constant", false); set_info (info, prop, "superconstant", false); o[prop] = old; } } for (var i = 0; i < all.length; i++) { var prop = all[i]; // remove constant flag ASSetPropFlags (o, prop, 0, 4); // try deleting var old = o[prop]; delete o[prop]; if (hasOwnProperty (o, prop)) { set_info (info, prop, "permanent", true); } else { set_info (info, prop, "permanent", false); o[prop] = old; } // put constant flag back, if it was set if (get_info (info, prop, "constant") == true) ASSetPropFlags (o, prop, 4); } for (var i = 0; i < all.length; i++) { var prop = all[i]; // format propflags var flags = ""; if (get_info (info, prop, "hidden") == true) { flags += "h"; } if (get_info (info, prop, "superpermanent") == true) { flags += "P"; } else if (get_info (info, prop, "permanent") == true) { flags += "p"; } if (get_info (info, prop, "superconstant") == true) { flags += "C"; } else if (get_info (info, prop, "constant") == true) { flags += "c"; } if (get_info (info, prop, "not6") == true) { flags += "6"; } if (get_info (info, prop, "newer") == true) { flags += "n"; } if (flags != "") flags = " (" + flags + ")"; var value = ""; // add value depending on the type if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") { value += " : " + o[prop]; } else if (typeof (o[prop]) == "string") { value += " : \"" + o[prop] + "\""; } // recurse if it's object or function and this is the place it has been // named after if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop == o[prop]["mySecretId"]) { trace (indentation + prop + flags + " = " + typeof (o[prop])); trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop, level + 1); } else { trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]); } } else { trace (indentation + prop + flags + " = " + typeof (o[prop]) + value); } } } function generate_names (o, prefix, identifier) { // mark the ones that are not hidden var nothidden = new Array (); for (var prop in o) { nothidden.push (prop); } // unhide everything ASSetPropFlags (o, null, 0, 1); var all = new Array (); for (var prop in o) { if (is_blaclisted (o, prop) == false) { // only get the ones that are not only in the __proto__ if (hasOwnProperty (o, prop) == true) { all.push (prop); } } } all.sort (); // hide the ones that were already hidden ASSetPropFlags (o, null, 1, 0); ASSetPropFlags (o, nothidden, 0, 1); for (var i = 0; i < all.length; i++) { var newer = false; var prop = all[i]; if (typeof (o[prop]) == "undefined") { ASSetPropFlags (o, prop, 0, 5248); if (typeof (o[prop]) != "undefined") newer = true; } if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") { if (hasOwnProperty (o[prop], "mySecretId")) { all[i] = null; // don't recurse to it again } else { o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier + "." + prop; } } if (newer == true) ASSetPropFlags (o, prop, 5248); } for (var i = 0; i < all.length; i++) { var prop = all[i]; if (prop != null) { var newer = false; if (typeof (o[prop]) == "undefined") { ASSetPropFlags (o, prop, 0, 5248); if (typeof (o[prop]) != "undefined") newer = true; } if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") generate_names (o[prop], prefix + (prefix != "" ? "." : "") + identifier, prop); if (newer == true) ASSetPropFlags (o, prop, 5248); } } } function trace_properties (o, prefix, identifier) { _global["mySecretId"] = "_global"; _global.Object["mySecretId"] = "_global.Object"; _global.Function["mySecretId"] = "_global.Function"; _global.Function.prototype["mySecretId"] = "_global.Function.prototype"; _global.XMLNode["mySecretId"] = "_global.XMLNode"; _global.flash.text.TextRenderer["mySecretId"] = "_global.flash.text.TextRenderer"; generate_names (_global.Object, "_global", "Object"); generate_names (_global.Function, "_global", "Function"); generate_names (_global.Function.prototype, "_global", "Function.prototype"); generate_names (_global.XMLNode, "_global", "XMLNode"); generate_names (_global.flash.text.TextRenderer, "_global.flash.text", "TextRenderer"); generate_names (_global, "", "_global"); if (typeof (o) == "object" || typeof (o) == "function") { if (!o.hasOwnProperty ("mySecretId")) { o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier; generate_names (o, prefix, identifier); } if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"]) { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o)); } else { trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + o["mySecretId"]); } trace_properties_recurse (o, prefix, identifier, 1); } else { var value = ""; if (typeof (o) == "number" || typeof (o) == "boolean") { value += " : " + o; } else if (typeof (o) == "string") { value += " : \"" + o + "\""; } trace (prefix + (prefix != "" ? "." : "") + identifier + " = " + typeof (o) + value); } }
Add special case to trace_properties.as for _global.flash.text.TextRenderer
Add special case to trace_properties.as for _global.flash.text.TextRenderer Now flash.text.TextRenderer gets priority in naming over textRenderer
ActionScript
lgpl-2.1
mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec
c550fac17067f1330a497ff184c17d1f4ece32e5
extension/src/starling/shaders/FastGaussianBlurShader.as
extension/src/starling/shaders/FastGaussianBlurShader.as
/** * User: booster * Date: 18/12/13 * Time: 11:29 */ package starling.shaders { import com.barliesque.agal.EasierAGAL; import com.barliesque.agal.IComponent; import com.barliesque.agal.IRegister; import com.barliesque.agal.TextureFlag; import com.barliesque.shaders.macro.Utils; import flash.display3D.Context3D; import flash.display3D.Context3DProgramType; public class FastGaussianBlurShader extends EasierAGAL implements ITextureShader { public static const HORIZONTAL:String = "horizontal"; public static const VERTICAL:String = "vertical"; private static const DEFAULT_FIRST_PASS_STRENGTH:Number = 1.25; private static const DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO:Number = 3.0; private static var _verticalOffsets:Vector.<Number> = new <Number>[0.0, 1.3846153846, 0.0, 3.2307692308]; private static var _horizontalOffsets:Vector.<Number> = new <Number>[1.3846153846, 0.0, 3.2307692308, 0.0]; private var _type:String = HORIZONTAL; private var _pass:int = 0; private var _strength:Number = Number.NaN; private var _firstPassStrength:Number = DEFAULT_FIRST_PASS_STRENGTH; private var _strengthIncreaseRatio:Number = DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO; private var _pixelWidth:Number = Number.NaN; private var _pixelHeight:Number = Number.NaN; private var _paramsDirty:Boolean = true; private var _strengthsDirty:Boolean = true; private var _strengths:Vector.<Number> = new <Number>[]; private var _offsets:Vector.<Number> = new <Number>[0, 0, 0, 0]; private var _uv:Vector.<Number> = new <Number>[0, 1, 0, 1]; private var _weights:Vector.<Number> = new <Number>[0.2270270270, 0.3162162162, 0.0702702703, 0]; public function get type():String { return _type; } public function set type(value:String):void { if(value == _type) return; _type = value; _paramsDirty = true; } public function get strength():Number { return _strength; } public function set strength(value:Number):void { if(value == _strength) return; _strength = value; _paramsDirty = true; _strengthsDirty = true; } public function get firstPassStrength():Number { return _firstPassStrength; } public function set firstPassStrength(value:Number):void { if(_firstPassStrength == value) return; _firstPassStrength = value; _paramsDirty = true; _strengthsDirty = true; } public function get strengthIncreaseRatio():Number { return _strengthIncreaseRatio; } public function set strengthIncreaseRatio(value:Number):void { if(_strengthIncreaseRatio == value) return; _strengthIncreaseRatio = value; _paramsDirty = true; _strengthsDirty = true; } public function get pass():int { return _pass; } public function set pass(value:int):void { if(value == _pass) return; _pass = value; _paramsDirty = true; } public function get pixelWidth():Number { return _pixelWidth; } public function set pixelWidth(value:Number):void { if(value == _pixelWidth) return; _pixelWidth = value; _paramsDirty = true; } public function get pixelHeight():Number { return _pixelHeight; } public function set pixelHeight(value:Number):void { if(value == _pixelHeight) return; _pixelHeight = value; _paramsDirty = true; } public function get passesNeeded():int { if(_strengthsDirty) updateStrengths(); return _strengths.length; } public function get minU():Number { return _uv[0]; } public function set minU(value:Number):void { _uv[0] = value; } public function get maxU():Number { return _uv[1]; } public function set maxU(value:Number):void { _uv[1] = value; } public function get minV():Number { return _uv[2]; } public function set minV(value:Number):void { _uv[2] = value; } public function get maxV():Number { return _uv[3]; } public function set maxV(value:Number):void { _uv[3] = value; } public function activate(context:Context3D):void { if(_strengthsDirty) updateStrengths(); if(_paramsDirty) updateParameters(); context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 4, _offsets); context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, _weights); context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 1, _uv); } public function deactivate(context:Context3D):void { } override protected function _vertexShader():void { comment("Apply a 4x4 matrix to transform vertices to clip-space"); multiply4x4(OUTPUT, ATTRIBUTE[0], CONST[0]); comment("Pass uv coordinates to fragment shader"); move(VARYING[0], ATTRIBUTE[1]); comment("pass 4 additional UVs for sampling neighbours, in order: -2, -1, +1, +2 pixels away"); subtract(VARYING[1], ATTRIBUTE[1], CONST[4].zw); subtract(VARYING[2], ATTRIBUTE[1], CONST[4].xy); add(VARYING[3], ATTRIBUTE[1], CONST[4].xy); add(VARYING[4], ATTRIBUTE[1], CONST[4].zw); } override protected function _fragmentShader():void { var uvCenter:IRegister = VARYING[0]; var uvMinusTwo:IRegister = VARYING[1]; var uvMinusOne:IRegister = VARYING[2]; var uvPlusOne:IRegister = VARYING[3]; var uvPlusTwo:IRegister = VARYING[4]; var uv:IRegister = TEMP[7]; var weightCenter:IComponent = CONST[0].x; var weightOne:IComponent = CONST[0].y; var weightTwo:IComponent = CONST[0].z; var minU:IComponent = CONST[1].x; var maxU:IComponent = CONST[1].y; var minV:IComponent = CONST[1].z; var maxV:IComponent = CONST[1].w; var colorCenter:IRegister = TEMP[0]; var colorMinusTwo:IRegister = TEMP[1]; var colorMinusOne:IRegister = TEMP[2]; var colorPlusOne:IRegister = TEMP[3]; var colorPlusTwo:IRegister = TEMP[4]; var outputColor:IRegister = TEMP[5]; var textureFlags:Array = [TextureFlag.TYPE_2D, TextureFlag.MODE_CLAMP, TextureFlag.FILTER_LINEAR, TextureFlag.MIP_NO]; sampleTexture(colorCenter, uvCenter, SAMPLER[0], textureFlags); multiply(outputColor, colorCenter, weightCenter); move(uv, uvMinusTwo); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorMinusTwo, uv, SAMPLER[0], textureFlags); multiply(colorMinusTwo, colorMinusTwo, weightTwo); add(outputColor, outputColor, colorMinusTwo); move(uv, uvMinusOne); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorMinusOne, uv, SAMPLER[0], textureFlags); multiply(colorMinusOne, colorMinusOne, weightOne); add(outputColor, outputColor, colorMinusOne); move(uv, uvPlusOne); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorPlusOne, uv, SAMPLER[0], textureFlags); multiply(colorPlusOne, colorPlusOne, weightOne); add(outputColor, outputColor, colorPlusOne); move(uv, uvPlusTwo); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorPlusTwo, uv, SAMPLER[0], textureFlags); multiply(colorPlusTwo, colorPlusTwo, weightTwo); add(outputColor, outputColor, colorPlusTwo); move(OUTPUT, outputColor); } private function updateParameters():void { // algorithm described here: // http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/ // // To run in constrained mode, we can only make 5 texture lookups in the fragment // shader. By making use of linear texture sampling, we can produce similar output // to what would be 9 lookups. _paramsDirty = false; var multiplier:Number, str:Number = _strengths[_pass]; var i:int, count:int = 4; trace("str: " + str); if(type == HORIZONTAL) { multiplier = _pixelWidth * str; for(i = 0; i < count; i++) _offsets[i] = _horizontalOffsets[i] * multiplier; } else { multiplier = _pixelHeight * str; for(i = 0; i < count; i++) _offsets[i] = _verticalOffsets[i] * multiplier; } } private function updateStrengths():void { _strengthsDirty = false; _strengths.length = 0; var str:Number = Math.min(_firstPassStrength, _strength); var sum:Number = 0; while(sum + str < _strength) { _strengths[_strengths.length] = str; sum += str; str *= _strengthIncreaseRatio; } var diff:Number = _strength - sum; if(diff > 0 || _strengths.length == 0) _strengths[_strengths.length] = diff; _strengths.sort(function (a:Number, b:Number):Number { return b - a; }); trace("strengths: [" + _strengths + "], total: " + _strength); } } }
/** * User: booster * Date: 18/12/13 * Time: 11:29 */ package starling.shaders { import com.barliesque.agal.EasierAGAL; import com.barliesque.agal.IComponent; import com.barliesque.agal.IRegister; import com.barliesque.agal.TextureFlag; import com.barliesque.shaders.macro.Utils; import flash.display3D.Context3D; import flash.display3D.Context3DProgramType; public class FastGaussianBlurShader extends EasierAGAL implements ITextureShader { public static const HORIZONTAL:String = "horizontal"; public static const VERTICAL:String = "vertical"; private static const DEFAULT_FIRST_PASS_STRENGTH:Number = 1.25; private static const DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO:Number = 3.0; private static var _verticalOffsets:Vector.<Number> = new <Number>[0.0, 1.3846153846, 0.0, 3.2307692308]; private static var _horizontalOffsets:Vector.<Number> = new <Number>[1.3846153846, 0.0, 3.2307692308, 0.0]; private var _type:String = HORIZONTAL; private var _pass:int = 0; private var _strength:Number = Number.NaN; private var _firstPassStrength:Number = DEFAULT_FIRST_PASS_STRENGTH; private var _strengthIncreaseRatio:Number = DEFAULT_STRENGTH_INCREASE_PER_PASS_RATIO; private var _pixelWidth:Number = Number.NaN; private var _pixelHeight:Number = Number.NaN; private var _paramsDirty:Boolean = true; private var _strengthsDirty:Boolean = true; private var _strengths:Vector.<Number> = new <Number>[]; private var _offsets:Vector.<Number> = new <Number>[0, 0, 0, 0]; private var _uv:Vector.<Number> = new <Number>[0, 1, 0, 1]; private var _weights:Vector.<Number> = new <Number>[0.2270270270, 0.3162162162, 0.0702702703, 0]; public function get type():String { return _type; } public function set type(value:String):void { if(value == _type) return; _type = value; _paramsDirty = true; } public function get strength():Number { return _strength; } public function set strength(value:Number):void { if(value == _strength) return; _strength = value; _paramsDirty = true; _strengthsDirty = true; } public function get firstPassStrength():Number { return _firstPassStrength; } public function set firstPassStrength(value:Number):void { if(_firstPassStrength == value) return; _firstPassStrength = value; _paramsDirty = true; _strengthsDirty = true; } public function get strengthIncreaseRatio():Number { return _strengthIncreaseRatio; } public function set strengthIncreaseRatio(value:Number):void { if(_strengthIncreaseRatio == value) return; _strengthIncreaseRatio = value; _paramsDirty = true; _strengthsDirty = true; } public function get pass():int { return _pass; } public function set pass(value:int):void { if(value == _pass) return; _pass = value; _paramsDirty = true; } public function get pixelWidth():Number { return _pixelWidth; } public function set pixelWidth(value:Number):void { if(value == _pixelWidth) return; _pixelWidth = value; _paramsDirty = true; } public function get pixelHeight():Number { return _pixelHeight; } public function set pixelHeight(value:Number):void { if(value == _pixelHeight) return; _pixelHeight = value; _paramsDirty = true; } public function get passesNeeded():int { if(_strengthsDirty) updateStrengths(); return _strengths.length; } public function get minU():Number { return _uv[0]; } public function set minU(value:Number):void { _uv[0] = value; } public function get maxU():Number { return _uv[1]; } public function set maxU(value:Number):void { _uv[1] = value; } public function get minV():Number { return _uv[2]; } public function set minV(value:Number):void { _uv[2] = value; } public function get maxV():Number { return _uv[3]; } public function set maxV(value:Number):void { _uv[3] = value; } public function activate(context:Context3D):void { if(_strengthsDirty) updateStrengths(); if(_paramsDirty) updateParameters(); context.setProgramConstantsFromVector(Context3DProgramType.VERTEX, 4, _offsets); context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, _weights); context.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 1, _uv); } public function deactivate(context:Context3D):void { } override protected function _vertexShader():void { comment("Apply a 4x4 matrix to transform vertices to clip-space"); multiply4x4(OUTPUT, ATTRIBUTE[0], CONST[0]); comment("Pass uv coordinates to fragment shader"); move(VARYING[0], ATTRIBUTE[1]); comment("pass 4 additional UVs for sampling neighbours, in order: -2, -1, +1, +2 pixels away"); subtract(VARYING[1], ATTRIBUTE[1], CONST[4].zw); subtract(VARYING[2], ATTRIBUTE[1], CONST[4].xy); add(VARYING[3], ATTRIBUTE[1], CONST[4].xy); add(VARYING[4], ATTRIBUTE[1], CONST[4].zw); } override protected function _fragmentShader():void { var uvCenter:IRegister = VARYING[0]; var uvMinusTwo:IRegister = VARYING[1]; var uvMinusOne:IRegister = VARYING[2]; var uvPlusOne:IRegister = VARYING[3]; var uvPlusTwo:IRegister = VARYING[4]; var uv:IRegister = TEMP[7]; var weightCenter:IComponent = CONST[0].x; var weightOne:IComponent = CONST[0].y; var weightTwo:IComponent = CONST[0].z; var minU:IComponent = CONST[1].x; var maxU:IComponent = CONST[1].y; var minV:IComponent = CONST[1].z; var maxV:IComponent = CONST[1].w; var colorCenter:IRegister = TEMP[0]; var colorMinusTwo:IRegister = TEMP[1]; var colorMinusOne:IRegister = TEMP[2]; var colorPlusOne:IRegister = TEMP[3]; var colorPlusTwo:IRegister = TEMP[4]; var outputColor:IRegister = TEMP[5]; var textureFlags:Array = [TextureFlag.TYPE_2D, TextureFlag.MODE_CLAMP, TextureFlag.FILTER_LINEAR, TextureFlag.MIP_NO]; sampleTexture(colorCenter, uvCenter, SAMPLER[0], textureFlags); multiply(outputColor, colorCenter, weightCenter); move(uv, uvMinusTwo); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorMinusTwo, uv, SAMPLER[0], textureFlags); multiply(colorMinusTwo, colorMinusTwo, weightTwo); add(outputColor, outputColor, colorMinusTwo); move(uv, uvMinusOne); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorMinusOne, uv, SAMPLER[0], textureFlags); multiply(colorMinusOne, colorMinusOne, weightOne); add(outputColor, outputColor, colorMinusOne); move(uv, uvPlusOne); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorPlusOne, uv, SAMPLER[0], textureFlags); multiply(colorPlusOne, colorPlusOne, weightOne); add(outputColor, outputColor, colorPlusOne); move(uv, uvPlusTwo); Utils.clamp(uv.x, uv.x, minU, maxU); Utils.clamp(uv.y, uv.y, minV, maxV); sampleTexture(colorPlusTwo, uv, SAMPLER[0], textureFlags); multiply(colorPlusTwo, colorPlusTwo, weightTwo); add(outputColor, outputColor, colorPlusTwo); move(OUTPUT, outputColor); } private function updateParameters():void { // algorithm described here: // http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling/ // // To run in constrained mode, we can only make 5 texture lookups in the fragment // shader. By making use of linear texture sampling, we can produce similar output // to what would be 9 lookups. _paramsDirty = false; var multiplier:Number, str:Number = _strengths[_pass]; var i:int, count:int = 4; if(type == HORIZONTAL) { multiplier = _pixelWidth * str; for(i = 0; i < count; i++) _offsets[i] = _horizontalOffsets[i] * multiplier; } else { multiplier = _pixelHeight * str; for(i = 0; i < count; i++) _offsets[i] = _verticalOffsets[i] * multiplier; } //trace("str: " + str); } private function updateStrengths():void { _strengthsDirty = false; _strengths.length = 0; var str:Number = Math.min(_firstPassStrength, _strength); var sum:Number = 0; while(sum + str < _strength) { _strengths[_strengths.length] = str; sum += str; str *= _strengthIncreaseRatio; } var diff:Number = _strength - sum; if(diff > 0 || _strengths.length == 0) _strengths[_strengths.length] = diff; _strengths.sort(function (a:Number, b:Number):Number { return b - a; }); //trace("strengths: [" + _strengths + "], total: " + _strength); } } }
Debug messages removed
Debug messages removed
ActionScript
mit
b005t3r/Starling-Extension-TextureProcessor
630666dc175d469d0b6e9dabb880aeffc2f2d5ee
dolly-framework/src/test/resources/dolly/data/PropertyLevelCopyableClass.as
dolly-framework/src/test/resources/dolly/data/PropertyLevelCopyableClass.as
package dolly.data { public class PropertyLevelCopyableClass { [Copyable] public static var staticProperty1:String = "Value of first-level static property 1."; public static var staticProperty2:String = "Value of first-level static property 2."; [Cloneable] private var _writableField1:String = "Value of first-level writable field."; [Cloneable] public var property1:String = "Value of first-level public property 1."; public var property2:String = "Value of first-level public property 2."; public function PropertyLevelCopyableClass() { } [Copyable] public function get writableField1():String { return _writableField1; } public function set writableField1(value:String):void { _writableField1 = value; } [Copyable] public function get readOnlyField1():String { return "Value of first-level read-only field."; } } }
package dolly.data { public class PropertyLevelCopyableClass { [Copyable] public static var staticProperty1:String = "Value of first-level static property 1."; public static var staticProperty2:String = "Value of first-level static property 2."; [Copyable] private var _writableField1:String = "Value of first-level writable field."; [Copyable] public var property1:String = "Value of first-level public property 1."; public var property2:String = "Value of first-level public property 2."; public function PropertyLevelCopyableClass() { } [Copyable] public function get writableField1():String { return _writableField1; } public function set writableField1(value:String):void { _writableField1 = value; } [Copyable] public function get readOnlyField1():String { return "Value of first-level read-only field."; } } }
Fix stupid mistake with metadata names.
Fix stupid mistake with metadata names.
ActionScript
mit
Yarovoy/dolly
0f8e77f4c87150ddca3ea2eaa103392c581c0954
as3/com/netease/protobuf/BaseFieldDescriptor.as
as3/com/netease/protobuf/BaseFieldDescriptor.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2011 , Yang Bo All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.errors.IllegalOperationError import flash.utils.getDefinitionByName; import flash.utils.IDataInput /** * @private */ public class BaseFieldDescriptor implements IFieldDescriptor { public var fullName:String protected var _name:String public final function get name():String { return _name } protected var tag:uint public final function get tagNumber():uint { return tag >>> 7 } public function get type():Class { throw new IllegalOperationError("Not Implemented!") } public function readSingleField(input:IDataInput):* { throw new IllegalOperationError("Not Implemented!") } public function writeSingleField(output:WritingBuffer, value:*):void { throw new IllegalOperationError("Not Implemented!") } public function write(destination:WritingBuffer, source:Message):void { throw new IllegalOperationError("Not Implemented!") } private static const ACTIONSCRIPT_KEYWORDS:Object = { "as" : true, "break" : true, "case" : true, "catch" : true, "class" : true, "const" : true, "continue" : true, "default" : true, "delete" : true, "do" : true, "else" : true, "extends" : true, "false" : true, "finally" : true, "for" : true, "function" : true, "if" : true, "implements" : true, "import" : true, "in" : true, "instanceof" : true, "interface" : true, "internal" : true, "is" : true, "native" : true, "new" : true, "null" : true, "package" : true, "private" : true, "protected" : true, "public" : true, "return" : true, "super" : true, "switch" : true, "this" : true, "throw" : true, "to" : true, "true" : true, "try" : true, "typeof" : true, "use" : true, "var" : true, "void" : true, "while" : true, "with" : true } public function toString():String { return name } internal static function getExtensionByName( name:String):BaseFieldDescriptor { const fieldPosition:int = name.lastIndexOf('/') if (fieldPosition == -1) { return BaseFieldDescriptor(getDefinitionByName(name)) } else { return getDefinitionByName(name.substring(0, fieldPosition))[ name.substring(fieldPosition + 1)] } } } } function regexToUpperCase(matched:String, index:int, whole:String):String { return matched.charAt(1).toUpperCase() }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2011 , Yang Bo All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.errors.IllegalOperationError import flash.utils.getDefinitionByName; import flash.utils.IDataInput /** * @private */ public class BaseFieldDescriptor implements IFieldDescriptor { public var fullName:String protected var _name:String public final function get name():String { return _name } protected var tag:uint public final function get tagNumber():uint { return tag >>> 3 } public function get type():Class { throw new IllegalOperationError("Not Implemented!") } public function readSingleField(input:IDataInput):* { throw new IllegalOperationError("Not Implemented!") } public function writeSingleField(output:WritingBuffer, value:*):void { throw new IllegalOperationError("Not Implemented!") } public function write(destination:WritingBuffer, source:Message):void { throw new IllegalOperationError("Not Implemented!") } private static const ACTIONSCRIPT_KEYWORDS:Object = { "as" : true, "break" : true, "case" : true, "catch" : true, "class" : true, "const" : true, "continue" : true, "default" : true, "delete" : true, "do" : true, "else" : true, "extends" : true, "false" : true, "finally" : true, "for" : true, "function" : true, "if" : true, "implements" : true, "import" : true, "in" : true, "instanceof" : true, "interface" : true, "internal" : true, "is" : true, "native" : true, "new" : true, "null" : true, "package" : true, "private" : true, "protected" : true, "public" : true, "return" : true, "super" : true, "switch" : true, "this" : true, "throw" : true, "to" : true, "true" : true, "try" : true, "typeof" : true, "use" : true, "var" : true, "void" : true, "while" : true, "with" : true } public function toString():String { return name } internal static function getExtensionByName( name:String):BaseFieldDescriptor { const fieldPosition:int = name.lastIndexOf('/') if (fieldPosition == -1) { return BaseFieldDescriptor(getDefinitionByName(name)) } else { return getDefinitionByName(name.substring(0, fieldPosition))[ name.substring(fieldPosition + 1)] } } } } function regexToUpperCase(matched:String, index:int, whole:String):String { return matched.charAt(1).toUpperCase() }
修复bug:tagID应该右移3位
修复bug:tagID应该右移3位
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
da7d4afda359a541b04717346aae7b181437196c
src/com/kemsky/support/isNaNFast.as
src/com/kemsky/support/isNaNFast.as
package com.kemsky.support { /** * Faster alternative to isNaN() * @private */ public function isNaNFast(target:*):Boolean { return !(target <= 0) && !(target > 0); } }
package com.kemsky.support { /** * Faster alternative to isNaN() * Useless in fact, function call is more expensive than isNaN * @private */ public function isNaNFast(target:*):Boolean { return !(target <= 0) && !(target > 0); } }
replace isNaN
replace isNaN
ActionScript
mit
kemsky/stream
5c1d8baccb5d11f91dd5bcc285560796ce5b690e
test/src/TestKLine.as
test/src/TestKLine.as
package { import flash.display.Graphics; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.TimerEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; /** * ... * @author lizhi */ public class TestKLine extends Sprite { private var datas:Array = []; private var kline:Sprite = new Sprite; private var labelTF:TextField = new TextField; private var ox:Number = 80; private var ox2:Number = 200; private var oy:Number = 30; public function TestKLine() { CONFIG::js_only{ SpriteFlexjs.autoSize = true; } stage.loaderInfo.parameters; labelTF.defaultTextFormat=new TextFormat("Courier New",24); labelTF.background = true; labelTF.backgroundColor = 0xdb5f4a; labelTF.textColor = 0xffffff; labelTF.autoSize = "left"; stage.addEventListener(Event.RESIZE, resize); var loader:URLLoader = new URLLoader; loader.addEventListener(Event.COMPLETE, loader_complete_all); loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioError); loader.load(new URLRequest("http://121.43.100.114:9095/getAllMobilePrice.do?pcode=XTAG100G&v="+Math.random())); addChild(kline); kline.y = oy; //update(); } private function loader_ioError(e:IOErrorEvent):void { trace(e); loader_complete_all(null); } private function timer_timer(e:TimerEvent):void { var loader:URLLoader = new URLLoader; loader.addEventListener(Event.COMPLETE, loader_complete); loader.load(new URLRequest("http://121.43.100.114:9095/getNewMobilePrice.do?pcode=XTAG100G&v="+Math.random())); //todo del //addData(10*Math.random()); //update(); } private function loader_complete_all(e:Event):void { if(e) var loader:URLLoader = e.currentTarget as URLLoader; if (loader){ var obj:Object = JSON.parse(loader.data + ""); for each(var o:Object in obj["content"]){ var d:Number = o["price"]; addData(d); } update(); } var timer:Timer = new Timer(5000); timer.addEventListener(TimerEvent.TIMER, timer_timer); timer.start(); } private function loader_complete(e:Event):void { var loader:URLLoader = e.currentTarget as URLLoader; var obj:Object = JSON.parse(loader.data+""); var d:Number = obj["content"]["price"]; addData(d); update(); } private function addData(data:Number):void{ datas.unshift(data); if (datas.length > 120){ datas.length = 120; } } private function resize(e:Event):void { update(); } private function update():void{ var min:Number = 1000; var max:Number =-1000; for each(var d:Number in datas){ if (d<min){ min = d; } if (d > max){ max = d; } } var w:Number = stage.stageWidth; var w2:Number = (w - ox2) / 120; kline.removeChildren(); kline.graphics.clear(); kline.graphics.lineStyle(0,0x555555); //trace(min, max); var s:Number = 0.05; while (true){ var minV:Number = Math.floor(min / s);// * s; var maxV:Number = Math.ceil(max / s);// * s; var numline:int = maxV - minV; if (numline < 4){ for (; numline < 3;numline++ ){ if ((numline%2)==0){ minV -= 1; }else{ maxV += 1; } } var h:Number = (stage.stageHeight - 2 * oy) / numline; for (var i:int = 0; i <= numline; i++ ){ var y:Number = getY(minV + i, minV, maxV, s, h); drawDashLine(kline.graphics, 0, y, w-ox, y,2); var tf:TextField = new TextField; tf.defaultTextFormat=new TextFormat("Courier New",24); tf.autoSize = "left"; kline.addChild(tf); tf.text = ""+((minV + i)*s).toFixed(2); tf.y = y-tf.height/2; tf.x = w-ox; } break; } s += .5; } kline.graphics.lineStyle(0, 0xdb5f4a); for (i = 0; i < datas.length; i++ ){ d = datas[i]; y = getY(d/s, minV, maxV, s, h); var x:Number = w - i * w2-ox2; if(i==0){ kline.graphics.moveTo(x + ox2-ox, y); kline.addChild(labelTF); labelTF.y = y - labelTF.height / 2; labelTF.x = w - ox; labelTF.text = d.toFixed(2) + ""; } kline.graphics.lineTo(x, y); if (x < 0){ break; } } } private function getY(v:Number, min:Number, max:Number,s:Number,h:Number):Number{ return (max - v) * h; } private function drawDashLine(ctx:Graphics, x1:Number, y1:Number, x2:Number, y2:Number, dashLen:Number=5):void { var xpos:Number = x2 - x1;//得到横向的高度; var ypos:Number = y2 - y1; //得到纵向的高度; var numDashes:Number = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen); //利用正切获取斜边的长度除以虚线长度,得到要分为多少段; for (var i:int = 0; i < numDashes; i++) { if (i % 2 === 0) { ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i); //有了横向宽度和多少段,得出每一段是多长,起点 + 每段长度 * i = 要绘制的起点; } else { ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i); } } } } }
package { import flash.display.Graphics; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.TimerEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.Timer; import flash.utils.getTimer; /** * ... * @author lizhi */ public class TestKLine extends Sprite { private var datas:Array = []; private var kline:Sprite = new Sprite; private var labelTF:TextField = new TextField; private var ox:Number = 80; private var ox2:Number = 200; private var oy:Number = 30; public function TestKLine() { CONFIG::js_only{ SpriteFlexjs.autoSize = true; } stage.loaderInfo.parameters; labelTF.defaultTextFormat=new TextFormat("Courier New",24); labelTF.background = true; labelTF.backgroundColor = 0xdb5f4a; labelTF.textColor = 0xffffff; labelTF.autoSize = "left"; stage.addEventListener(Event.RESIZE, resize); var loader:URLLoader = new URLLoader; loader.addEventListener(Event.COMPLETE, loader_complete_all); loader.addEventListener(IOErrorEvent.IO_ERROR, loader_ioError); loader.load(new URLRequest("http://121.43.100.114:9095/getAllMobilePrice.do?pcode=XTAG100G&v="+Math.random())); addChild(kline); kline.y = oy; //update(); } private function loader_ioError(e:IOErrorEvent):void { trace(e); loader_complete_all(null); } private function timer_timer(e:TimerEvent):void { var loader:URLLoader = new URLLoader; loader.addEventListener(Event.COMPLETE, loader_complete); loader.load(new URLRequest("http://121.43.100.114:9095/getNewMobilePrice.do?pcode=XTAG100G&v="+Math.random())); //todo del //addData(10*Math.random()); //update(); } private function loader_complete_all(e:Event):void { if(e) var loader:URLLoader = e.currentTarget as URLLoader; if (loader){ var obj:Object = JSON.parse(loader.data + ""); for each(var o:Object in obj["content"]){ var d:Number = o["price"]; addData(d); } update(); } var timer:Timer = new Timer(5000); timer.addEventListener(TimerEvent.TIMER, timer_timer); timer.start(); } private function loader_complete(e:Event):void { var loader:URLLoader = e.currentTarget as URLLoader; var obj:Object = JSON.parse(loader.data+""); var d:Number = obj["content"]["price"]; addData(d); update(); } private function addData(data:Number):void{ datas.unshift(data); if (datas.length > 120){ datas.length = 120; } } private function resize(e:Event):void { update(); } private function update():void{ var min:Number = 1000; var max:Number =-1000; for each(var d:Number in datas){ if (d<min){ min = d; } if (d > max){ max = d; } } var w:Number = stage.stageWidth; var w2:Number = (w - ox2) / 120; kline.removeChildren(); kline.graphics.clear(); kline.graphics.lineStyle(0,0x555555); //trace(min, max); var s:Number = 0.05; while (true){ var minV:Number = Math.floor(min / s);// * s; var maxV:Number = Math.ceil(max / s);// * s; var numline:int = maxV - minV; if (numline < 4){ for (; numline < 3;numline++ ){ if ((numline%2)==0){ minV -= 1; }else{ maxV += 1; } } var h:Number = int((stage.stageHeight - 2 * oy) / numline); for (var i:int = 0; i <= numline; i++ ){ var y:Number = getY(minV + i, minV, maxV, s, h); drawDashLine(kline.graphics, 0, y, w-ox, y,2); var tf:TextField = new TextField; tf.defaultTextFormat=new TextFormat("Courier New",24); tf.autoSize = "left"; kline.addChild(tf); tf.text = ""+((minV + i)*s).toFixed(2); tf.y = y-tf.height/2; tf.x = w-ox; } break; } s += .5; } kline.graphics.lineStyle(0, 0xdb5f4a); for (i = 0; i < datas.length; i++ ){ d = datas[i]; y = getY(d/s, minV, maxV, s, h); var x:Number = w - i * w2-ox2; if(i==0){ kline.graphics.moveTo(x + ox2-ox, y); kline.addChild(labelTF); labelTF.y = y - labelTF.height / 2; labelTF.x = w - ox; labelTF.text = d.toFixed(2) + ""; } kline.graphics.lineTo(x, y); if (x < 0){ break; } } } private function getY(v:Number, min:Number, max:Number,s:Number,h:Number):Number{ return Math.round((max - v) * h)+.5; } private function drawDashLine(ctx:Graphics, x1:Number, y1:Number, x2:Number, y2:Number, dashLen:Number=5):void { var xpos:Number = x2 - x1;//得到横向的高度; var ypos:Number = y2 - y1; //得到纵向的高度; var numDashes:Number = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen); //利用正切获取斜边的长度除以虚线长度,得到要分为多少段; for (var i:int = 0; i < numDashes; i++) { if (i % 2 === 0) { ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i); //有了横向宽度和多少段,得出每一段是多长,起点 + 每段长度 * i = 要绘制的起点; } else { ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i); } } } } }
test kline update
test kline update
ActionScript
mit
matrix3d/spriteflexjs,matrix3d/spriteflexjs
19febb579adabc379bbb078c28d1afabf217dd38
vivified/core/vivi_initialize.as
vivified/core/vivi_initialize.as
/* Vivified * Copyright (C) 2007 Benjamin Otte <[email protected]> * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ /*** general objects ***/ Wrap = function () {}; Wrap.prototype = {}; Wrap.prototype.toString = Native.wrap_toString; Frame = function () extends Wrap {}; Frame.prototype = new Wrap (); Frame.prototype.addProperty ("code", Native.frame_code_get, null); Frame.prototype.addProperty ("name", Native.frame_name_get, null); Frame.prototype.addProperty ("next", Native.frame_next_get, null); /*** breakpoints ***/ Breakpoint = function () extends Native.Breakpoint { super (); Breakpoint.list.push (this); }; Breakpoint.list = new Array (); Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set); /*** information about the player ***/ Player = {}; Player.addProperty ("frame", Native.player_frame_get, null); /*** commands available for debugging ***/ Commands = new Object (); Commands.print = Native.print; Commands.error = Native.error; Commands.r = Native.run; Commands.run = Native.run; Commands.halt = Native.stop; Commands.stop = Native.stop; Commands.s = Native.step; Commands.step = Native.step; Commands.reset = Native.reset; Commands.restart = function () { Commands.reset (); Commands.run (); }; Commands.quit = Native.quit; /* can't use "break" as a function name, it's a keyword in JS */ Commands.add = function (name) { if (name == undefined) { Commands.error ("add command requires a function name"); return undefined; } var ret = new Breakpoint (); ret.onStartFrame = function (frame) { if (frame.name != name) return false; Commands.print ("Breakpoint: function " + name + " called"); Commands.print (" " + frame); return true; }; ret.toString = function () { return "function call " + name; }; }; Commands.list = function () { var a = Breakpoint.list; var i; for (i = 0; i < a.length; i++) { Commands.print (i + ": " + a[i]); } }; Commands.del = function (id) { var a = Breakpoint.list; if (id == undefined) { while (a[0]) Commands.del (0); } var b = a[id]; a.splice (id, 1); b.active = false; }; Commands.delete = Commands.del;
/* Vivified * Copyright (C) 2007 Benjamin Otte <[email protected]> * * This library 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 2.1 of the License, or (at your option) any later version. * * This library 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 this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ /*** general objects ***/ Wrap = function () {}; Wrap.prototype = {}; Wrap.prototype.toString = Native.wrap_toString; Frame = function () extends Wrap {}; Frame.prototype = new Wrap (); Frame.prototype.addProperty ("code", Native.frame_code_get, null); Frame.prototype.addProperty ("name", Native.frame_name_get, null); Frame.prototype.addProperty ("next", Native.frame_next_get, null); /*** breakpoints ***/ Breakpoint = function () extends Native.Breakpoint { super (); Breakpoint.list.push (this); }; Breakpoint.list = new Array (); Breakpoint.prototype.addProperty ("active", Native.breakpoint_active_get, Native.breakpoint_active_set); /*** information about the player ***/ Player = {}; Player.addProperty ("frame", Native.player_frame_get, null); /*** commands available for debugging ***/ Commands = new Object (); Commands.print = Native.print; Commands.error = Native.error; Commands.r = Native.run; Commands.run = Native.run; Commands.halt = Native.stop; Commands.stop = Native.stop; Commands.s = Native.step; Commands.step = Native.step; Commands.reset = Native.reset; Commands.restart = function () { Commands.reset (); Commands.run (); }; Commands.quit = Native.quit; /* can't use "break" as a function name, it's a keyword in JS */ Commands.add = function (name) { if (name == undefined) { Commands.error ("add command requires a function name"); return undefined; } var ret = new Breakpoint (); ret.onStartFrame = function (frame) { if (frame.name != name) return false; Commands.print ("Breakpoint: function " + name + " called"); Commands.print (" " + frame); return true; }; ret.toString = function () { return "function call " + name; }; return ret; }; Commands.list = function () { var a = Breakpoint.list; var i; for (i = 0; i < a.length; i++) { Commands.print (i + ": " + a[i]); } }; Commands.del = function (id) { var a = Breakpoint.list; if (id == undefined) { while (a[0]) Commands.del (0); } var b = a[id]; a.splice (id, 1); b.active = false; }; Commands.delete = Commands.del;
return the breakpoint that was added from Commands.add()
return the breakpoint that was added from Commands.add()
ActionScript
lgpl-2.1
freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
60217f11d9d8643910bad1934a41ca054b12aae4
src/as/com/threerings/util/NetUtil.as
src/as/com/threerings/util/NetUtil.as
package com.threerings.util { import flash.net.URLRequest; //import flash.net.navigateToURL; // function import public class NetUtil { /** * Convenience method to load a web page in the browser window without * having to worry about SecurityErrors in various conditions. * * @return true if the url was unable to be loaded. */ public static function navigateToURL ( url :String, preferSameWindowOrTab :Boolean = true) :Boolean { var ureq :URLRequest = new URLRequest(url); if (preferSameWindowOrTab) { try { flash.net.navigateToURL(ureq, "_self"); return true; } catch (err :SecurityError) { // ignore; fall back to using a blank window, below... } } // open in a blank window try { flash.net.navigateToURL(ureq); return true; } catch (err :SecurityError) { Log.getLog(NetUtil).warning( "Unable to navigate to URL [e=" + err + "]."); } return false; // failure! } } }
package com.threerings.util { import flash.net.URLRequest; //import flash.net.navigateToURL; // function import public class NetUtil { /** * Convenience method to load a web page in the browser window without * having to worry about SecurityErrors in various conditions. * * @return true if the url was able to be loaded. */ public static function navigateToURL ( url :String, preferSameWindowOrTab :Boolean = true) :Boolean { var ureq :URLRequest = new URLRequest(url); if (preferSameWindowOrTab) { try { flash.net.navigateToURL(ureq, "_self"); return true; } catch (err :SecurityError) { // ignore; fall back to using a blank window, below... } } // open in a blank window try { flash.net.navigateToURL(ureq); return true; } catch (err :SecurityError) { Log.getLog(NetUtil).warning( "Unable to navigate to URL [e=" + err + "]."); } return false; // failure! } } }
fix comment to reflect reality
fix comment to reflect reality git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4590 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
f04d06dd60b79bb994d3df785cd41e6f35a8089f
utils/peephole.as
utils/peephole.as
/* -*- java-mode -*- */ /* ***** 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 [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * 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 ***** */ /* Generate peephole optimization state tables from a description. peepspec ::= peep* peep ::= pattern guard? action pattern ::= "pattern" ident (";" ident)* eol guard ::= expr action ::= expr (";" expr) expr ::= token+ token ::= any C++ token valid in an expression | $integer.integer ident ::= C++ identifier eol ::= newline or end-of-file The idea is that the identifiers in the pattern are opcode values that are resolved at compile time and which drive the peephole optimizer state machine. The guard is evaluated in case there are side conditions apart from the opcode values; it must be a C++ expression. The action represents individual instruction words that replace the instructions matched by the pattern. The syntax $n.m refers to the m'th word of the n'th matched instruction. The guard will normally be evaluated zero or one times, but it would be good not to depend on that. For example (this one has only one instruction in the action) pattern OP_getlocal ; OP_getlocal ; OP_getlocal guard $0.1 < 1024 && $1.1 < 1024 && $2.1 < 1024 action OP_get2locals ; (($2.1 << 20) | ($1.1 << 10) | $0.1) Continuation lines are allowed, they start with '*' in the first column. Comment lines start with //. Comment lines and blank lines are ignored everywhere before continuation lines are resolved. Restrictions: - The action cannot introduce more words than the instruction originally occupied (it would not be hard to lift this restriction). - Lookupswitch may not appear in these patterns - Any PC-relative branch instruction must be the last in the pattern as well as in the replacement code */ package peephole { import avmplus.*; class Pattern { var P, G, A; function Pattern(P, G, A) { this.P = P; this.G = G; this.A = A; } } function assert(cond) { if (!cond) throw new Error("Assertion failed"); } function cleanup(lines) { var j = 0; var first = true; for ( var i=0, limit=lines.length ; i < limit ; i++ ) { if (/^\s*$/.test(lines[i])) continue; if (/^\s*\/\//.test(lines[i])) continue; assert(/^(\*|pattern\s+|guard\s+|action\s+)/.test(lines[i])); if (lines[i].charAt(0) == '*') { assert(!first); lines[j] += lines[i].substring(1); continue; } lines[j++] = lines[i]; first = false; } lines.length = j; return lines; } function patterns(lines) { var output = []; var P = null; var G = null; var A = null; var res; for ( var i=0, limit=lines.length ; i < limit ; i++ ) { var L = lines[i]; if (P == null) { res = /^pattern\s+(.*)$/.exec(L); assert(res != null); P = res[1].split(/\s*;\s*/); continue; } if (G == null) { res = /^guard\s+(.*)$/.exec(L); if (res != null) { G = res[1]; continue; } } if (A == null) { res = /^action\s+(.*)$/.exec(L); assert(res != null); A = res[1].split(/\s*;\s*/); } assert( P != null && A != null ); output.push(new Pattern(P, G, A)); P = G = A = null; } return output; } function printT(x) { var s = "{"; for ( var i in x ) { if (i == "toString") continue; s += i + ": " + x[i] + ", "; } s += "}"; return s; } function build(patterns) { var T = { toString: function () { return printT(this); } }; for ( var i=0, ilimit=patterns.length ; i < ilimit ; i++ ) { var p = patterns[i]; var container = T; for ( var j=0, jlimit=p.P.length ; j < jlimit ; j++ ) { if (!(p.P[j] in container)) container[p.P[j]] = { toString: function () { return printT(this); } }; container = container[p.P[j]]; } if (!("actions" in container)) container.actions = []; container.actions.push(p); } return T; } function generate(toplevel) { var initial = []; for ( var n in toplevel ) { if (n == "actions" || n == "toString") continue; initial.push({name: n, state: expand(toplevel[n])}); } return initial; } function display(container, sofar) { if (container.actions) { var s = ""; for ( var p=sofar ; p != null ; p=p.next ) s = s + p.name + " "; print(s); } for (var n in container) { if (n == "actions" || n == "toString") continue; display(container[n], { name: n, next: sofar }); } } if (System.argv.length != 2) { print("Usage: peephole inputfile outputfile"); System.exit(1); } var T = build(patterns(cleanup(File.read(System.argv[0]).split("\n")))); print(String(T)); display(T, null); }
/* -*- java-mode -*- */ /* ***** 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 [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * 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 ***** */ /* Generate peephole optimization state tables from a description. peepspec ::= peep* peep ::= pattern guard? action pattern ::= "pattern" ident (";" ident)* eol guard ::= expr action ::= expr (";" expr) expr ::= token+ token ::= any C++ token valid in an expression | $integer.integer ident ::= C++ identifier eol ::= newline or end-of-file Identifiers in the pattern must be opcode names; these are resolved at compile time and the peephole optimizer state machine uses them to transition from one state to another. The guard is evaluated in case there are side conditions apart from the opcode values; the guard must be a C++ expression. The action represents individual instruction words that replace the instructions matched by the pattern; each word should be a C++ expression. The syntax $n.m refers to the m'th word of the n'th matched instruction. It can be used in the guard and action. The guard will be evaluated zero or one times per match. (The current implementation only invokes a guard after longer matches have failed, so zero times is typical - you can't track state machine progress by having side effects in the guard.) For example (this one has only one instruction in the action): pattern OP_getlocal ; OP_getlocal ; OP_getlocal guard $0.1 < 1024 && $1.1 < 1024 && $2.1 < 1024 action OP_get3locals ; ($2.1 << 20) | ($1.1 << 10) | $0.1 Continuation lines are allowed, they start with '*' in the first column. The continuation line, less its '*', is pasted onto the end of the preceding line. Comment lines start with // (possibly preceded by blanks). Comment lines and blank lines are ignored everywhere before continuation lines are resolved. Comments can't follow patterns, guards, or actions on the same line. Restrictions (not checked by this program): - The action cannot introduce more words than the instruction originally occupied (it would not be hard to lift this restriction). - Lookupswitch must not appear in these patterns. - Any PC-relative branch instruction must be the last in the pattern or in the replacement code. */ package peephole { import avmplus.*; class Pattern { var P, G, A; function Pattern(P, G, A) { this.P = P; this.G = G; this.A = A; } } function assert(cond) { if (!cond) throw new Error("Assertion failed"); } function preprocess(lines) { var j = 0; var first = true; for ( var i=0, limit=lines.length ; i < limit ; i++ ) { if (/^\s*$/.test(lines[i])) continue; if (/^\s*\/\//.test(lines[i])) continue; assert(/^(\*|pattern\s+|guard\s+|action\s+)/.test(lines[i])); if (lines[i].charAt(0) == '*') { assert(!first); lines[j] += lines[i].substring(1); continue; } lines[j++] = lines[i]; first = false; } lines.length = j; return lines; } function parse(lines) { var output = []; var P = null; var G = null; var A = null; var res; for ( var i=0, limit=lines.length ; i < limit ; i++ ) { var L = lines[i].replace(/\$([0-9]+)\.([0-9]+)/g, "I[$1][$2]"); if (P == null) { res = /^pattern\s+(.*)$/.exec(L); assert(res != null); P = res[1].split(/\s*;\s*/); continue; } if (G == null) { res = /^guard\s+(.*)$/.exec(L); if (res != null) { G = res[1]; continue; } } if (A == null) { res = /^action\s+(.*)$/.exec(L); assert(res != null); A = res[1].split(/\s*;\s*/); } assert( P != null && A != null ); output.push(new Pattern(P, G, A)); P = G = A = null; } return output; } function build(patterns) { var T = {}; for ( var i=0, ilimit=patterns.length ; i < ilimit ; i++ ) { var p = patterns[i]; var container = T; for ( var j=0, jlimit=p.P.length ; j < jlimit ; j++ ) { if (!(p.P[j] in container)) container[p.P[j]] = {}; container = container[p.P[j]]; } if (!("actions" in container)) container.actions = []; container.actions.push(p); } return T; } function generate(toplevel) { var initial = []; for ( var n in toplevel ) { if (n == "actions" || n == "toString") continue; initial.push({name: n, state: expand(toplevel[n])}); } return initial; } function display(container, sofar) { if (container.actions) { var s = ""; for ( var p=sofar ; p != null ; p=p.next ) s = s + p.name + " "; print(s); } for (var n in container) { if (n == "actions" || n == "toString") continue; display(container[n], { name: n, next: sofar }); } } if (System.argv.length != 2) { print("Usage: peephole inputfile outputfile"); System.exit(1); } var T = build(parse(preprocess(File.read(System.argv[0]).split("\n")))); display(T, null); }
Work in progress
Work in progress
ActionScript
mpl-2.0
pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux
841849f7ce5d4ca072c96d19af8134f3a12d3d27
src/flash/tandem/model/ApplicationModel.as
src/flash/tandem/model/ApplicationModel.as
//////////////////////////////////////////////////////////////////////////////// // // tandem. explore your world. // Copyright (c) 2007–2008 Daniel Gasienica ([email protected]) // // tandem is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // tandem 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with tandem. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////////// package tandem.model { import com.adobe.webapis.flickr.FlickrService; import com.adobe.webapis.flickr.User; import flash.events.EventDispatcher; public class ApplicationModel extends EventDispatcher { //-------------------------------------------------------------------------- // // Class Constants // //-------------------------------------------------------------------------- // If you don't have this file, please complete settings-sample.as and rename it include "../settings.as" //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- public var service : FlickrService public var photos : Array = [] public var user : User = new User() //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function ApplicationModel() { if ( instance != null ) throw new Error( "Hey, I'm a singleton, please don't instantiate me!" ) instance = this } //-------------------------------------------------------------------------- // // Method: Access // //-------------------------------------------------------------------------- private static var instance : ApplicationModel public static function getInstance() : ApplicationModel { if ( instance == null ) instance = new ApplicationModel() return instance } } }
//////////////////////////////////////////////////////////////////////////////// // // tandem. explore your world. // Copyright (c) 2007–2008 Daniel Gasienica ([email protected]) // // tandem is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // tandem 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with tandem. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////////// package tandem.model { import com.adobe.webapis.flickr.FlickrService; import com.adobe.webapis.flickr.User; import flash.events.EventDispatcher; public class ApplicationModel extends EventDispatcher { //-------------------------------------------------------------------------- // // Class Constants // //-------------------------------------------------------------------------- // If you don't have this file, please complete settings-sample.as and rename it include "../settings.as" //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- public var service : FlickrService public var photos : Array = [] public var user : User = new User() //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- /** * Constructor. */ public function ApplicationModel(enforcer:SingletonEnforcer) { if (!enforcer) throw new Error("Can’t instantiate singleton directly." ) instance = this } //-------------------------------------------------------------------------- // // Method: Access // //-------------------------------------------------------------------------- private static var instance : ApplicationModel public static function getInstance() : ApplicationModel { if ( instance == null ) instance = new ApplicationModel(new SingletonEnforcer()) return instance } } } class SingletonEnforcer {}
Fix singleton.
Fix singleton.
ActionScript
agpl-3.0
openzoom/tandem
c812e0d9912f00ed1237bc35d08ddd3080ce9500
frameworks/as/projects/FlexJSUI/src/org/apache/flex/net/dataConverters/LazyCollection.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/net/dataConverters/LazyCollection.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.net.dataConverters { import flash.events.Event; import flash.events.IEventDispatcher; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.data.ICollection; import org.apache.flex.events.EventDispatcher; import org.apache.flex.net.IInputParser; import org.apache.flex.net.IItemConverter; /** * The LazyCollection class implements a collection * whose items require conversion from a source data format * to some other data type. For example, converting * SOAP or JSON to ActionScript data classes. * The Flex SDK used to convert all of the data items * when the source data arrived, which, for very large data sets * or complex data classes, could lock up the user interface. * The lazy collection converts items as they are fetched from * the collection, resulting in significant performance savings * in many cases. Note that, if you need to compute a summary of * data in the collection when the source data arrives, the * computation can still lock up the user interface as you will * have to visit and convert every data item. Of course, it is * possible to compute that summary in a worker or pseudo-thread. * The LazyCollection class is designed to be a bead that attaches * to a data retrieval strand that dispatches an Event.COMPLETE and * has a "data" property that gets passed to the input parser. * * This LazyCollection does not support adding/removing items from * the collection or sending data back to the source. Subclasses * have that additional functionality. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class LazyCollection extends EventDispatcher implements IBead, ICollection { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function LazyCollection() { super(); } private var _inputParser:IInputParser; /** * A lazy collection uses an IInputParser to convert the source data items * into an array of data items. This is required in order to determine * the length of the collection. This conversion happens as the source * data arrives so it needs to be fast to avoid locking up the UI. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get inputParser():IInputParser { return _inputParser; } /** * @private */ public function set inputParser(value:IInputParser):void { if (_inputParser != value) { _inputParser = value; dispatchEvent(new Event("inputParserChanged")); } } private var _itemConverter:IItemConverter; /** * A lazy collection uses an IItemConverter to convert the source data items * into the desired data type. The converter is only called as items * are fetched from the collection. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get itemConverter():IItemConverter { return _itemConverter; } /** * @private */ public function set itemConverter(value:IItemConverter):void { if (_itemConverter != value) { _itemConverter = value; dispatchEvent(new Event("itemConverterChanged")); } } private var _id:String; /** * @copy org.apache.flex.core.UIBase#id * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get id():String { return _id; } /** * @private */ public function set id(value:String):void { if (_id != value) { _id = value; dispatchEvent(new Event("idChanged")); } } private var _strand:IStrand; /** * @copy org.apache.flex.core.UIBase#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(_strand).addEventListener(Event.COMPLETE, completeHandler); } /** * The array of raw data needing conversion. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var rawData:Array; /** * The array of desired data types. This array is sparse and * unconverted items are therefore undefined in the array. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var data:Array; private function completeHandler(event:Event):void { rawData = inputParser.parseItems(_strand["data"]); data = new Array(rawData.length); } /** * Fetches an item from the collection, converting it first if necessary. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getItemAt(index:int):Object { if (data[index] == undefined) { data[index] = itemConverter.convertItem(rawData[index]); } return data[index]; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.net.dataConverters { import flash.events.Event; import flash.events.IEventDispatcher; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.data.ICollection; import org.apache.flex.events.EventDispatcher; import org.apache.flex.net.IInputParser; import org.apache.flex.net.IItemConverter; /** * The LazyCollection class implements a collection * whose items require conversion from a source data format * to some other data type. For example, converting * SOAP or JSON to ActionScript data classes. * The Flex SDK used to convert all of the data items * when the source data arrived, which, for very large data sets * or complex data classes, could lock up the user interface. * The lazy collection converts items as they are fetched from * the collection, resulting in significant performance savings * in many cases. Note that, if you need to compute a summary of * data in the collection when the source data arrives, the * computation can still lock up the user interface as you will * have to visit and convert every data item. Of course, it is * possible to compute that summary in a worker or pseudo-thread. * The LazyCollection class is designed to be a bead that attaches * to a data retrieval strand that dispatches an Event.COMPLETE and * has a "data" property that gets passed to the input parser. * * This LazyCollection does not support adding/removing items from * the collection or sending data back to the source. Subclasses * have that additional functionality. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class LazyCollection extends EventDispatcher implements IBead, ICollection { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function LazyCollection() { super(); } private var _inputParser:IInputParser; /** * A lazy collection uses an IInputParser to convert the source data items * into an array of data items. This is required in order to determine * the length of the collection. This conversion happens as the source * data arrives so it needs to be fast to avoid locking up the UI. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get inputParser():IInputParser { return _inputParser; } /** * @private */ public function set inputParser(value:IInputParser):void { if (_inputParser != value) { _inputParser = value; dispatchEvent(new Event("inputParserChanged")); } } private var _itemConverter:IItemConverter; /** * A lazy collection uses an IItemConverter to convert the source data items * into the desired data type. The converter is only called as items * are fetched from the collection. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get itemConverter():IItemConverter { return _itemConverter; } /** * @private */ public function set itemConverter(value:IItemConverter):void { if (_itemConverter != value) { _itemConverter = value; dispatchEvent(new Event("itemConverterChanged")); } } private var _id:String; /** * @copy org.apache.flex.core.UIBase#id * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get id():String { return _id; } /** * @private */ public function set id(value:String):void { if (_id != value) { _id = value; dispatchEvent(new Event("idChanged")); } } private var _strand:IStrand; /** * @copy org.apache.flex.core.UIBase#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function set strand(value:IStrand):void { _strand = value; IEventDispatcher(_strand).addEventListener(Event.COMPLETE, completeHandler); } /** * The array of raw data needing conversion. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var rawData:Array; /** * The array of desired data types. This array is sparse and * unconverted items are therefore undefined in the array. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ protected var data:Array; private function completeHandler(event:Event):void { rawData = inputParser.parseItems(_strand["data"]); data = new Array(rawData.length); } /** * Fetches an item from the collection, converting it first if necessary. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function getItemAt(index:int):Object { if (data[index] == undefined) { data[index] = itemConverter.convertItem(rawData[index]); } return data[index]; } /** * The number of items. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function get length():int { return rawData ? rawData.length : 0; } } }
add length prop
add length prop
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
9153e6bcab5bce804d5a940db2e33037a11ade47
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import flash.utils.IDataInput; import com.hurlant.util.Hex; import org.denivip.osmf.utility.decrypt.AES; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; [Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] [Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase { private var _syncFound:Boolean; private var _pmtPID:uint; private var _audioPID:uint; private var _videoPID:uint; private var _mp3AudioPID:uint; private var _audioPES:HTTPStreamingMP2PESAudio; private var _videoPES:HTTPStreamingMP2PESVideo; private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio; private var _cachedOutputBytes:ByteArray; private var alternatingYieldCounter:int = 0; private var _key:HTTPStreamingM3U8IndexKey = null; private var _iv:ByteArray = null; private var _decryptBuffer:ByteArray = new ByteArray; // AES-128 specific variables private var _decryptAES:AES = null; public function HTTPStreamingMP2TSFileHandler() { _audioPES = new HTTPStreamingMP2PESAudio; _videoPES = new HTTPStreamingMP2PESVideo; _mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio; } override public function beginProcessFile(seek:Boolean, seekTime:Number):void { _syncFound = false; } override public function get inputBytesNeeded():Number { return _syncFound ? 187 : 1; } override public function processFileSegment(input:IDataInput):ByteArray { var bytesAvailableStart:uint = input.bytesAvailable; var output:ByteArray; if (_cachedOutputBytes !== null) { output = _cachedOutputBytes; _cachedOutputBytes = null; } else { output = new ByteArray(); } while (true) { if(!_syncFound) { if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 16) { if (_decryptBuffer.bytesAvailable < 1) { break; } } else { if (!decryptToBuffer(input, 16)) { break; } } if (_decryptBuffer.readByte() == 0x47) { _syncFound = true; } } } else { if(input.bytesAvailable < 1) break; if(input.readByte() == 0x47) _syncFound = true; } } else { _syncFound = false; var packet:ByteArray = new ByteArray(); if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 176) { if (_decryptBuffer.bytesAvailable < 187) { break; } } else { var bytesLeft:uint = input.bytesAvailable - 176; if (bytesLeft > 0 && bytesLeft < 15) { if (!decryptToBuffer(input, input.bytesAvailable)) { break; } } else { if (!decryptToBuffer(input, 176)) { break; } } } _decryptBuffer.readBytes(packet, 0, 187); } } else { if(input.bytesAvailable < 187) break; input.readBytes(packet, 0, 187); } var result:ByteArray = processPacket(packet); if (result !== null) { output.writeBytes(result); } if (bytesAvailableStart - input.bytesAvailable > 10000) { alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03; if (alternatingYieldCounter /*& 0x01 === 1*/) { _cachedOutputBytes = output; return null; } break; } } } output.position = 0; return output.length === 0 ? null : output; } private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{ if (_key) { // Clear buffer if (_decryptBuffer.bytesAvailable == 0) { _decryptBuffer.clear(); } if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) { if (!_decryptAES) { _decryptAES = new AES(_key.key); _decryptAES.pad = "none"; _decryptAES.iv = _iv; } // Save buffer position var currentPosition:uint = _decryptBuffer.position; _decryptBuffer.position += _decryptBuffer.bytesAvailable; // Save block to decrypt var decrypt:ByteArray = new ByteArray; input.readBytes(decrypt, 0, blockSize); // Save new IV from ciphertext var newIv:ByteArray = new ByteArray; decrypt.position += (decrypt.bytesAvailable-16); decrypt.readBytes(newIv, 0, 16); decrypt.position = 0; // Decrypt if (input.bytesAvailable == 0) { _decryptAES.pad = "pkcs7"; } _decryptAES.decrypt(decrypt); decrypt.position = 0; // Write into buffer _decryptBuffer.writeBytes(decrypt); _decryptBuffer.position = currentPosition; // Update AES IV _decryptAES.iv = newIv; return true; } } return false; } override public function endProcessFile(input:IDataInput):ByteArray { _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; return null; } public function resetCache():void{ _cachedOutputBytes = null; alternatingYieldCounter = 0; _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set initialOffset(offset:Number):void{ offset *= 1000; // convert to ms _videoPES.initialTimestamp = offset; _audioPES.initialTimestamp = offset; _mp3audioPES.initialTimestamp = offset; } public function set key(key:HTTPStreamingM3U8IndexKey):void { _key = key; if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set iv(iv:String):void { if (iv) { _iv = Hex.toArray(iv); } } private function processPacket(packet:ByteArray):ByteArray { // decode rest of transport stream prefix (after the 0x47 flag byte) // top of second byte var value:uint = packet.readUnsignedByte(); //var tei:Boolean = Boolean(value & 0x80); // error indicator var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication //var tpri:Boolean = Boolean(value & 0x20); // transport priority indication // bottom of second byte and all of third value <<= 8; value += packet.readUnsignedByte(); var pid:uint = value & 0x1fff; // packet ID // fourth byte value = packet.readUnsignedByte(); //var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field var hasPD:Boolean = Boolean(value & 0x10); // has payload data //var ccount:uint = value & 0x0f; // continuty count // technically hasPD without hasAF is an error, see spec if(hasAF) { // process adaptation field // don't care about flags // don't care about clocks here var af:uint = packet.readUnsignedByte(); packet.position += af; // skip to end } return hasPD ? processES(pid, pusi, packet) : null; } private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray { var output:ByteArray = null; if(pid == 0) // PAT { if(pusi) processPAT(packet); } else if(pid == _pmtPID) { if(pusi) processPMT(packet); } else if(pid == _audioPID) { output = _audioPES.processES(pusi, packet); } else if(pid == _videoPID) { output = _videoPES.processES(pusi, packet); } else if(pid == _mp3AudioPID) { output = _mp3audioPES.processES(pusi, packet); } return output; } private function processPAT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint packet.readUnsignedByte(); // tableID:uint var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits packet.position += 5; // skip tsid + version/cni + sec# + last sec# remaining -= 5; while(remaining > 4) { packet.readUnsignedShort(); // program number _pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits remaining -= 4; //return; // immediately after reading the first pmt ID, if we don't we get the LAST one } // and ignore the CRC (4 bytes) } private function processPMT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint var tableID:uint = packet.readUnsignedByte(); if (tableID != 0x02) { CONFIG::LOGGING { logger.warn("PAT pointed to PMT that isn't PMT"); } return; // don't try to parse it } var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID remaining -= 7; var piLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 2; packet.position += piLen; // skip program info remaining -= piLen; while(remaining > 4) { var type:uint = packet.readUnsignedByte(); var pid:uint = packet.readUnsignedShort() & 0x1fff; var esiLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 5; packet.position += esiLen; remaining -= esiLen; switch(type) { case 0x1b: // H.264 video _videoPID = pid; break; case 0x0f: // AAC Audio / ADTS _audioPID = pid; break; case 0x03: // MP3 Audio (3 & 4) case 0x04: _mp3AudioPID = pid; break; default: CONFIG::LOGGING { logger.error("unsupported type "+type.toString(16)+" in PMT"); } break; } } // and ignore CRC } override public function flushFileSegment(input:IDataInput):ByteArray { var flvBytes:ByteArray = new ByteArray(); var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true); var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true); if(flvBytesVideo) flvBytes.readBytes(flvBytesVideo); if(flvBytesAudio) flvBytes.readBytes(flvBytesAudio); return flvBytes; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger; } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import flash.utils.IDataInput; import com.hurlant.util.Hex; import org.denivip.osmf.utility.decrypt.AES; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; [Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] [Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase { private var _syncFound:Boolean; private var _pmtPID:uint; private var _audioPID:uint; private var _videoPID:uint; private var _mp3AudioPID:uint; private var _audioPES:HTTPStreamingMP2PESAudio; private var _videoPES:HTTPStreamingMP2PESVideo; private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio; private var _cachedOutputBytes:ByteArray; private var alternatingYieldCounter:int = 0; private var _key:HTTPStreamingM3U8IndexKey = null; private var _iv:ByteArray = null; private var _decryptBuffer:ByteArray = new ByteArray; // AES-128 specific variables private var _decryptAES:AES = null; public function HTTPStreamingMP2TSFileHandler() { _audioPES = new HTTPStreamingMP2PESAudio; _videoPES = new HTTPStreamingMP2PESVideo; _mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio; } override public function beginProcessFile(seek:Boolean, seekTime:Number):void { _syncFound = false; } override public function get inputBytesNeeded():Number { return _syncFound ? 187 : 1; } override public function processFileSegment(input:IDataInput):ByteArray { var bytesAvailableStart:uint = input.bytesAvailable; var output:ByteArray; if (_cachedOutputBytes !== null) { output = _cachedOutputBytes; _cachedOutputBytes = null; } else { output = new ByteArray(); } while (true) { if(!_syncFound) { if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 16) { if (_decryptBuffer.bytesAvailable < 1) { break; } } else { if (!decryptToBuffer(input, 16)) { break; } } if (_decryptBuffer.readByte() == 0x47) { _syncFound = true; } } } else { if(input.bytesAvailable < 1) break; if(input.readByte() == 0x47) _syncFound = true; } } else { var packet:ByteArray = new ByteArray(); if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 176) { if (_decryptBuffer.bytesAvailable < 187) { break; } } else { var bytesLeft:uint = input.bytesAvailable - 176; if (bytesLeft > 0 && bytesLeft < 15) { if (!decryptToBuffer(input, input.bytesAvailable)) { break; } } else { if (!decryptToBuffer(input, 176)) { break; } } } _decryptBuffer.readBytes(packet, 0, 187); } } else { if(input.bytesAvailable < 187) break; input.readBytes(packet, 0, 187); } _syncFound = false; var result:ByteArray = processPacket(packet); if (result !== null) { output.writeBytes(result); } if (bytesAvailableStart - input.bytesAvailable > 10000) { alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03; if (alternatingYieldCounter /*& 0x01 === 1*/) { _cachedOutputBytes = output; return null; } break; } } } output.position = 0; return output.length === 0 ? null : output; } private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{ if (_key) { // Clear buffer if (_decryptBuffer.bytesAvailable == 0) { _decryptBuffer.clear(); } if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) { if (!_decryptAES) { _decryptAES = new AES(_key.key); _decryptAES.pad = "none"; _decryptAES.iv = _iv; } // Save buffer position var currentPosition:uint = _decryptBuffer.position; _decryptBuffer.position += _decryptBuffer.bytesAvailable; // Save block to decrypt var decrypt:ByteArray = new ByteArray; input.readBytes(decrypt, 0, blockSize); // Save new IV from ciphertext var newIv:ByteArray = new ByteArray; decrypt.position += (decrypt.bytesAvailable-16); decrypt.readBytes(newIv, 0, 16); decrypt.position = 0; // Decrypt if (input.bytesAvailable == 0) { _decryptAES.pad = "pkcs7"; } _decryptAES.decrypt(decrypt); decrypt.position = 0; // Write into buffer _decryptBuffer.writeBytes(decrypt); _decryptBuffer.position = currentPosition; // Update AES IV _decryptAES.iv = newIv; return true; } } return false; } override public function endProcessFile(input:IDataInput):ByteArray { _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; return null; } public function resetCache():void{ _cachedOutputBytes = null; alternatingYieldCounter = 0; _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set initialOffset(offset:Number):void{ offset *= 1000; // convert to ms _videoPES.initialTimestamp = offset; _audioPES.initialTimestamp = offset; _mp3audioPES.initialTimestamp = offset; } public function set key(key:HTTPStreamingM3U8IndexKey):void { _key = key; if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set iv(iv:String):void { if (iv) { _iv = Hex.toArray(iv); } } private function processPacket(packet:ByteArray):ByteArray { // decode rest of transport stream prefix (after the 0x47 flag byte) // top of second byte var value:uint = packet.readUnsignedByte(); //var tei:Boolean = Boolean(value & 0x80); // error indicator var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication //var tpri:Boolean = Boolean(value & 0x20); // transport priority indication // bottom of second byte and all of third value <<= 8; value += packet.readUnsignedByte(); var pid:uint = value & 0x1fff; // packet ID // fourth byte value = packet.readUnsignedByte(); //var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field var hasPD:Boolean = Boolean(value & 0x10); // has payload data //var ccount:uint = value & 0x0f; // continuty count // technically hasPD without hasAF is an error, see spec if(hasAF) { // process adaptation field // don't care about flags // don't care about clocks here var af:uint = packet.readUnsignedByte(); packet.position += af; // skip to end } return hasPD ? processES(pid, pusi, packet) : null; } private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray { var output:ByteArray = null; if(pid == 0) // PAT { if(pusi) processPAT(packet); } else if(pid == _pmtPID) { if(pusi) processPMT(packet); } else if(pid == _audioPID) { output = _audioPES.processES(pusi, packet); } else if(pid == _videoPID) { output = _videoPES.processES(pusi, packet); } else if(pid == _mp3AudioPID) { output = _mp3audioPES.processES(pusi, packet); } return output; } private function processPAT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint packet.readUnsignedByte(); // tableID:uint var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits packet.position += 5; // skip tsid + version/cni + sec# + last sec# remaining -= 5; while(remaining > 4) { packet.readUnsignedShort(); // program number _pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits remaining -= 4; //return; // immediately after reading the first pmt ID, if we don't we get the LAST one } // and ignore the CRC (4 bytes) } private function processPMT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint var tableID:uint = packet.readUnsignedByte(); if (tableID != 0x02) { CONFIG::LOGGING { logger.warn("PAT pointed to PMT that isn't PMT"); } return; // don't try to parse it } var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID remaining -= 7; var piLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 2; packet.position += piLen; // skip program info remaining -= piLen; while(remaining > 4) { var type:uint = packet.readUnsignedByte(); var pid:uint = packet.readUnsignedShort() & 0x1fff; var esiLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 5; packet.position += esiLen; remaining -= esiLen; switch(type) { case 0x1b: // H.264 video _videoPID = pid; break; case 0x0f: // AAC Audio / ADTS _audioPID = pid; break; case 0x03: // MP3 Audio (3 & 4) case 0x04: _mp3AudioPID = pid; break; default: CONFIG::LOGGING { logger.error("unsupported type "+type.toString(16)+" in PMT"); } break; } } // and ignore CRC } override public function flushFileSegment(input:IDataInput):ByteArray { var flvBytes:ByteArray = new ByteArray(); var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true); var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true); if(flvBytesVideo) flvBytes.readBytes(flvBytesVideo); if(flvBytesAudio) flvBytes.readBytes(flvBytesAudio); return flvBytes; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger; } } }
Fix bug where syncFound was flagged as false incorrectly
Fix bug where syncFound was flagged as false incorrectly This was causing byte-level sync issues with throttled (and potentially other) streams
ActionScript
isc
denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin
8bea26c515c7bd6b4487cc2f4b8fcc1545c1cbde
skin-src/goplayer/AbstractStandardSkin.as
skin-src/goplayer/AbstractStandardSkin.as
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 bufferingIndicator.mouseEnabled = false volumeSliderFillMaxHeight = volumeSliderFill.height volumeSliderFillMinY = volumeSliderFill.y volumeSlider.mouseChildren = false volumeSlider.buttonMode = true volumeSliderThumbGuide.visible = false volumeSlider.visible = false chrome.visible = enableChrome addEventListeners() } override public function update() : void { super.update() chromeFader.targetAlpha = showChrome ? 1 : 0 upperPanel.visible = showTitle titleField.text = titleText 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 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 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(playButton, handlePlayButtonClicked) onclick(pauseButton, handlePauseButtonClicked) onclick(muteButton, handleMuteButtonClicked) onclick(unmuteButton, handleUnmuteButtonClicked) onclick(enableFullscreenButton, handleEnableFullscreenButtonClicked) onmousemove(seekBar, handleSeekBarMouseMove) onrollover(seekBar, handleSeekBarRollOver) onrollout(seekBar, handleSeekBarRollOut) onclick(seekBar, handleSeekBarClicked) onmousedown(volumeSlider, handleVolumeSliderMouseDown) onrollover(muteButton, handleVolumeButtonRollOver) onrollover(unmuteButton, handleVolumeButtonRollOver) onrollover(chrome, handleChromeRollOver) onrollout(chrome, handleChromeRollOut) onclick(rightTimeField, handleRightTimeFieldClicked) } private function handleChromeRollOver() : void { hoveringChrome = true, update() } private function handleChromeRollOut() : void { hoveringChrome = false, update() } private function handleRightTimeFieldClicked() : void { showRemainingTime = !showRemainingTime } private function handlePlayButtonClicked() : void { backend.handleUserPlay() } private function handlePauseButtonClicked() : void { backend.handleUserPause() } private function handleMuteButtonClicked() : void { backend.handleUserMute() } private function handleUnmuteButtonClicked() : void { backend.handleUserUnmute() } private function handleEnableFullscreenButtonClicked() : void { backend.handleUserToggleFullscreen() } 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 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 handleVolumeButtonRollOver() : void { volumeSlider.visible = true } // ----------------------------------------------------- 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 chrome() : Sprite { return undefinedPart("chrome") } protected function get upperPanel() : Sprite { return undefinedPart("upperPanel") } protected function get titleField() : TextField { return undefinedPart("titleField") } protected function get controlBar() : Sprite { return undefinedPart("controlBar") } 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") } } }
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 bufferingIndicator.mouseEnabled = false volumeSliderFillMaxHeight = volumeSliderFill.height volumeSliderFillMinY = volumeSliderFill.y volumeSlider.mouseChildren = false volumeSlider.buttonMode = true volumeSliderThumbGuide.visible = false volumeSlider.visible = false chrome.visible = enableChrome addEventListeners() } override public function update() : void { super.update() chromeFader.targetAlpha = showChrome ? 1 : 0 upperPanel.visible = showTitle titleField.text = titleText 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 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(playButton, handlePlayButtonClicked) onclick(pauseButton, handlePauseButtonClicked) onclick(muteButton, handleMuteButtonClicked) onclick(unmuteButton, handleUnmuteButtonClicked) onclick(enableFullscreenButton, handleEnableFullscreenButtonClicked) onmousemove(seekBar, handleSeekBarMouseMove) onrollover(seekBar, handleSeekBarRollOver) onrollout(seekBar, handleSeekBarRollOut) onclick(seekBar, handleSeekBarClicked) onmousedown(volumeSlider, handleVolumeSliderMouseDown) onrollover(muteButton, handleVolumeButtonRollOver) onrollover(unmuteButton, handleVolumeButtonRollOver) onrollover(chrome, handleChromeRollOver) onrollout(chrome, handleChromeRollOut) onclick(rightTimeField, handleRightTimeFieldClicked) } private function handleChromeRollOver() : void { hoveringChrome = true, update() } private function handleChromeRollOut() : void { hoveringChrome = false, update() } private function handleRightTimeFieldClicked() : void { showRemainingTime = !showRemainingTime } private function handlePlayButtonClicked() : void { backend.handleUserPlay() } private function handlePauseButtonClicked() : void { backend.handleUserPause() } private function handleMuteButtonClicked() : void { backend.handleUserMute() } private function handleUnmuteButtonClicked() : void { backend.handleUserUnmute() } private function handleEnableFullscreenButtonClicked() : void { backend.handleUserToggleFullscreen() } 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 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 handleVolumeButtonRollOver() : void { volumeSlider.visible = true } // ----------------------------------------------------- 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 chrome() : Sprite { return undefinedPart("chrome") } protected function get upperPanel() : Sprite { return undefinedPart("upperPanel") } protected function get titleField() : TextField { return undefinedPart("titleField") } protected function get controlBar() : Sprite { return undefinedPart("controlBar") } 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") } } }
Fix bug: Seek bar groove width was not being updated.
Fix bug: Seek bar groove width was not being updated.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
af35764ee88591e9d07cb96836288ccdc2b9af44
src/aerys/minko/type/animation/timeline/MatrixLinearTimeline.as
src/aerys/minko/type/animation/timeline/MatrixLinearTimeline.as
package aerys.minko.type.animation.timeline { import aerys.minko.scene.node.IScene; import aerys.minko.type.math.Matrix4x4; public class MatrixLinearTimeline implements ITimeline { private var _targetName : String; private var _propertyName : String; private var _timeTable : Vector.<uint> private var _values : Vector.<Matrix4x4>; public function get targetName() : String { return _targetName; } public function get propertyName() : String { return _propertyName; } public function get duration() : uint { return _timeTable[_timeTable.length - 1]; } public function MatrixLinearTimeline(targetName : String, propertyName : String, timeTable : Vector.<uint>, matrices : Vector.<Matrix4x4>) { _targetName = targetName; _propertyName = propertyName; _timeTable = timeTable; _values = matrices; } public function updateAt(t : uint, scene : IScene) : void { var timeId : uint = getIndexForTime(t); var timeCount : uint = _timeTable.length; // change matrix value. var out : Matrix4x4 = scene[_propertyName]; if (!out) throw new Error(_propertyName + ' property was not found on scene node named ' + _targetName); if (timeId == 0) { Matrix4x4.copy(_values[0], out); } else if (timeId == timeCount) { Matrix4x4.copy(_values[timeCount - 1], out); } else { var previousTime : Number = _timeTable[timeId - 1]; var nextTime : Number = _timeTable[timeId]; var interpolationRatio : Number = (t - previousTime) / (nextTime - previousTime); var previousMatrix : Matrix4x4 = _values[timeId - 1]; var nextMatrix : Matrix4x4 = _values[timeId]; Matrix4x4.copy(previousMatrix, out); previousMatrix.interpolateTo(nextMatrix, 1 - interpolationRatio); } } private function getIndexForTime(t : uint) : uint { // use a dichotomy to find the current frame in the time table. var timeCount : uint = _timeTable.length; var bottomTimeId : uint = 0; var upperTimeId : uint = timeCount; var timeId : uint; while (upperTimeId - bottomTimeId > 1) { timeId = (bottomTimeId + upperTimeId) >> 1; if (_timeTable[timeId] > t) upperTimeId = timeId; else bottomTimeId = timeId; } return upperTimeId; } public function clone() : ITimeline { return new MatrixLinearTimeline(_targetName, _propertyName, _timeTable.slice(), _values.slice()); } public function reverse() : void { _timeTable.reverse(); _values.reverse(); } } }
package aerys.minko.type.animation.timeline { import aerys.minko.scene.node.IScene; import aerys.minko.type.math.Matrix4x4; public class MatrixLinearTimeline implements ITimeline { private var _targetName : String; private var _propertyName : String; private var _timeTable : Vector.<uint> private var _values : Vector.<Matrix4x4>; public function get targetName() : String { return _targetName; } public function get propertyName() : String { return _propertyName; } public function get duration() : uint { return _timeTable[_timeTable.length - 1]; } public function MatrixLinearTimeline(targetName : String, propertyName : String, timeTable : Vector.<uint>, matrices : Vector.<Matrix4x4>) { _targetName = targetName; _propertyName = propertyName; _timeTable = timeTable; _values = matrices; } public function updateAt(t : uint, scene : IScene) : void { var timeId : uint = getIndexForTime(t); var timeCount : uint = _timeTable.length; // change matrix value. var out : Matrix4x4 = scene[_propertyName]; if (!out) throw new Error(_propertyName + ' property was not found on scene node named ' + _targetName); if (timeId == 0) { Matrix4x4.copy(_values[0], out); } else if (timeId == timeCount) { Matrix4x4.copy(_values[timeCount - 1], out); } else { var previousTime : Number = _timeTable[timeId - 1]; var nextTime : Number = _timeTable[timeId]; var interpolationRatio : Number = (t - previousTime) / (nextTime - previousTime); var previousMatrix : Matrix4x4 = _values[timeId - 1]; var nextMatrix : Matrix4x4 = _values[timeId]; Matrix4x4.copy(previousMatrix, out); out.interpolateTo(nextMatrix, 1 - interpolationRatio); } } private function getIndexForTime(t : uint) : uint { // use a dichotomy to find the current frame in the time table. var timeCount : uint = _timeTable.length; var bottomTimeId : uint = 0; var upperTimeId : uint = timeCount; var timeId : uint; while (upperTimeId - bottomTimeId > 1) { timeId = (bottomTimeId + upperTimeId) >> 1; if (_timeTable[timeId] > t) upperTimeId = timeId; else bottomTimeId = timeId; } return upperTimeId; } public function clone() : ITimeline { return new MatrixLinearTimeline(_targetName, _propertyName, _timeTable.slice(), _values.slice()); } public function reverse() : void { _timeTable.reverse(); _values.reverse(); } } }
Fix bug in MatrixLinearTimeline that was messing with animations over the time
Fix bug in MatrixLinearTimeline that was messing with animations over the time
ActionScript
mit
aerys/minko-as3
29db853197aea86c7852a81e652afbf613126bf9
src/org/mangui/hls/model/Level.as
src/org/mangui/hls/model/Level.as
package org.mangui.hls.model { CONFIG::LOGGING { import org.mangui.hls.utils.Log; } import org.mangui.hls.utils.PTS; /** HLS streaming quality level. **/ public class Level { /** audio only Level ? **/ public var audio : Boolean; /** Level Bitrate. **/ public var bitrate : Number; /** Level Name. **/ public var name : String; /** level index **/ public var index : int = 0; /** video width (from playlist) **/ public var width : int; /** video height (from playlist) **/ public var height : int; /** URL of this bitrate level (for M3U8). **/ public var url : String; /** Level fragments **/ public var fragments : Vector.<Fragment>; /** min sequence number from M3U8. **/ public var start_seqnum : int; /** max sequence number from M3U8. **/ public var end_seqnum : int; /** target fragment duration from M3U8 **/ public var targetduration : Number; /** average fragment duration **/ public var averageduration : Number; /** Total duration **/ public var duration : Number; /** Audio Identifier **/ public var audio_stream_id : String; /** Create the quality level. **/ public function Level() : void { this.fragments = new Vector.<Fragment>(); }; /** Return the Fragment before a given time position. **/ public function getFragmentBeforePosition(position : Number) : Fragment { if (fragments[0].data.valid && position < fragments[0].start_time) return fragments[0]; var len : int = fragments.length; for (var i : int = 0; i < len; i++) { /* check whether fragment contains current position */ if (fragments[i].data.valid && fragments[i].start_time <= position && fragments[i].start_time + fragments[i].duration > position) { return fragments[i]; } } return fragments[len - 1]; }; /** Return the sequence number from a given program date **/ public function getSeqNumFromProgramDate(program_date : Number) : int { if (program_date < fragments[0].program_date) return -1; var len : int = fragments.length; for (var i : int = 0; i < len; i++) { /* check whether fragment contains current position */ if (fragments[i].data.valid && fragments[i].program_date <= program_date && fragments[i].program_date + 1000 * fragments[i].duration > program_date) { return (start_seqnum + i); } } return -1; }; /** Return the sequence number nearest a PTS **/ public function getSeqNumNearestPTS(pts : Number, continuity : int) : Number { if (fragments.length == 0) return -1; var firstIndex : Number = getFirstIndexfromContinuity(continuity); if (firstIndex == -1 || isNaN(fragments[firstIndex].data.pts_start_computed)) return -1; var lastIndex : Number = getLastIndexfromContinuity(continuity); for (var i : int = firstIndex; i <= lastIndex; i++) { var frag : Fragment = fragments[i]; /* check nearest fragment */ if ( frag.data.valid && (frag.duration >= 0) && (Math.abs(frag.data.pts_start_computed - pts) < Math.abs(frag.data.pts_start_computed + 1000 * frag.duration - pts))) { return frag.seqnum; } } // requested PTS above max PTS of this level return Number.POSITIVE_INFINITY; }; public function getLevelstartPTS() : Number { if (fragments.length) return fragments[0].data.pts_start_computed; else return NaN; } /** Return the fragment index from fragment sequence number **/ public function getFragmentfromSeqNum(seqnum : Number) : Fragment { var index : int = getIndexfromSeqNum(seqnum); if (index != -1) { return fragments[index]; } else { return null; } } /** Return the fragment index from fragment sequence number **/ private function getIndexfromSeqNum(seqnum : int) : int { if (seqnum >= start_seqnum && seqnum <= end_seqnum) { return (fragments.length - 1 - (end_seqnum - seqnum)); } else { return -1; } } /** Return the first index matching with given continuity counter **/ private function getFirstIndexfromContinuity(continuity : int) : int { // look for first fragment matching with given continuity index var len : int = fragments.length; for (var i : int = 0; i < len; i++) { if (fragments[i].continuity == continuity) return i; } return -1; } /** Return the first seqnum matching with given continuity counter **/ public function getFirstSeqNumfromContinuity(continuity : int) : Number { var index : int = getFirstIndexfromContinuity(continuity); if (index == -1) { return Number.NEGATIVE_INFINITY; } return fragments[index].seqnum; } /** Return the last seqnum matching with given continuity counter **/ public function getLastSeqNumfromContinuity(continuity : int) : Number { var index : int = getLastIndexfromContinuity(continuity); if (index == -1) { return Number.NEGATIVE_INFINITY; } return fragments[index].seqnum; } /** Return the last index matching with given continuity counter **/ private function getLastIndexfromContinuity(continuity : Number) : int { var firstIndex : int = getFirstIndexfromContinuity(continuity); if (firstIndex == -1) return -1; var lastIndex : int = firstIndex; // look for first fragment matching with given continuity index for (var i : int = firstIndex; i < fragments.length; i++) { if (fragments[i].continuity == continuity) lastIndex = i; else break; } return lastIndex; } /** set Fragments **/ public function updateFragments(_fragments : Vector.<Fragment>) : void { var idx_with_metrics : int = -1; var len : int = _fragments.length; var frag : Fragment; // update PTS from previous fragments for (var i : int = 0; i < len; i++) { frag = getFragmentfromSeqNum(_fragments[i].seqnum); if (frag != null && !isNaN(frag.data.pts_start)) { _fragments[i].data = frag.data; idx_with_metrics = i; } } updateFragmentsProgramDate(_fragments); fragments = _fragments; start_seqnum = _fragments[0].seqnum; end_seqnum = _fragments[len - 1].seqnum; if (idx_with_metrics != -1) { // if at least one fragment contains PTS info, recompute PTS information for all fragments updateFragment(fragments[idx_with_metrics].seqnum, true, fragments[idx_with_metrics].data.pts_start, fragments[idx_with_metrics].data.pts_start + 1000 * fragments[idx_with_metrics].duration); } else { duration = _fragments[len - 1].start_time + _fragments[len - 1].duration; } averageduration = duration / len; } private function updateFragmentsProgramDate(_fragments : Vector.<Fragment>) : void { var len : int = _fragments.length; var continuity : int; var program_date : Number; var frag : Fragment; for (var i : int = 0; i < len; i++) { frag = _fragments[i]; if (frag.continuity != continuity) { continuity = frag.continuity; program_date = 0; } if (frag.program_date) { program_date = frag.program_date + 1000 * frag.duration; } else if (program_date) { frag.program_date = program_date; } } } private function _updatePTS(from_index : int, to_index : int) : void { // CONFIG::LOGGING { // Log.info("updateFragmentPTS from/to:" + from_index + "/" + to_index); // } var frag_from : Fragment = fragments[from_index]; var frag_to : Fragment = fragments[to_index]; if (frag_from.data.valid && frag_to.data.valid) { if (!isNaN(frag_to.data.pts_start)) { // we know PTS[to_index] frag_to.data.pts_start_computed = frag_to.data.pts_start; /* normalize computed PTS value based on known PTS value. * this is to avoid computing wrong fragment duration in case of PTS looping */ var from_pts : Number = PTS.normalize(frag_to.data.pts_start, frag_from.data.pts_start_computed); /* update fragment duration. it helps to fix drifts between playlist reported duration and fragment real duration */ if (to_index > from_index) { frag_from.duration = (frag_to.data.pts_start - from_pts) / 1000; CONFIG::LOGGING { if (frag_from.duration < 0) { Log.error("negative duration computed for " + frag_from + ", there should be some duration drift between playlist and fragment!"); } } } else { frag_to.duration = ( from_pts - frag_to.data.pts_start) / 1000; CONFIG::LOGGING { if (frag_to.duration < 0) { Log.error("negative duration computed for " + frag_to + ", there should be some duration drift between playlist and fragment!"); } } } } else { // we dont know PTS[to_index] if (to_index > from_index) frag_to.data.pts_start_computed = frag_from.data.pts_start_computed + 1000 * frag_from.duration; else frag_to.data.pts_start_computed = frag_from.data.pts_start_computed - 1000 * frag_to.duration; } } } public function updateFragment(seqnum : Number, valid : Boolean, min_pts : Number = 0, max_pts : Number = 0) : Number { // CONFIG::LOGGING { // Log.info("updatePTS : seqnum/min/max:" + seqnum + '/' + min_pts + '/' + max_pts); // } // get fragment from seqnum var fragIdx : int = getIndexfromSeqNum(seqnum); if (fragIdx != -1) { var frag : Fragment = fragments[fragIdx]; // update fragment start PTS + duration if (valid) { frag.data.pts_start = min_pts; frag.data.pts_start_computed = min_pts; frag.duration = (max_pts - min_pts) / 1000; } else { frag.duration = 0; } frag.data.valid = valid; // CONFIG::LOGGING { // Log.info("SN["+fragments[fragIdx].seqnum+"]:pts/duration:" + fragments[fragIdx].start_pts_computed + "/" + fragments[fragIdx].duration); // } // adjust fragment PTS/duration from seqnum-1 to frag 0 for (var i : int = fragIdx; i > 0 && fragments[i - 1].continuity == frag.continuity; i--) { _updatePTS(i, i - 1); // CONFIG::LOGGING { // Log.info("SN["+fragments[i-1].seqnum+"]:pts/duration:" + fragments[i-1].start_pts_computed + "/" + fragments[i-1].duration); // } } // adjust fragment PTS/duration from seqnum to last frag for (i = fragIdx; i < fragments.length - 1 && fragments[i + 1].continuity == frag.continuity; i++) { _updatePTS(i, i + 1); // CONFIG::LOGGING { // Log.info("SN["+fragments[i+1].seqnum+"]:pts/duration:" + fragments[i+1].start_pts_computed + "/" + fragments[i+1].duration); // } } // second, adjust fragment offset var start_time_offset : Number = fragments[0].start_time; var len : int = fragments.length; for (i = 0; i < len; i++) { fragments[i].start_time = start_time_offset; start_time_offset += fragments[i].duration; // CONFIG::LOGGING { // Log.info("SN["+fragments[i].seqnum+"]:start_time/continuity/pts/duration:" + fragments[i].start_time + "/" + fragments[i].continuity + "/"+ fragments[i].start_pts_computed + "/" + fragments[i].duration); // } } duration = start_time_offset; return frag.start_time; } else { return 0; } } } }
package org.mangui.hls.model { CONFIG::LOGGING { import org.mangui.hls.utils.Log; } import org.mangui.hls.utils.PTS; /** HLS streaming quality level. **/ public class Level { /** audio only Level ? **/ public var audio : Boolean; /** Level Bitrate. **/ public var bitrate : Number; /** Level Name. **/ public var name : String; /** level index **/ public var index : int = 0; /** video width (from playlist) **/ public var width : int; /** video height (from playlist) **/ public var height : int; /** URL of this bitrate level (for M3U8). **/ public var url : String; /** Level fragments **/ public var fragments : Vector.<Fragment>; /** min sequence number from M3U8. **/ public var start_seqnum : int; /** max sequence number from M3U8. **/ public var end_seqnum : int; /** target fragment duration from M3U8 **/ public var targetduration : Number; /** average fragment duration **/ public var averageduration : Number; /** Total duration **/ public var duration : Number; /** Audio Identifier **/ public var audio_stream_id : String; /** Create the quality level. **/ public function Level() : void { this.fragments = new Vector.<Fragment>(); }; /** Return the Fragment before a given time position. **/ public function getFragmentBeforePosition(position : Number) : Fragment { if (fragments[0].data.valid && position < fragments[0].start_time) return fragments[0]; var len : int = fragments.length; for (var i : int = 0; i < len; i++) { /* check whether fragment contains current position */ if (fragments[i].data.valid && fragments[i].start_time <= position && fragments[i].start_time + fragments[i].duration > position) { return fragments[i]; } } return fragments[len - 1]; }; /** Return the sequence number from a given program date **/ public function getSeqNumFromProgramDate(program_date : Number) : int { if (program_date < fragments[0].program_date) return -1; var len : int = fragments.length; for (var i : int = 0; i < len; i++) { /* check whether fragment contains current position */ if (fragments[i].data.valid && fragments[i].program_date <= program_date && fragments[i].program_date + 1000 * fragments[i].duration > program_date) { return (start_seqnum + i); } } return -1; }; /** Return the sequence number nearest a PTS **/ public function getSeqNumNearestPTS(pts : Number, continuity : int) : Number { if (fragments.length == 0) return -1; var firstIndex : Number = getFirstIndexfromContinuity(continuity); if (firstIndex == -1 || isNaN(fragments[firstIndex].data.pts_start_computed)) return -1; var lastIndex : Number = getLastIndexfromContinuity(continuity); for (var i : int = firstIndex; i <= lastIndex; i++) { var frag : Fragment = fragments[i]; /* check nearest fragment */ if ( frag.data.valid && (frag.duration >= 0) && (Math.abs(frag.data.pts_start_computed - pts) < Math.abs(frag.data.pts_start_computed + 1000 * frag.duration - pts))) { return frag.seqnum; } } // requested PTS above max PTS of this level return Number.POSITIVE_INFINITY; }; public function getLevelstartPTS() : Number { if (fragments.length) return fragments[0].data.pts_start_computed; else return NaN; } /** Return the fragment index from fragment sequence number **/ public function getFragmentfromSeqNum(seqnum : Number) : Fragment { var index : int = getIndexfromSeqNum(seqnum); if (index != -1) { return fragments[index]; } else { return null; } } /** Return the fragment index from fragment sequence number **/ private function getIndexfromSeqNum(seqnum : int) : int { if (seqnum >= start_seqnum && seqnum <= end_seqnum) { return (fragments.length - 1 - (end_seqnum - seqnum)); } else { return -1; } } /** Return the first index matching with given continuity counter **/ private function getFirstIndexfromContinuity(continuity : int) : int { // look for first fragment matching with given continuity index var len : int = fragments.length; for (var i : int = 0; i < len; i++) { if (fragments[i].continuity == continuity) return i; } return -1; } /** Return the first seqnum matching with given continuity counter **/ public function getFirstSeqNumfromContinuity(continuity : int) : Number { var index : int = getFirstIndexfromContinuity(continuity); if (index == -1) { return Number.NEGATIVE_INFINITY; } return fragments[index].seqnum; } /** Return the last seqnum matching with given continuity counter **/ public function getLastSeqNumfromContinuity(continuity : int) : Number { var index : int = getLastIndexfromContinuity(continuity); if (index == -1) { return Number.NEGATIVE_INFINITY; } return fragments[index].seqnum; } /** Return the last index matching with given continuity counter **/ private function getLastIndexfromContinuity(continuity : Number) : int { var firstIndex : int = getFirstIndexfromContinuity(continuity); if (firstIndex == -1) return -1; var lastIndex : int = firstIndex; // look for first fragment matching with given continuity index for (var i : int = firstIndex; i < fragments.length; i++) { if (fragments[i].continuity == continuity) lastIndex = i; else break; } return lastIndex; } /** set Fragments **/ public function updateFragments(_fragments : Vector.<Fragment>) : void { var idx_with_metrics : int = -1; var len : int = _fragments.length; var frag : Fragment; // update PTS from previous fragments for (var i : int = 0; i < len; i++) { frag = getFragmentfromSeqNum(_fragments[i].seqnum); if (frag != null && !isNaN(frag.data.pts_start)) { _fragments[i].data = frag.data; idx_with_metrics = i; } } updateFragmentsProgramDate(_fragments); fragments = _fragments; start_seqnum = _fragments[0].seqnum; end_seqnum = _fragments[len - 1].seqnum; if (idx_with_metrics != -1) { // if at least one fragment contains PTS info, recompute PTS information for all fragments updateFragment(fragments[idx_with_metrics].seqnum, true, fragments[idx_with_metrics].data.pts_start, fragments[idx_with_metrics].data.pts_start + 1000 * fragments[idx_with_metrics].duration); } else { duration = _fragments[len - 1].start_time + _fragments[len - 1].duration; } averageduration = duration / len; } private function updateFragmentsProgramDate(_fragments : Vector.<Fragment>) : void { var len : int = _fragments.length; var continuity : int; var program_date : Number; var frag : Fragment; for (var i : int = 0; i < len; i++) { frag = _fragments[i]; if (frag.continuity != continuity) { continuity = frag.continuity; program_date = 0; } if (frag.program_date) { program_date = frag.program_date + 1000 * frag.duration; } else if (program_date) { frag.program_date = program_date; } } } private function _updatePTS(from_index : int, to_index : int) : void { // CONFIG::LOGGING { // Log.info("updateFragmentPTS from/to:" + from_index + "/" + to_index); // } var frag_from : Fragment = fragments[from_index]; var frag_to : Fragment = fragments[to_index]; if (frag_from.data.valid && frag_to.data.valid) { if (!isNaN(frag_to.data.pts_start)) { // we know PTS[to_index] frag_to.data.pts_start_computed = frag_to.data.pts_start; /* normalize computed PTS value based on known PTS value. * this is to avoid computing wrong fragment duration in case of PTS looping */ var from_pts : Number = PTS.normalize(frag_to.data.pts_start, frag_from.data.pts_start_computed); /* update fragment duration. it helps to fix drifts between playlist reported duration and fragment real duration */ if (to_index > from_index) { frag_from.duration = (frag_to.data.pts_start - from_pts) / 1000; CONFIG::LOGGING { if (frag_from.duration < 0) { Log.error("negative duration computed for " + frag_from + ", there should be some duration drift between playlist and fragment!"); } } } else { frag_to.duration = ( from_pts - frag_to.data.pts_start) / 1000; CONFIG::LOGGING { if (frag_to.duration < 0) { Log.error("negative duration computed for " + frag_to + ", there should be some duration drift between playlist and fragment!"); } } } } else { // we dont know PTS[to_index] if (to_index > from_index) frag_to.data.pts_start_computed = frag_from.data.pts_start_computed + 1000 * frag_from.duration; else frag_to.data.pts_start_computed = frag_from.data.pts_start_computed - 1000 * frag_to.duration; } } } public function updateFragment(seqnum : Number, valid : Boolean, min_pts : Number = 0, max_pts : Number = 0) : Number { // CONFIG::LOGGING { // Log.info("updatePTS : seqnum/min/max:" + seqnum + '/' + min_pts + '/' + max_pts); // } // get fragment from seqnum var fragIdx : int = getIndexfromSeqNum(seqnum); if (fragIdx != -1) { var frag : Fragment = fragments[fragIdx]; // update fragment start PTS + duration if (valid) { frag.data.pts_start = min_pts; frag.data.pts_start_computed = min_pts; frag.duration = (max_pts - min_pts) / 1000; } else { frag.duration = 0; } frag.data.valid = valid; // CONFIG::LOGGING { // Log.info("SN["+fragments[fragIdx].seqnum+"]:pts/duration:" + fragments[fragIdx].start_pts_computed + "/" + fragments[fragIdx].duration); // } // adjust fragment PTS/duration from seqnum-1 to frag 0 for (var i : int = fragIdx; i > 0 && fragments[i - 1].continuity == frag.continuity; i--) { _updatePTS(i, i - 1); // CONFIG::LOGGING { // Log.info("SN["+fragments[i-1].seqnum+"]:pts/duration:" + fragments[i-1].start_pts_computed + "/" + fragments[i-1].duration); // } } // adjust fragment PTS/duration from seqnum to last frag for (i = fragIdx; i < fragments.length - 1 && fragments[i + 1].continuity == frag.continuity; i++) { _updatePTS(i, i + 1); // CONFIG::LOGGING { // Log.info("SN["+fragments[i+1].seqnum+"]:pts/duration:" + fragments[i+1].start_pts_computed + "/" + fragments[i+1].duration); // } } // second, adjust fragment offset var start_time_offset : Number = fragments[0].start_time; var len : int = fragments.length; for (i = 0; i < len; i++) { fragments[i].start_time = start_time_offset; start_time_offset += fragments[i].duration; // CONFIG::LOGGING { // Log.info("SN["+fragments[i].seqnum+"]:start_time/continuity/pts/duration:" + fragments[i].start_time + "/" + fragments[i].continuity + "/"+ fragments[i].start_pts_computed + "/" + fragments[i].duration); // } } duration = start_time_offset; return frag.start_time; } else { CONFIG::LOGGING { Log.error("updateFragment:seqnum " + seqnum + "not found!"); } return 0; } } } }
improve error logs
improve error logs
ActionScript
mpl-2.0
viktorot/flashls,hola/flashls,School-Improvement-Network/flashls,ryanhefner/flashls,stevemayhew/flashls,Peer5/flashls,Boxie5/flashls,JulianPena/flashls,suuhas/flashls,JulianPena/flashls,codex-corp/flashls,aevange/flashls,Boxie5/flashls,aevange/flashls,mangui/flashls,tedconf/flashls,fixedmachine/flashls,dighan/flashls,dighan/flashls,thdtjsdn/flashls,loungelogic/flashls,ryanhefner/flashls,Peer5/flashls,aevange/flashls,viktorot/flashls,suuhas/flashls,School-Improvement-Network/flashls,stevemayhew/flashls,NicolasSiver/flashls,loungelogic/flashls,fixedmachine/flashls,codex-corp/flashls,ryanhefner/flashls,vidible/vdb-flashls,neilrackett/flashls,suuhas/flashls,aevange/flashls,Peer5/flashls,vidible/vdb-flashls,clappr/flashls,tedconf/flashls,viktorot/flashls,School-Improvement-Network/flashls,Corey600/flashls,stevemayhew/flashls,thdtjsdn/flashls,NicolasSiver/flashls,ryanhefner/flashls,clappr/flashls,jlacivita/flashls,mangui/flashls,Peer5/flashls,hola/flashls,stevemayhew/flashls,suuhas/flashls,neilrackett/flashls,jlacivita/flashls,Corey600/flashls
36085fe6d5abe00d2b742a843071f64020cebca4
collect-flex/collect-flex-client/src/main/flex/org/openforis/collect/presenter/DetailPresenter.as
collect-flex/collect-flex-client/src/main/flex/org/openforis/collect/presenter/DetailPresenter.as
package org.openforis.collect.presenter { /** * * @author S. Ricci * */ import flash.events.Event; import flash.events.MouseEvent; import mx.collections.IList; import mx.events.IndexChangedEvent; import mx.rpc.AsyncResponder; import mx.rpc.events.ResultEvent; import org.openforis.collect.Application; import org.openforis.collect.client.ClientFactory; import org.openforis.collect.client.DataClient; import org.openforis.collect.event.UIEvent; import org.openforis.collect.metamodel.proxy.AttributeDefinitionProxy; import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy; import org.openforis.collect.metamodel.proxy.ModelVersionProxy; import org.openforis.collect.model.proxy.RecordProxy; import org.openforis.collect.ui.UIBuilder; import org.openforis.collect.ui.component.detail.FormContainer; import org.openforis.collect.ui.view.DetailView; public class DetailPresenter extends AbstractPresenter { private var _dataClient:DataClient; private var _view:DetailView; public function DetailPresenter(view:DetailView) { this._view = view; this._dataClient = ClientFactory.dataClient; super(); } override internal function initEventListeners():void { _view.backToListButton.addEventListener(MouseEvent.CLICK, backToListButtonClickHandler); eventDispatcher.addEventListener(UIEvent.ACTIVE_RECORD_CHANGED, activeRecordChangedListener); } /** * Active record changed * */ internal function activeRecordChangedListener(event:UIEvent):void { var activeRecord:RecordProxy = Application.activeRecord; var activeRootEntity:EntityDefinitionProxy = Application.activeRootEntity; var keyValues:String = ""; var keyAttributeDefinitions:IList = activeRootEntity.keyAttributeDefinitions; for each (var k:AttributeDefinitionProxy in keyAttributeDefinitions) { keyValues += activeRecord.rootEntityKeys.get(k.name); } var version:ModelVersionProxy = activeRecord.version; _view.keyAttributeValuesText.text = keyValues; _view.rootEntityDefinitionText.text = activeRootEntity.getLabelText(); _view.formVersionText.text = version.getLabelText(); var form:FormContainer = null; if (_view.formsContainer.contatinsForm(version,activeRootEntity)){ _view.currentState = DetailView.EDIT_STATE; form = _view.formsContainer.getForm(version, activeRootEntity); } else { //build form _view.currentState = DetailView.LOADING_STATE; form = UIBuilder.buildForm(activeRootEntity, version); _view.formsContainer.addForm(form, version, activeRootEntity); _view.currentState = DetailView.EDIT_STATE; } form = _view.formsContainer.setActiveForm(version, activeRootEntity); form.record = activeRecord; } /** * Back to list * */ protected function backToListButtonClickHandler(event:Event):void { _dataClient.clearActiveRecord(new AsyncResponder(clearActiveRecordHandler, faultHandler)); } internal function clearActiveRecordHandler(event:ResultEvent, token:Object = null):void { var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST); eventDispatcher.dispatchEvent(uiEvent); } } }
package org.openforis.collect.presenter { /** * * @author S. Ricci * */ import flash.events.Event; import flash.events.MouseEvent; import mx.collections.IList; import mx.events.IndexChangedEvent; import mx.rpc.AsyncResponder; import mx.rpc.events.ResultEvent; import org.openforis.collect.Application; import org.openforis.collect.client.ClientFactory; import org.openforis.collect.client.DataClient; import org.openforis.collect.event.UIEvent; import org.openforis.collect.metamodel.proxy.AttributeDefinitionProxy; import org.openforis.collect.metamodel.proxy.EntityDefinitionProxy; import org.openforis.collect.metamodel.proxy.ModelVersionProxy; import org.openforis.collect.model.proxy.RecordProxy; import org.openforis.collect.ui.UIBuilder; import org.openforis.collect.ui.component.detail.FormContainer; import org.openforis.collect.ui.view.DetailView; public class DetailPresenter extends AbstractPresenter { private var _dataClient:DataClient; private var _view:DetailView; public function DetailPresenter(view:DetailView) { this._view = view; this._dataClient = ClientFactory.dataClient; super(); } override internal function initEventListeners():void { _view.backToListButton.addEventListener(MouseEvent.CLICK, backToListButtonClickHandler); eventDispatcher.addEventListener(UIEvent.ACTIVE_RECORD_CHANGED, activeRecordChangedListener); } /** * Active record changed * */ internal function activeRecordChangedListener(event:UIEvent):void { var activeRecord:RecordProxy = Application.activeRecord; var activeRootEntity:EntityDefinitionProxy = Application.activeRootEntity; var keyValues:String = ""; var keyAttributeDefinitions:IList = activeRootEntity.keyAttributeDefinitions; for each (var k:AttributeDefinitionProxy in keyAttributeDefinitions) { keyValues += activeRecord.rootEntityKeys.get(k.name); } var version:ModelVersionProxy = activeRecord.version; _view.keyAttributeValuesText.text = keyValues; _view.rootEntityDefinitionText.text = activeRootEntity.getLabelText(); _view.formVersionText.text = version.getLabelText(); var form:FormContainer = null; if (_view.formsContainer.contatinsForm(version,activeRootEntity)){ _view.currentState = DetailView.EDIT_STATE; form = _view.formsContainer.getForm(version, activeRootEntity); } else { //build form _view.currentState = DetailView.LOADING_STATE; form = UIBuilder.buildForm(activeRootEntity, version); _view.formsContainer.addForm(form, version, activeRootEntity); _view.currentState = DetailView.EDIT_STATE; } form = _view.formsContainer.setActiveForm(version, activeRootEntity); form.record = activeRecord; } /** * Back to list * */ protected function backToListButtonClickHandler(event:Event):void { _dataClient.clearActiveRecord(new AsyncResponder(clearActiveRecordHandler, faultHandler)); } internal function clearActiveRecordHandler(event:ResultEvent, token:Object = null):void { Application.activeRecord = null; var uiEvent:UIEvent = new UIEvent(UIEvent.BACK_TO_LIST); eventDispatcher.dispatchEvent(uiEvent); } } }
clean active record when going back to list
clean active record when going back to list
ActionScript
mit
openforis/collect,openforis/collect,openforis/collect,openforis/collect
aff208070b7e98353074325b5fc501421b1d7209
gb/joypad.as
gb/joypad.as
import "./cpu"; import "./mmu"; import "./machine"; import "./bits"; struct Joypad { CPU: *cpu.CPU; // Select Select_Button: bool; Select_Direction: bool; // State State_Start: bool; State_A: bool; State_B: bool; State_Select: bool; State_Up: bool; State_Down: bool; State_Left: bool; State_Right: bool; } implement Joypad { def New(cpu_: *cpu.CPU): Self { let j: Joypad; j.CPU = cpu_; return j; } def Reset(self, mode: machine.MachineMode) { // Input starts off disabled on CGB (but enabled on GB) self.Select_Button = (mode == machine.MODE_GB); self.Select_Direction = (mode == machine.MODE_GB); self.State_Start = false; self.State_A = false; self.State_B = false; self.State_Select = false; self.State_Up = false; self.State_Down = false; self.State_Left = false; self.State_Right = false; } def OnKey(self, which: uint32, isPressed: bool) { if which == 40 { // START => ENTER (US Keyboard) self.State_Start = isPressed; } else if which == 29 { // A => Z (US Keyboard) self.State_A = isPressed; } else if which == 27 { // B => X (US Keyboard) self.State_B = isPressed; } else if which == 225 { // SELECT => LEFT SHIFT (US Keyboard) self.State_Select = isPressed; } else if which == 82 { // UP => UP ARROW (US Keyboard) self.State_Up = isPressed; } else if which == 81 { // DOWN => DOWN ARROW (US Keyboard) self.State_Down = isPressed; } else if which == 80 { // LEFT => LEFT ARROW (US Keyboard) self.State_Left = isPressed; } else if which == 79 { // RIGHT => RIGHT ARROW (US Keyboard) self.State_Right = isPressed; } } def OnKeyPress(self, which: uint32) { self.OnKey(which, true); } def OnKeyRelease(self, which: uint32) { self.OnKey(which, false); } def Read(self, address: uint16, ptr: *uint8): bool { *ptr = if address == 0xFF00 { // P1 – Joypad (R/W) // Bit 7 - Not used // Bit 6 - Not used // Bit 5 - P15 Select Button Keys (0=Select) // Bit 4 - P14 Select Direction Keys (0=Select) // Bit 3 - P13 Input Down or Start (0=Pressed) (Read Only) // Bit 2 - P12 Input Up or Select (0=Pressed) (Read Only) // Bit 1 - P11 Input Left or Button B (0=Pressed) (Read Only) // Bit 0 - P10 Input Right or Button A (0=Pressed) (Read Only) // NOTE: This is backwards logic to me. 0 = True ? ( bits.Bit(true, 7) | bits.Bit(true, 6) | bits.Bit(not self.Select_Button, 5) | bits.Bit(not self.Select_Direction, 4) | bits.Bit(not ((self.Select_Button and self.State_Start) or (self.Select_Direction and self.State_Down)), 3) | bits.Bit(not ((self.Select_Button and self.State_Select) or (self.Select_Direction and self.State_Up)), 2) | bits.Bit(not ((self.Select_Button and self.State_B) or (self.Select_Direction and self.State_Left)), 1) | bits.Bit(not ((self.Select_Button and self.State_A) or (self.Select_Direction and self.State_Right)), 0) ); } else { return false; }; return true; } def Write(self, address: uint16, value: uint8): bool { if address == 0xFF00 { self.Select_Button = not bits.Test(value, 5); self.Select_Direction = not bits.Test(value, 4); } else { return false; } return true; } def AsMemoryController(self, this: *Joypad): mmu.MemoryController { let mc: mmu.MemoryController; mc.Read = MCRead; mc.Write = MCWrite; mc.Data = this as *uint8; mc.Release = MCRelease; return mc; } } def MCRelease(this: *mmu.MemoryController) { // Do nothing } def MCRead(this: *mmu.MemoryController, address: uint16, value: *uint8): bool { return (this.Data as *Joypad).Read(address, value); } def MCWrite(this: *mmu.MemoryController, address: uint16, value: uint8): bool { return (this.Data as *Joypad).Write(address, value); }
import "./cpu"; import "./mmu"; import "./machine"; import "./bits"; struct Joypad { CPU: *cpu.CPU; // Select Select_Button: bool; Select_Direction: bool; // State State_Start: bool; State_A: bool; State_B: bool; State_Select: bool; State_Up: bool; State_Down: bool; State_Left: bool; State_Right: bool; } implement Joypad { def New(cpu_: *cpu.CPU): Self { let j: Joypad; j.CPU = cpu_; return j; } def Reset(self, mode: machine.MachineMode) { // Input starts off disabled on CGB (but enabled on GB) self.Select_Button = (mode == machine.MODE_GB); self.Select_Direction = (mode == machine.MODE_GB); self.State_Start = false; self.State_A = false; self.State_B = false; self.State_Select = false; self.State_Up = false; self.State_Down = false; self.State_Left = false; self.State_Right = false; } def OnKey(self, which: uint32, isPressed: bool) { if which == 40 { // START => ENTER (US Keyboard) self.State_Start = isPressed; } else if which == 29 { // A => Z (US Keyboard) self.State_A = isPressed; } else if which == 27 { // B => X (US Keyboard) self.State_B = isPressed; } else if which == 225 { // SELECT => LEFT SHIFT (US Keyboard) self.State_Select = isPressed; } else if which == 82 { // UP => UP ARROW (US Keyboard) self.State_Up = isPressed; } else if which == 81 { // DOWN => DOWN ARROW (US Keyboard) self.State_Down = isPressed; } else if which == 80 { // LEFT => LEFT ARROW (US Keyboard) self.State_Left = isPressed; } else if which == 79 { // RIGHT => RIGHT ARROW (US Keyboard) self.State_Right = isPressed; } } def OnKeyPress(self, which: uint32) { self.OnKey(which, true); } def OnKeyRelease(self, which: uint32) { self.OnKey(which, false); } def Read(self, address: uint16, ptr: *uint8): bool { *ptr = if address == 0xFF00 { // P1 – Joypad (R/W) // Bit 7 - Not used // Bit 6 - Not used // Bit 5 - P15 Select Button Keys (0=Select) // Bit 4 - P14 Select Direction Keys (0=Select) // Bit 3 - P13 Input Down or Start (0=Pressed) (Read Only) // Bit 2 - P12 Input Up or Select (0=Pressed) (Read Only) // Bit 1 - P11 Input Left or Button B (0=Pressed) (Read Only) // Bit 0 - P10 Input Right or Button A (0=Pressed) (Read Only) ( bits.Bit(true, 7) | bits.Bit(true, 6) | bits.Bit(not self.Select_Button, 5) | bits.Bit(not self.Select_Direction, 4) | bits.Bit(not ((self.Select_Button and self.State_Start) or (self.Select_Direction and self.State_Down)), 3) | bits.Bit(not ((self.Select_Button and self.State_Select) or (self.Select_Direction and self.State_Up)), 2) | bits.Bit(not ((self.Select_Button and self.State_B) or (self.Select_Direction and self.State_Left)), 1) | bits.Bit(not ((self.Select_Button and self.State_A) or (self.Select_Direction and self.State_Right)), 0) ); } else { return false; }; return true; } def Write(self, address: uint16, value: uint8): bool { if address == 0xFF00 { self.Select_Button = not bits.Test(value, 5); self.Select_Direction = not bits.Test(value, 4); } else { return false; } return true; } def AsMemoryController(self, this: *Joypad): mmu.MemoryController { let mc: mmu.MemoryController; mc.Read = MCRead; mc.Write = MCWrite; mc.Data = this as *uint8; mc.Release = MCRelease; return mc; } } def MCRelease(this: *mmu.MemoryController) { // Do nothing } def MCRead(this: *mmu.MemoryController, address: uint16, value: *uint8): bool { return (this.Data as *Joypad).Read(address, value); } def MCWrite(this: *mmu.MemoryController, address: uint16, value: uint8): bool { return (this.Data as *Joypad).Write(address, value); }
remove unneeded comment
:fire: remove unneeded comment
ActionScript
mit
arrow-lang/wadatsumi
79e646611ba35f38060b3dd42fbfcfaeb92253ee
flash-src/WebSocket.as
flash-src/WebSocket.as
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/> // License: New BSD License // Reference: http://dev.w3.org/html5/websockets/ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31 package { import flash.display.*; import flash.events.*; import flash.external.*; import flash.net.*; import flash.system.*; import flash.utils.*; import mx.core.*; import mx.controls.*; import mx.events.*; import mx.utils.*; import com.adobe.net.proxies.RFC2817Socket; import com.gsolo.encryption.MD5; [Event(name="message", type="WebSocketMessageEvent")] [Event(name="open", type="flash.events.Event")] [Event(name="close", type="flash.events.Event")] [Event(name="error", type="flash.events.Event")] [Event(name="stateChange", type="WebSocketStateEvent")] public class WebSocket extends EventDispatcher { private static var CONNECTING:int = 0; private static var OPEN:int = 1; private static var CLOSING:int = 2; private static var CLOSED:int = 3; private var socket:RFC2817Socket; private var main:WebSocketMain; private var url:String; private var scheme:String; private var host:String; private var port:uint; private var path:String; private var origin:String; private var protocol:String; private var buffer:ByteArray = new ByteArray(); private var headerState:int = 0; private var readyState:int = CONNECTING; private var bufferedAmount:int = 0; private var headers:String; private var noiseChars:Array; private var expectedDigest:String; public function WebSocket( main:WebSocketMain, url:String, protocol:String, proxyHost:String = null, proxyPort:int = 0, headers:String = null) { this.main = main; initNoiseChars(); this.url = url; var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?$/); if (!m) main.fatal("SYNTAX_ERR: invalid url: " + url); this.scheme = m[1]; this.host = m[2]; this.port = parseInt(m[4] || "80"); this.path = m[5] || "/"; this.origin = main.getOrigin(); this.protocol = protocol; // if present and not the empty string, headers MUST end with \r\n // headers should be zero or more complete lines, for example // "Header1: xxx\r\nHeader2: yyyy\r\n" this.headers = headers; socket = new RFC2817Socket(); // if no proxy information is supplied, it acts like a normal Socket // @see RFC2817Socket::connect if (proxyHost != null && proxyPort != 0){ socket.setProxyInfo(proxyHost, proxyPort); } socket.addEventListener(Event.CLOSE, onSocketClose); socket.addEventListener(Event.CONNECT, onSocketConnect); socket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError); socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError); socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData); socket.connect(host, port); } public function send(data:String):int { if (readyState == OPEN) { socket.writeByte(0x00); socket.writeUTFBytes(decodeURIComponent(data)); socket.writeByte(0xff); socket.flush(); main.log("sent: " + data); return -1; } else if (readyState == CLOSED) { var bytes:ByteArray = new ByteArray(); bytes.writeUTFBytes(decodeURIComponent(data)); bufferedAmount += bytes.length; // not sure whether it should include \x00 and \xff // We use return value to let caller know bufferedAmount because we cannot fire // stateChange event here which causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. return bufferedAmount; } else { main.fatal("INVALID_STATE_ERR: invalid state"); return 0; } } public function close():void { main.log("close"); try { socket.close(); } catch (ex:Error) { } readyState = CLOSED; // We don't fire any events here because it causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. // We do something equivalent in JavaScript WebSocket#close instead. } public function getReadyState():int { return readyState; } public function getBufferedAmount():int { return bufferedAmount; } private function onSocketConnect(event:Event):void { main.log("connected"); var hostValue:String = host + (port == 80 ? "" : ":" + port); var cookie:String = ""; if (main.getCallerHost() == host) { cookie = ExternalInterface.call("function(){return document.cookie}"); } var key1:String = generateKey(); var key2:String = generateKey(); var key3:String = generateKey3(); expectedDigest = getSecurityDigest(key1, key2, key3); var opt:String = ""; if (protocol) opt += "WebSocket-Protocol: " + protocol + "\r\n"; // if caller passes additional headers they must end with "\r\n" if (headers) opt += headers; var req:String = StringUtil.substitute( "GET {0} HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Host: {1}\r\n" + "Origin: {2}\r\n" + "Cookie: {3}\r\n" + "Sec-WebSocket-Key1: {4}\r\n" + "Sec-WebSocket-Key2: {5}\r\n" + "{6}" + "\r\n", path, hostValue, origin, cookie, key1, key2, opt); main.log("request header:\n" + req); socket.writeUTFBytes(req); main.log("sent key3: " + key3); writeBytes(key3); socket.flush(); } private function onSocketClose(event:Event):void { main.log("closed"); readyState = CLOSED; notifyStateChange(); dispatchEvent(new Event("close")); } private function onSocketIoError(event:IOErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (IoError)"; } else { message = "error communicating with Web Socket server at " + url + " (IoError)"; } onError(message); } private function onSocketSecurityError(event:SecurityErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (SecurityError)\n" + "make sure the server is running and Flash socket policy file is correctly placed"; } else { message = "error communicating with Web Socket server at " + url + " (SecurityError)"; } onError(message); } private function onError(message:String):void { var state:int = readyState; if (state == CLOSED) return; main.error(message); close(); notifyStateChange(); dispatchEvent(new Event(state == CONNECTING ? "close" : "error")); } private function onSocketData(event:ProgressEvent):void { var pos:int = buffer.length; socket.readBytes(buffer, pos); for (; pos < buffer.length; ++pos) { if (headerState < 4) { // try to find "\r\n\r\n" if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) { ++headerState; } else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) { ++headerState; } else { headerState = 0; } if (headerState == 4) { var headerStr:String = buffer.readUTFBytes(pos + 1); main.log("response header:\n" + headerStr); if (!validateHeader(headerStr)) return; makeBufferCompact(); pos = -1; } } else if (headerState == 4) { if (pos == 15) { var replyDigest:String = readBytes(buffer, 16); main.log("reply digest: " + replyDigest); if (replyDigest != expectedDigest) { onError("digest doesn't match: " + replyDigest + " != " + expectedDigest); return; } headerState = 5; makeBufferCompact(); pos = -1; readyState = OPEN; notifyStateChange(); dispatchEvent(new Event("open")); } } else { if (buffer[pos] == 0xff) { if (buffer.readByte() != 0x00) { onError("data must start with \\x00"); return; } var data:String = buffer.readUTFBytes(pos - 1); main.log("received: " + data); dispatchEvent(new WebSocketMessageEvent("message", encodeURIComponent(data))); buffer.readByte(); makeBufferCompact(); pos = -1; } } } } private function validateHeader(headerStr:String):Boolean { var lines:Array = headerStr.split(/\r\n/); if (!lines[0].match(/^HTTP\/1.1 101 /)) { onError("bad response: " + lines[0]); return false; } var header:Object = {}; for (var i:int = 1; i < lines.length; ++i) { if (lines[i].length == 0) continue; var m:Array = lines[i].match(/^(\S+): (.*)$/); if (!m) { onError("failed to parse response header line: " + lines[i]); return false; } header[m[1]] = m[2]; } if (header["Upgrade"] != "WebSocket") { onError("invalid Upgrade: " + header["Upgrade"]); return false; } if (header["Connection"] != "Upgrade") { onError("invalid Connection: " + header["Connection"]); return false; } var resOrigin:String = header["Sec-WebSocket-Origin"].toLowerCase(); if (resOrigin != origin) { onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'"); return false; } if (protocol && header["Sec-WebSocket-Protocol"] != protocol) { onError("protocol doesn't match: '" + header["WebSocket-Protocol"] + "' != '" + protocol + "'"); return false; } return true; } private function makeBufferCompact():void { if (buffer.position == 0) return; var nextBuffer:ByteArray = new ByteArray(); buffer.readBytes(nextBuffer); buffer = nextBuffer; } private function notifyStateChange():void { dispatchEvent(new WebSocketStateEvent("stateChange", readyState, bufferedAmount)); } private function initNoiseChars():void { noiseChars = new Array(); for (var i:int = 0x21; i <= 0x2f; ++i) { noiseChars.push(String.fromCharCode(i)); } for (var j:int = 0x3a; j <= 0x7a; ++j) { noiseChars.push(String.fromCharCode(j)); } } private function generateKey():String { var spaces:uint = randomInt(1, 12); var max:uint = uint.MAX_VALUE / spaces; var number:uint = randomInt(0, max); var key:String = (number * spaces).toString(); var noises:int = randomInt(1, 12); var pos:int; for (var i:int = 0; i < noises; ++i) { var char:String = noiseChars[randomInt(0, noiseChars.length - 1)]; pos = randomInt(0, key.length); key = key.substr(0, pos) + char + key.substr(pos); } for (var j:int = 0; j < spaces; ++j) { pos = randomInt(1, key.length - 1); key = key.substr(0, pos) + " " + key.substr(pos); } return key; } private function generateKey3():String { var key3:String = ""; for (var i:int = 0; i < 8; ++i) { key3 += String.fromCharCode(randomInt(0, 255)); } return key3; } private function getSecurityDigest(key1:String, key2:String, key3:String):String { var bytes1:String = keyToBytes(key1); var bytes2:String = keyToBytes(key2); return MD5.rstr_md5(bytes1 + bytes2 + key3); } private function keyToBytes(key:String):String { var keyNum:uint = parseInt(key.replace(/[^\d]/g, "")); var spaces:uint = 0; for (var i:int = 0; i < key.length; ++i) { if (key.charAt(i) == " ") ++spaces; } var resultNum:uint = keyNum / spaces; var bytes:String = ""; for (var j:int = 3; j >= 0; --j) { bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff); } return bytes; } private function writeBytes(bytes:String):void { for (var i:int = 0; i < bytes.length; ++i) { socket.writeByte(bytes.charCodeAt(i)); } } private function readBytes(buffer:ByteArray, numBytes:int):String { var bytes:String = ""; for (var i:int = 0; i < numBytes; ++i) { // & 0xff is to make \x80-\xff positive number. bytes += String.fromCharCode(buffer.readByte() & 0xff); } return bytes; } private function randomInt(min:uint, max:uint):uint { return min + Math.floor(Math.random() * (Number(max) - min + 1)); } // for debug private function dumpBytes(bytes:String):void { var output:String = ""; for (var i:int = 0; i < bytes.length; ++i) { output += bytes.charCodeAt(i).toString() + ", "; } main.log(output); } } }
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/> // License: New BSD License // Reference: http://dev.w3.org/html5/websockets/ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31 package { import flash.display.*; import flash.events.*; import flash.external.*; import flash.net.*; import flash.system.*; import flash.utils.*; import mx.core.*; import mx.controls.*; import mx.events.*; import mx.utils.*; import com.adobe.net.proxies.RFC2817Socket; import com.gsolo.encryption.MD5; [Event(name="message", type="WebSocketMessageEvent")] [Event(name="open", type="flash.events.Event")] [Event(name="close", type="flash.events.Event")] [Event(name="error", type="flash.events.Event")] [Event(name="stateChange", type="WebSocketStateEvent")] public class WebSocket extends EventDispatcher { private static var CONNECTING:int = 0; private static var OPEN:int = 1; private static var CLOSING:int = 2; private static var CLOSED:int = 3; private var socket:RFC2817Socket; private var main:WebSocketMain; private var url:String; private var scheme:String; private var host:String; private var port:uint; private var path:String; private var origin:String; private var protocol:String; private var buffer:ByteArray = new ByteArray(); private var headerState:int = 0; private var readyState:int = CONNECTING; private var bufferedAmount:int = 0; private var headers:String; private var noiseChars:Array; private var expectedDigest:String; public function WebSocket( main:WebSocketMain, url:String, protocol:String, proxyHost:String = null, proxyPort:int = 0, headers:String = null) { this.main = main; initNoiseChars(); this.url = url; var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?$/); if (!m) main.fatal("SYNTAX_ERR: invalid url: " + url); this.scheme = m[1]; this.host = m[2]; this.port = parseInt(m[4] || "80"); this.path = m[5] || "/"; this.origin = main.getOrigin(); this.protocol = protocol; // if present and not the empty string, headers MUST end with \r\n // headers should be zero or more complete lines, for example // "Header1: xxx\r\nHeader2: yyyy\r\n" this.headers = headers; socket = new RFC2817Socket(); // if no proxy information is supplied, it acts like a normal Socket // @see RFC2817Socket::connect if (proxyHost != null && proxyPort != 0){ socket.setProxyInfo(proxyHost, proxyPort); } socket.addEventListener(Event.CLOSE, onSocketClose); socket.addEventListener(Event.CONNECT, onSocketConnect); socket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError); socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError); socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData); socket.connect(host, port); } public function send(data:String):int { if (readyState == OPEN) { socket.writeByte(0x00); socket.writeUTFBytes(decodeURIComponent(data)); socket.writeByte(0xff); socket.flush(); main.log("sent: " + data); return -1; } else if (readyState == CLOSED) { var bytes:ByteArray = new ByteArray(); bytes.writeUTFBytes(decodeURIComponent(data)); bufferedAmount += bytes.length; // not sure whether it should include \x00 and \xff // We use return value to let caller know bufferedAmount because we cannot fire // stateChange event here which causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. return bufferedAmount; } else { main.fatal("INVALID_STATE_ERR: invalid state"); return 0; } } public function close():void { main.log("close"); try { socket.close(); } catch (ex:Error) { } readyState = CLOSED; // We don't fire any events here because it causes weird error: // > You are trying to call recursively into the Flash Player which is not allowed. // We do something equivalent in JavaScript WebSocket#close instead. } public function getReadyState():int { return readyState; } public function getBufferedAmount():int { return bufferedAmount; } private function onSocketConnect(event:Event):void { main.log("connected"); var hostValue:String = host + (port == 80 ? "" : ":" + port); var cookie:String = ""; if (main.getCallerHost() == host) { cookie = ExternalInterface.call("function(){return document.cookie}"); } var key1:String = generateKey(); var key2:String = generateKey(); var key3:String = generateKey3(); expectedDigest = getSecurityDigest(key1, key2, key3); var opt:String = ""; if (protocol) opt += "WebSocket-Protocol: " + protocol + "\r\n"; // if caller passes additional headers they must end with "\r\n" if (headers) opt += headers; var req:String = StringUtil.substitute( "GET {0} HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Host: {1}\r\n" + "Origin: {2}\r\n" + "Cookie: {3}\r\n" + "Sec-WebSocket-Key1: {4}\r\n" + "Sec-WebSocket-Key2: {5}\r\n" + "{6}" + "\r\n", path, hostValue, origin, cookie, key1, key2, opt); main.log("request header:\n" + req); socket.writeUTFBytes(req); main.log("sent key3: " + key3); main.log("expected digest: " + expectedDigest); writeBytes(key3); socket.flush(); } private function onSocketClose(event:Event):void { main.log("closed"); readyState = CLOSED; notifyStateChange(); dispatchEvent(new Event("close")); } private function onSocketIoError(event:IOErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (IoError)"; } else { message = "error communicating with Web Socket server at " + url + " (IoError)"; } onError(message); } private function onSocketSecurityError(event:SecurityErrorEvent):void { var message:String; if (readyState == CONNECTING) { message = "cannot connect to Web Socket server at " + url + " (SecurityError)\n" + "make sure the server is running and Flash socket policy file is correctly placed"; } else { message = "error communicating with Web Socket server at " + url + " (SecurityError)"; } onError(message); } private function onError(message:String):void { var state:int = readyState; if (state == CLOSED) return; main.error(message); close(); notifyStateChange(); dispatchEvent(new Event(state == CONNECTING ? "close" : "error")); } private function onSocketData(event:ProgressEvent):void { var pos:int = buffer.length; socket.readBytes(buffer, pos); for (; pos < buffer.length; ++pos) { if (headerState < 4) { // try to find "\r\n\r\n" if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) { ++headerState; } else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) { ++headerState; } else { headerState = 0; } if (headerState == 4) { var headerStr:String = buffer.readUTFBytes(pos + 1); main.log("response header:\n" + headerStr); if (!validateHeader(headerStr)) return; makeBufferCompact(); pos = -1; } } else if (headerState == 4) { var replyDigest:String = readBytes(buffer, 16); main.log("reply digest: " + replyDigest); if (replyDigest != expectedDigest) { onError("digest doesn't match: " + replyDigest + " != " + expectedDigest); return; } headerState = 5; makeBufferCompact(); pos = -1; readyState = OPEN; notifyStateChange(); dispatchEvent(new Event("open")); } else { if (buffer[pos] == 0xff) { if (buffer.readByte() != 0x00) { onError("data must start with \\x00"); return; } var data:String = buffer.readUTFBytes(pos - 1); main.log("received: " + data); dispatchEvent(new WebSocketMessageEvent("message", encodeURIComponent(data))); buffer.readByte(); makeBufferCompact(); pos = -1; } } } } private function validateHeader(headerStr:String):Boolean { var lines:Array = headerStr.split(/\r\n/); if (!lines[0].match(/^HTTP\/1.1 101 /)) { onError("bad response: " + lines[0]); return false; } var header:Object = {}; for (var i:int = 1; i < lines.length; ++i) { if (lines[i].length == 0) continue; var m:Array = lines[i].match(/^(\S+): (.*)$/); if (!m) { onError("failed to parse response header line: " + lines[i]); return false; } header[m[1]] = m[2]; } if (header["Upgrade"] != "WebSocket") { onError("invalid Upgrade: " + header["Upgrade"]); return false; } if (header["Connection"] != "Upgrade") { onError("invalid Connection: " + header["Connection"]); return false; } var resOrigin:String = header["Sec-WebSocket-Origin"].toLowerCase(); if (resOrigin != origin) { onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'"); return false; } if (protocol && header["Sec-WebSocket-Protocol"] != protocol) { onError("protocol doesn't match: '" + header["WebSocket-Protocol"] + "' != '" + protocol + "'"); return false; } return true; } private function makeBufferCompact():void { if (buffer.position == 0) return; var nextBuffer:ByteArray = new ByteArray(); buffer.readBytes(nextBuffer); buffer = nextBuffer; } private function notifyStateChange():void { dispatchEvent(new WebSocketStateEvent("stateChange", readyState, bufferedAmount)); } private function initNoiseChars():void { noiseChars = new Array(); for (var i:int = 0x21; i <= 0x2f; ++i) { noiseChars.push(String.fromCharCode(i)); } for (var j:int = 0x3a; j <= 0x7a; ++j) { noiseChars.push(String.fromCharCode(j)); } } private function generateKey():String { var spaces:uint = randomInt(1, 12); var max:uint = uint.MAX_VALUE / spaces; var number:uint = randomInt(0, max); var key:String = (number * spaces).toString(); var noises:int = randomInt(1, 12); var pos:int; for (var i:int = 0; i < noises; ++i) { var char:String = noiseChars[randomInt(0, noiseChars.length - 1)]; pos = randomInt(0, key.length); key = key.substr(0, pos) + char + key.substr(pos); } for (var j:int = 0; j < spaces; ++j) { pos = randomInt(1, key.length - 1); key = key.substr(0, pos) + " " + key.substr(pos); } return key; } private function generateKey3():String { var key3:String = ""; for (var i:int = 0; i < 8; ++i) { key3 += String.fromCharCode(randomInt(0, 255)); } return key3; } private function getSecurityDigest(key1:String, key2:String, key3:String):String { var bytes1:String = keyToBytes(key1); var bytes2:String = keyToBytes(key2); return MD5.rstr_md5(bytes1 + bytes2 + key3); } private function keyToBytes(key:String):String { var keyNum:uint = parseInt(key.replace(/[^\d]/g, "")); var spaces:uint = 0; for (var i:int = 0; i < key.length; ++i) { if (key.charAt(i) == " ") ++spaces; } var resultNum:uint = keyNum / spaces; var bytes:String = ""; for (var j:int = 3; j >= 0; --j) { bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff); } return bytes; } private function writeBytes(bytes:String):void { for (var i:int = 0; i < bytes.length; ++i) { socket.writeByte(bytes.charCodeAt(i)); } } private function readBytes(buffer:ByteArray, numBytes:int):String { var bytes:String = ""; for (var i:int = 0; i < numBytes; ++i) { // & 0xff is to make \x80-\xff positive number. bytes += String.fromCharCode(buffer.readByte() & 0xff); } return bytes; } private function randomInt(min:uint, max:uint):uint { return min + Math.floor(Math.random() * (Number(max) - min + 1)); } // for debug private function dumpBytes(bytes:String):void { var output:String = ""; for (var i:int = 0; i < bytes.length; ++i) { output += bytes.charCodeAt(i).toString() + ", "; } main.log(output); } } }
Remove invalid check of 'pos'.
Remove invalid check of 'pos'. This check causes the new (hixie-76) WebSockets protocol check to hang.
ActionScript
bsd-3-clause
hehuabing/web-socket-js,gimite/web-socket-js,gimite/web-socket-js,hanicker/web-socket-js,keiosweb/web-socket-js,zhangxingits/web-socket-js,hanicker/web-socket-js,nitzo/web-socket-js,hehuabing/web-socket-js,zhangxingits/web-socket-js,hehuabing/web-socket-js,zhangxingits/web-socket-js,keiosweb/web-socket-js,nitzo/web-socket-js,hanicker/web-socket-js,nitzo/web-socket-js,keiosweb/web-socket-js,gimite/web-socket-js
3b6ac534dc61f2d9e09b0ed3e15141b1bb25a64b
src/org/mangui/hls/demux/DemuxHelper.as
src/org/mangui/hls/demux/DemuxHelper.as
/* 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/. */ package org.mangui.hls.demux { import flash.utils.ByteArray; import org.mangui.hls.model.Level; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class DemuxHelper { public static function probe(data : ByteArray, level : Level, audioselect : Function, progress : Function, complete : Function, videometadata : Function, id3tagfound : Function, audioOnly : Boolean) : Demuxer { data.position = 0; CONFIG::LOGGING { Log.debug("probe fragment type"); } var aac_match : Boolean = AACDemuxer.probe(data); var mp3_match : Boolean = MP3Demuxer.probe(data); var ts_match : Boolean = TSDemuxer.probe(data); CONFIG::LOGGING { Log.debug("AAC/MP3/TS match:" + aac_match + "/" + mp3_match + "/" + ts_match); } /* prioritize level info : * if ts_match && codec_avc => TS demuxer * if aac_match && codec_aac => AAC demuxer * if mp3_match && codec_mp3 => MP3 demuxer * if no codec info in Manifest, use fallback order : AAC/MP3/TS */ if (ts_match && level.codec_h264) { CONFIG::LOGGING { Log.debug("TS match + H264 signaled in Manifest, use TS demuxer"); } return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly); } else if (aac_match && level.codec_aac) { CONFIG::LOGGING { Log.debug("AAC match + AAC signaled in Manifest, use AAC demuxer"); } return new AACDemuxer(audioselect, progress, complete, id3tagfound); } else if (mp3_match && level.codec_mp3) { CONFIG::LOGGING { Log.debug("MP3 match + MP3 signaled in Manifest, use MP3 demuxer"); } return new MP3Demuxer(audioselect, progress, complete, id3tagfound); } else if (aac_match) { return new AACDemuxer(audioselect, progress, complete, id3tagfound); } else if (mp3_match) { return new MP3Demuxer(audioselect, progress, complete, id3tagfound); } else if (ts_match) { return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly); } else { CONFIG::LOGGING { Log.debug("probe fails"); } return null; } } } }
/* 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/. */ package org.mangui.hls.demux { import flash.utils.ByteArray; import org.mangui.hls.model.Level; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class DemuxHelper { public static function probe(data : ByteArray, level : Level, audioselect : Function, progress : Function, complete : Function, videometadata : Function, id3tagfound : Function, audioOnly : Boolean) : Demuxer { data.position = 0; CONFIG::LOGGING { Log.debug("probe fragment type"); } var aac_match : Boolean = AACDemuxer.probe(data); var mp3_match : Boolean = MP3Demuxer.probe(data); var ts_match : Boolean = TSDemuxer.probe(data); CONFIG::LOGGING { Log.debug("AAC/MP3/TS match:" + aac_match + "/" + mp3_match + "/" + ts_match); } /* prioritize level info : * if ts_match && codec_avc => TS demuxer * if aac_match && codec_aac => AAC demuxer * if mp3_match && codec_mp3 => MP3 demuxer * if no codec info in Manifest, use fallback order : AAC/MP3/TS */ if (ts_match && level && level.codec_h264) { CONFIG::LOGGING { Log.debug("TS match + H264 signaled in Manifest, use TS demuxer"); } return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly); } else if (aac_match && level && level.codec_aac) { CONFIG::LOGGING { Log.debug("AAC match + AAC signaled in Manifest, use AAC demuxer"); } return new AACDemuxer(audioselect, progress, complete, id3tagfound); } else if (mp3_match && level && level.codec_mp3) { CONFIG::LOGGING { Log.debug("MP3 match + MP3 signaled in Manifest, use MP3 demuxer"); } return new MP3Demuxer(audioselect, progress, complete, id3tagfound); } else if (aac_match) { return new AACDemuxer(audioselect, progress, complete, id3tagfound); } else if (mp3_match) { return new MP3Demuxer(audioselect, progress, complete, id3tagfound); } else if (ts_match) { return new TSDemuxer(audioselect, progress, complete, videometadata, audioOnly); } else { CONFIG::LOGGING { Log.debug("probe fails"); } return null; } } } }
Make probe Level parameter optional
[Mangui.DemuxHelper] Make probe Level parameter optional Selection logic ensures proper Demuxer is used anyway
ActionScript
mpl-2.0
codex-corp/flashls,codex-corp/flashls
5a89de067f3440feb457c1bdb90738aee9f0a017
SendAndLoadExample.as
SendAndLoadExample.as
package { import flash.events.*; import flash.net.*; import flash.display.Loader; import flash.external.ExternalInterface; public class SendAndLoadExample { private var _url:String; private var lastSendedUrl:String = ""; public function SendAndLoadExample() { } public function sendData(url:String,msg:String):void { _url = url; if(lastSendedUrl != _url){ var src = encodeURI(_url); var request:URLRequest = new URLRequest(src); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleComplete); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError); loader.load(request); lastSendedUrl = _url; //Config.app.msgbox.text += msg; //ExternalInterface.call('console.log','url Loaded'); } } private function handleComplete(event:Event):void { //var loader:URLLoader = URLLoader(event.target); //trace("post happened"); // ExternalInterface.call('console.log','url Loaded'); } private function onIOError(event:IOErrorEvent):void { // ExternalInterface.call('console.log','url error'); } } }
package { import flash.events.*; import flash.net.*; import flash.display.Loader; import flash.external.ExternalInterface; public class SendAndLoadExample { private var _url:String; private var lastSendedUrl:String = ""; public function SendAndLoadExample() { } public function sendData(url:String,msg:String):void { _url = url; if(lastSendedUrl != _url){ var src = encodeURI(_url); var request:URLRequest = new URLRequest(src); var loader:Loader = new Loader(); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleComplete); loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError); loader.load(request); lastSendedUrl = _url; } } private function handleComplete(event:Event):void { var loadedContent = event.target; } private function onIOError(event:IOErrorEvent):void { // ExternalInterface.call('console.log','url error'); } } }
comment outs
comment outs
ActionScript
mit
ozgurersil/VPAID
0e1794ef1bdb9fe141372fadd1c30b5ab9a07d34
src/org/mangui/hls/HLSSettings.as
src/org/mangui/hls/HLSSettings.as
/* 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/. */ package org.mangui.hls { import org.mangui.hls.constant.HLSAltAudioSwitchMode; import org.mangui.hls.constant.HLSMaxLevelCappingMode; import org.mangui.hls.constant.HLSSeekMode; public final class HLSSettings extends Object { /** * autoStartLoad * * if set to true, * start level playlist and first fragments will be loaded automatically, * after triggering of HlsEvent.MANIFEST_PARSED event * if set to false, * an explicit API call (hls.startLoad()) will be needed * to start quality level/fragment loading. * * Default is true */ public static var autoStartLoad : Boolean = true; /** * capLevelToStage * * Limit levels usable in auto-quality by the stage dimensions (width and height). * true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight). * Max level will be set depending on the maxLevelCappingMode option. * false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelToStage : Boolean = true; /** * maxLevelCappingMode * * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode * HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled) * HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled) * * Default is HLSMaxLevelCappingMode.DOWNSCALE */ public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.UPSCALE; // // // // // // ///////////////////////////////// // // org.mangui.hls.stream.HLSNetStream // // // // // // // ///////////////////////////////// /** * minBufferLength * * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling. * * Default is -1 = auto */ public static var minBufferLength : Number = -1; /** * minBufferLengthCapping * * Defines minimum buffer length capping value (max value) if minBufferLength is set to -1 * * Default is -1 = no capping */ public static var minBufferLengthCapping : Number = -1; /** * maxBufferLength * * Defines maximum buffer length in seconds. * (0 means infinite buffering) * * Default is 120 */ public static var maxBufferLength : Number = 120; /** * maxBackBufferLength * * Defines maximum back buffer length in seconds. * (0 means infinite back buffering) * * Default is 30 */ public static var maxBackBufferLength : Number = 30; /** * lowBufferLength * * Defines low buffer length in seconds. * When crossing down this threshold, HLS will switch to buffering state. * * Default is 3 */ public static var lowBufferLength : Number = 3; /** * mediaTimeUpdatePeriod * * time update period in ms * period at which HLSEvent.MEDIA_TIME will be triggered * Default is 100 ms */ public static var mediaTimePeriod : int = 100; /** * fpsDroppedMonitoringPeriod * * dropped FPS Monitor Period in ms * period at which nb dropped FPS will be checked * Default is 5000 ms */ public static var fpsDroppedMonitoringPeriod : int = 5000; /** * fpsDroppedMonitoringThreshold * * dropped FPS Threshold * every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS. * if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal * than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired * Default is 0.2 (20%) */ public static var fpsDroppedMonitoringThreshold : Number = 0.2; /** * If the dropped FPS threshold is reached, should we nudge the playhead position * forward slightly to try to kick start playback? * * Default is false */ public static var fpsDroppedNudgeEnabled : Boolean = false; /** * capLevelonFPSDrop * * Limit levels usable in auto-quality when FPS drop is detected * i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a * true - enabled * false - disabled * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelonFPSDrop : Boolean = false; /** * smoothAutoSwitchonFPSDrop * * force a smooth level switch Limit when FPS drop is detected in auto-quality * i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch * to level 4 for next fragment * true - enabled * false - disabled * * Note: this setting is active only if capLevelonFPSDrop==true * * Default is true */ public static var smoothAutoSwitchonFPSDrop : Boolean = true; /** * switchDownOnLevelError * * if level loading fails, and if in auto mode, and we are not on lowest level * don't report Level loading error straight-away, try to switch down first * true - enabled * false - disabled * * Default is true */ public static var switchDownOnLevelError : Boolean = true; /** * seekMode * * Defines seek mode to one form available in HLSSeekMode class: * HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position * HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position) * * Default is HLSSeekMode.KEYFRAME_SEEK */ public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK; /** * keyLoadMaxRetry * * Max nb of retries for Key Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var keyLoadMaxRetry : int = 3; /** * keyLoadMaxRetryTimeout * * Maximum key retry timeout (in milliseconds) in case I/O errors are met. * Every fail on key request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var keyLoadMaxRetryTimeout : Number = 64000; /** * fragmentLoadMaxRetry * * Max number of retries for Fragment Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var fragmentLoadMaxRetry : int = 3; /** * fragmentLoadMaxRetryTimeout * * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached. * * Default is 4000 */ public static var fragmentLoadMaxRetryTimeout : Number = 4000; /** * fragmentLoadSkipAfterMaxRetry * * control behaviour in case fragment load still fails after max retry timeout * if set to true, fragment will be skipped and next one will be loaded. * If set to false, an I/O Error will be raised. * * Default is true. */ public static var fragmentLoadSkipAfterMaxRetry : Boolean = true; /** * maxSkippedFragments * * Maximum count of skipped fragments in a row before an I/O Error will be raised. * 0 - no skip (same as fragmentLoadSkipAfterMaxRetry = false) * -1 - no limit for skipping, skip till the end of the playlist * * Default is -1. */ public static var maxSkippedFragments : int = -1; /** * flushLiveURLCache * * If set to true, live playlist will be flushed from URL cache before reloading * (this is to workaround some cache issues with some combination of Flash Player / IE version) * * Default is false */ public static var flushLiveURLCache : Boolean = false; /** * initialLiveManifestSize * * Number of segments needed to start playback of Live stream. * * Default is 2 */ public static var initialLiveManifestSize : uint = 2; /** * liveStopLoadingOnPause * * Should live streams stop loading when paused? * * Default is true */ public static var liveStopLoadingOnPause : Boolean = true; /** * manifestLoadMaxRetry * * max nb of retries for Manifest Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var manifestLoadMaxRetry : int = 3; /** * manifestLoadMaxRetryTimeout * * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached. * * Default is 64000 */ public static var manifestLoadMaxRetryTimeout : Number = 64000; /** * manifestRedundantLoadmaxRetry * * max nb of looping over the redundant streams. * >0 means looping over the stream array 2 or more times * 0 means looping exactly once (no retries) - default behaviour * -1 means infinite retry */ public static var manifestRedundantLoadmaxRetry : int = 3; /** * startFromBitrate * * If greater than 0, specifies the preferred bitrate. * If -1, and startFromLevel is not specified, automatic start level selection will be used. * This parameter, if set, will take priority over startFromLevel. * * Default is -1 */ public static var startFromBitrate : Number = -1; /** * startFromLevel * * start level : * from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate) * * Default is -1 */ public static var startFromLevel : Number = -1; /** * autoStartMaxDuration * * max fragment loading duration in automatic start level selection mode (in ms) * -1 : max duration not capped * other : max duration is capped to avoid long playback starting time * * Default is -1 */ public static var autoStartMaxDuration : Number = -1; /** * seekFromLevel * * Seek level: * from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, keep previous level matching previous download bandwidth * * Default is -1 */ public static var seekFromLevel : Number = -1; /** * subtitlesAutoSelectDefault * * Should a subtitles track automatically be selected if it is flagged * as DEFAULT=YES? * * Default is false */ public static var subtitlesAutoSelectDefault:Boolean = false; /** * subtitlesAutoSelect * * Should a subtitles track automatically be selected if it is flagged * as AUTOSELECT=YES and the language matches the current system locale? * If true, these subtitles will always be selected in preference to * default subtitles. * * Default is true */ public static var subtitlesAutoSelect:Boolean = true; /** * subtitlesAutoSelectForced * * Should a subtitles track automatically be selected is it is flagged * as FORCED=YES? If true, forced subtitles will always be selected * in preference to all others. * * Default is true */ public static var subtitlesAutoSelectForced:Boolean = true; /** * subtitlesUseFlvTagForVod * * Should VOD subtitles be appended directly into the stream or handled * using media time events? * * Default is false */ public static var subtitlesUseFlvTagForVod:Boolean = false; /** * altAudioSwitchMode * * Selects which method to use when switching between alternative audio * streams. * * Default is HLSAltAudioSwitchMode.DEFAULT */ public static var altAudioSwitchMode:uint = HLSAltAudioSwitchMode.DEFAULT; /** * When bandwidth availability increases, what is the maximum number * of quality levels we can we switch up at a time? * * Default is uint.MAX_VALUE */ public static var maxUpSwitchLimit:uint = uint.MAX_VALUE; /** * When bandwidth availability decreases, what is the maximum number * of quality levels we can we switch down at a time? * * Default is uint.MAX_VALUE */ public static var maxDownSwitchLimit:uint = uint.MAX_VALUE; /** * When decoding AES data, how much of the time available for each * frame should be used for decryption? * * Default is 0.2 */ public static var aesMaxFrameTime:Number = 0.2; /** * useHardwareVideoDecoder * * Use hardware video decoder: * it will set NetStream.useHardwareDecoder * refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder * * Default is true */ public static var useHardwareVideoDecoder : Boolean = true; /** * logInfo * * Defines whether INFO level log messages will will appear in the console * * Default is true */ public static var logInfo : Boolean = true; /** * logDebug * * Defines whether DEBUG level log messages will will appear in the console * * Default is false */ public static var logDebug : Boolean = false; /** * logDebug2 * * Defines whether DEBUG2 level log messages will will appear in the console * * Default is false */ public static var logDebug2 : Boolean = false; /** * logWarn * * Defines whether WARN level log messages will will appear in the console * * Default is true */ public static var logWarn : Boolean = true; /** * logError * * Defines whether ERROR level log messages will will appear in the console * * Default is true */ public static var logError : Boolean = true; } }
/* 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/. */ package org.mangui.hls { import org.mangui.hls.constant.HLSAltAudioSwitchMode; import org.mangui.hls.constant.HLSMaxLevelCappingMode; import org.mangui.hls.constant.HLSSeekMode; public final class HLSSettings extends Object { /** * autoStartLoad * * if set to true, * start level playlist and first fragments will be loaded automatically, * after triggering of HlsEvent.MANIFEST_PARSED event * if set to false, * an explicit API call (hls.startLoad()) will be needed * to start quality level/fragment loading. * * Default is true */ public static var autoStartLoad : Boolean = true; /** * capLevelToStage * * Limit levels usable in auto-quality by the stage dimensions (width and height). * true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight). * Max level will be set depending on the maxLevelCappingMode option. * false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelToStage : Boolean = true; /** * maxLevelCappingMode * * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode * HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled) * HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled) * * Default is HLSMaxLevelCappingMode.DOWNSCALE */ public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.UPSCALE; // // // // // // ///////////////////////////////// // // org.mangui.hls.stream.HLSNetStream // // // // // // // ///////////////////////////////// /** * minBufferLength * * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling. * * Default is -1 = auto */ public static var minBufferLength : Number = -1; /** * minBufferLengthCapping * * Defines minimum buffer length capping value (max value) if minBufferLength is set to -1 * * Default is -1 = no capping */ public static var minBufferLengthCapping : Number = -1; /** * maxBufferLength * * Defines maximum buffer length in seconds. * (0 means infinite buffering) * * Default is 120 */ public static var maxBufferLength : Number = 120; /** * maxBackBufferLength * * Defines maximum back buffer length in seconds. * (0 means infinite back buffering) * * Default is 30 */ public static var maxBackBufferLength : Number = 30; /** * lowBufferLength * * Defines low buffer length in seconds. * When crossing down this threshold, HLS will switch to buffering state. * * Default is 3 */ public static var lowBufferLength : Number = 3; /** * mediaTimeUpdatePeriod * * time update period in ms * period at which HLSEvent.MEDIA_TIME will be triggered * Default is 100 ms */ public static var mediaTimePeriod : int = 100; /** * fpsDroppedMonitoringPeriod * * dropped FPS Monitor Period in ms * period at which nb dropped FPS will be checked * Default is 5000 ms */ public static var fpsDroppedMonitoringPeriod : int = 5000; /** * fpsDroppedMonitoringThreshold * * dropped FPS Threshold * every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS. * if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal * than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired * Default is 0.2 (20%) */ public static var fpsDroppedMonitoringThreshold : Number = 0.2; /** * If the dropped FPS threshold is reached, should we nudge the playhead position * forward slightly to try to kick start playback? * * Default is false */ public static var fpsDroppedNudgeEnabled : Boolean = false; /** * capLevelonFPSDrop * * Limit levels usable in auto-quality when FPS drop is detected * i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a * true - enabled * false - disabled * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelonFPSDrop : Boolean = false; /** * smoothAutoSwitchonFPSDrop * * force a smooth level switch Limit when FPS drop is detected in auto-quality * i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch * to level 4 for next fragment * true - enabled * false - disabled * * Note: this setting is active only if capLevelonFPSDrop==true * * Default is true */ public static var smoothAutoSwitchonFPSDrop : Boolean = true; /** * switchDownOnLevelError * * if level loading fails, and if in auto mode, and we are not on lowest level * don't report Level loading error straight-away, try to switch down first * true - enabled * false - disabled * * Default is true */ public static var switchDownOnLevelError : Boolean = true; /** * seekMode * * Defines seek mode to one form available in HLSSeekMode class: * HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position * HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position) * * Default is HLSSeekMode.KEYFRAME_SEEK */ public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK; /** * keyLoadMaxRetry * * Max nb of retries for Key Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var keyLoadMaxRetry : int = 3; /** * keyLoadMaxRetryTimeout * * Maximum key retry timeout (in milliseconds) in case I/O errors are met. * Every fail on key request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var keyLoadMaxRetryTimeout : Number = 64000; /** * fragmentLoadMaxRetry * * Max number of retries for Fragment Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry * * Default is 3 */ public static var fragmentLoadMaxRetry : int = 3; /** * fragmentLoadMaxRetryTimeout * * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached. * * Default is 4000 */ public static var fragmentLoadMaxRetryTimeout : Number = 4000; /** * fragmentLoadSkipAfterMaxRetry * * control behaviour in case fragment load still fails after max retry timeout * if set to true, fragment will be skipped and next one will be loaded. * If set to false, an I/O Error will be raised. * * Default is true. */ public static var fragmentLoadSkipAfterMaxRetry : Boolean = true; /** * maxSkippedFragments * * Maximum count of skipped fragments in a row before an I/O Error will be raised. * 0 - no skip (same as fragmentLoadSkipAfterMaxRetry = false) * -1 - no limit for skipping, skip till the end of the playlist * * Default is -1. */ public static var maxSkippedFragments : int = -1; /** * flushLiveURLCache * * If set to true, live playlist will be flushed from URL cache before reloading * (this is to workaround some cache issues with some combination of Flash Player / IE version) * * Default is false */ public static var flushLiveURLCache : Boolean = false; /** * initialLiveManifestSize * * Number of segments needed to start playback of Live stream. * * Default is 2 */ public static var initialLiveManifestSize : uint = 2; /** * liveStopLoadingOnPause * * Should live streams stop loading when paused? * * Default is true */ public static var liveStopLoadingOnPause : Boolean = true; /** * manifestLoadMaxRetry * * max nb of retries for Manifest Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var manifestLoadMaxRetry : int = 3; /** * manifestLoadMaxRetryTimeout * * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached. * * Default is 64000 */ public static var manifestLoadMaxRetryTimeout : Number = 64000; /** * manifestRedundantLoadmaxRetry * * max nb of looping over the redundant streams. * >0 means looping over the stream array 2 or more times * 0 means looping exactly once (no retries) - default behaviour * -1 means infinite retry */ public static var manifestRedundantLoadmaxRetry : int = 3; /** * startFromBitrate * * If greater than 0, specifies the preferred bitrate. * If -1, and startFromLevel is not specified, automatic start level selection will be used. * This parameter, if set, will take priority over startFromLevel. * * Default is -1 */ public static var startFromBitrate : Number = -1; /** * startFromLevel * * start level : * from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate) * * Default is -1 */ public static var startFromLevel : Number = -1; /** * autoStartMaxDuration * * max fragment loading duration in automatic start level selection mode (in ms) * -1 : max duration not capped * other : max duration is capped to avoid long playback starting time * * Default is -1 */ public static var autoStartMaxDuration : Number = -1; /** * seekFromLevel * * Seek level: * from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, keep previous level matching previous download bandwidth * * Default is -1 */ public static var seekFromLevel : Number = -1; /** * subtitlesAutoSelectDefault * * Should a subtitles track automatically be selected if it is flagged * as DEFAULT=YES? * * Default is false */ public static var subtitlesAutoSelectDefault:Boolean = false; /** * subtitlesAutoSelect * * Should a subtitles track automatically be selected if it is flagged * as AUTOSELECT=YES and the language matches the current system locale? * If true, these subtitles will always be selected in preference to * default subtitles. * * Default is true */ public static var subtitlesAutoSelect:Boolean = true; /** * subtitlesAutoSelectForced * * Should a subtitles track automatically be selected is it is flagged * as FORCED=YES? If true, forced subtitles will always be selected * in preference to all others. * * Default is true */ public static var subtitlesAutoSelectForced:Boolean = true; /** * subtitlesUseFlvTagForVod * * Should VOD subtitles be appended directly into the stream or handled * using media time events? * * Default is false */ public static var subtitlesUseFlvTagForVod:Boolean = false; /** * altAudioSwitchMode * * Selects which method to use when switching between alternative audio * streams. * * Default is HLSAltAudioSwitchMode.DEFAULT */ public static var altAudioSwitchMode:uint = HLSAltAudioSwitchMode.DEFAULT; /** * When bandwidth availability increases, what is the maximum number * of quality levels we can we switch up at a time? * * Default is uint.MAX_VALUE */ public static var maxUpSwitchLimit:uint = uint.MAX_VALUE; /** * When bandwidth availability decreases, what is the maximum number * of quality levels we can we switch down at a time? * * Default is uint.MAX_VALUE */ public static var maxDownSwitchLimit:uint = uint.MAX_VALUE; /** * When decoding AES data, how much of the time available for each * frame should be used for decryption? * * Default is 0.2 */ public static var aesMaxFrameTime:Number = 0.2; /** * useHardwareVideoDecoder * * Use hardware video decoder: * it will set NetStream.useHardwareDecoder * refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder * * Default is false */ public static var useHardwareVideoDecoder : Boolean = false; /** * logInfo * * Defines whether INFO level log messages will will appear in the console * * Default is true */ public static var logInfo : Boolean = true; /** * logDebug * * Defines whether DEBUG level log messages will will appear in the console * * Default is false */ public static var logDebug : Boolean = false; /** * logDebug2 * * Defines whether DEBUG2 level log messages will will appear in the console * * Default is false */ public static var logDebug2 : Boolean = false; /** * logWarn * * Defines whether WARN level log messages will will appear in the console * * Default is true */ public static var logWarn : Boolean = true; /** * logError * * Defines whether ERROR level log messages will will appear in the console * * Default is true */ public static var logError : Boolean = true; } }
Set default value for useHardwareVideoDecoder to false
Set default value for useHardwareVideoDecoder to false
ActionScript
mpl-2.0
neilrackett/flashls,neilrackett/flashls
daca3f9466b80227083fe5513d88489d233de15d
src/aerys/minko/render/geometry/stream/IVertexStream.as
src/aerys/minko/render/geometry/stream/IVertexStream.as
package aerys.minko.render.geometry.stream { import aerys.minko.type.Signal; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; public interface IVertexStream { function get format() : VertexFormat; function get numVertices() : uint; function get changed() : Signal; function get boundsChanged() : Signal; function disposeLocalData(waitForUpload : Boolean = true) : void; function deleteVertexByIndex(index : uint) : Boolean; function getStreamByComponent(component : VertexComponent) : VertexStream; function dispose() : void; } }
package aerys.minko.render.geometry.stream { import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.type.Signal; public interface IVertexStream { function get format() : VertexFormat; function get numVertices() : uint; function get changed() : Signal; function get boundsChanged() : Signal; function get(index : uint, component : VertexComponent = null, offset : uint = 0) : Number; function set(index : uint, value : Number, component : VertexComponent = null, offset : uint = 0) : void; function deleteVertex(index : uint) : IVertexStream; function duplicateVertex(index : uint) : IVertexStream; function disposeLocalData(waitForUpload : Boolean = true) : void; function getStreamByComponent(component : VertexComponent) : VertexStream; function dispose() : void; } }
add get(), set(), duplicateVertex() and deleteVertex() to the IVertexStream interface
add get(), set(), duplicateVertex() and deleteVertex() to the IVertexStream interface
ActionScript
mit
aerys/minko-as3
be0e78beb0de264fc343744725348ecb0e023aec
tamarin-central/thane/flash/net/Socket.as
tamarin-central/thane/flash/net/Socket.as
// // $Id: $ package flash.net { import flash.errors.IOError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.IDataOutput; public class Socket extends EventDispatcher implements IDataInput, IDataOutput { public function Socket (host :String = null, port :int = 0) { if (_theSocket != null) { throw new Error("You may not create Sockets"); } _theSocket = this; _state = ST_VIRGIN; Thane.requestHeartbeat(heartbeat); if (host != null && port > 0) { connect(host, port); } } public function connect (host: String, port: int) :void { if (!host) { throw new IOError("No host specified in connect()"); } if (_state == ST_WAITING) { return; } if (_state == ST_CONNECTED) { close(); } _host = host; _port = port; _state = ST_WAITING; trace("Socket:connect() switching to ST_WAITING..."); } public function close () :void { if (_state != ST_CONNECTED) { throw new IOError("Socket was not open"); } nb_disconnect(); } protected function heartbeat () :void { if (_theSocket == null) { return; } switch(_state) { case ST_VIRGIN: break; case ST_CONNECTED: _oBuf.position = _oPos; var wrote :int = 0; var read :int = nb_read(_iBuf); if (_oPos < _oBuf.length) { wrote = nb_write(_oBuf); } if (read > 0 || wrote > 0) { trace("Socket:heartbeat() read " + read + ", wrote " + wrote); } _iBuf = massageBuffer(_iBuf); _oBuf = massageBuffer(_oBuf); _oPos = _oBuf.position; if (read > 0) { _bytesTotal += read; dispatchEvent(new ProgressEvent(ProgressEvent.SOCKET_DATA)); } break; case ST_WAITING: switch(nb_connect(_host, _port)) { case -1: dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); _state = ST_VIRGIN; break; case 0: trace("Socket:heartbeat() trying to connect..."); break; case 1: trace("Socket:heartbeat() connected!"); _state = ST_CONNECTED; dispatchEvent(new Event(Event.CONNECT)); break; } } } private native function nb_disconnect() :void; /** Returns -1 for error, 0 for keep trying, 1 for success. */ private native function nb_connect (host :String, port :int) :int; /** Returns -1 for error, else the number of bytes read. */ private native function nb_read (iBuf :ByteArray) :int; /** Returns -1 for error, else the number of bytes written. */ private native function nb_write (oBuf :ByteArray) :int; public function flush () :void { // TODO: we should probably respect flush somehow... } public function get endian(): String { return _iBuf.endian; } public function set endian(type: String) :void { _iBuf.endian = type; _oBuf.endian = type; } public function get bytesAvailable () :uint { return _iBuf.bytesAvailable; } public function set objectEncoding (encoding :uint) :void { if (encoding != ObjectEncoding.AMF3) { throw new Error("Only AMF3 supported"); } } public function get objectEncoding () :uint { return ObjectEncoding.AMF3; } // IDataInput public function readBytes(bytes :ByteArray, offset :uint=0, length :uint=0) :void { return _iBuf.readBytes(bytes, offset, length); } public function readBoolean() :Boolean { return _iBuf.readBoolean(); } public function readByte() :int { return _iBuf.readByte(); } public function readUnsignedByte() :uint { return _iBuf.readUnsignedByte(); } public function readShort() :int { return _iBuf.readShort(); } public function readUnsignedShort() :uint { return _iBuf.readUnsignedShort(); } public function readInt() :int { return _iBuf.readInt(); } public function readUnsignedInt() :uint { return _iBuf.readUnsignedInt(); } public function readFloat() :Number { return _iBuf.readFloat(); } public function readDouble() :Number { return _iBuf.readDouble(); } public function readUTF() :String { return _iBuf.readUTF(); } public function readUTFBytes(length :uint) :String { return _iBuf.readUTFBytes(length); } // IDataOutput public function writeBytes(bytes :ByteArray, offset :uint = 0, length :uint = 0) :void { _oBuf.writeBytes(bytes, offset, length); } public function writeBoolean(value :Boolean) :void { _oBuf.writeBoolean(value); } public function writeByte(value :int) :void { _oBuf.writeByte(value); } public function writeShort(value :int) :void { _oBuf.writeShort(value); } public function writeInt(value :int) :void { _oBuf.writeInt(value); } public function writeUnsignedInt(value :uint) :void { _oBuf.writeUnsignedInt(value); } public function writeFloat(value :Number) :void { _oBuf.writeFloat(value); } public function writeDouble(value :Number) :void { _oBuf.writeDouble(value); } public function writeUTF(value :String) :void { _oBuf.writeUTF(value); } public function writeUTFBytes(value :String) :void { _oBuf.writeUTFBytes(value); } // AMF3 bits public function readObject () :* { return AMF3Decoder.decode(this); } public function writeObject (object :*) :void { AMF3Encoder.encode(this, object); } protected function massageBuffer (buffer :ByteArray) :ByteArray { // we only switch buffers if we're wasting 25% and at least 64k if (buffer.position < 0x10000 || 4*buffer.position < buffer.length) { return buffer; } var newBuffer :ByteArray = new ByteArray(); if (buffer.bytesAvailable > 0) { buffer.readBytes(newBuffer, 0, buffer.bytesAvailable); } return newBuffer; } private var _state :int; private var _host :String; private var _port :int; private var _iBuf :ByteArray = new ByteArray(); private var _oBuf :ByteArray = new ByteArray(); // we have to keep our own position in oBuf because writing changes it (?!) private var _oPos :int = 0; private var _bytesTotal :int = 0; private static var _theSocket :Socket = null; private static const ST_VIRGIN :int = 1; private static const ST_WAITING :int = 2; private static const ST_CONNECTED :int = 3; } }
// // $Id: $ package flash.net { import flash.errors.IOError; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.utils.ByteArray; import flash.utils.IDataInput; import flash.utils.IDataOutput; public class Socket extends EventDispatcher implements IDataInput, IDataOutput { public function Socket (host :String = null, port :int = 0) { if (_theSocket != null) { throw new Error("You may not create Sockets"); } _theSocket = this; _state = ST_VIRGIN; Thane.requestHeartbeat(heartbeat); if (host != null && port > 0) { connect(host, port); } } public function connect (host: String, port: int) :void { if (!host) { throw new IOError("No host specified in connect()"); } if (_state == ST_WAITING) { return; } if (_state == ST_CONNECTED) { close(); } _host = host; _port = port; _state = ST_WAITING; // trace("Socket:connect() switching to ST_WAITING..."); } public function close () :void { if (_state != ST_CONNECTED) { throw new IOError("Socket was not open"); } nb_disconnect(); } protected function heartbeat () :void { if (_theSocket == null) { return; } switch(_state) { case ST_VIRGIN: break; case ST_CONNECTED: _oBuf.position = _oPos; var wrote :int = 0; var read :int = nb_read(_iBuf); if (_oPos < _oBuf.length) { wrote = nb_write(_oBuf); } if (read > 0 || wrote > 0) { // trace("Socket:heartbeat() read " + read + ", wrote " + wrote); } _iBuf = massageBuffer(_iBuf); _oBuf = massageBuffer(_oBuf); _oPos = _oBuf.position; if (read > 0) { _bytesTotal += read; dispatchEvent(new ProgressEvent(ProgressEvent.SOCKET_DATA)); } break; case ST_WAITING: switch(nb_connect(_host, _port)) { case -1: dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR)); _state = ST_VIRGIN; break; case 0: // trace("Socket:heartbeat() trying to connect..."); break; case 1: // trace("Socket:heartbeat() connected!"); _state = ST_CONNECTED; dispatchEvent(new Event(Event.CONNECT)); break; } } } private native function nb_disconnect() :void; /** Returns -1 for error, 0 for keep trying, 1 for success. */ private native function nb_connect (host :String, port :int) :int; /** Returns -1 for error, else the number of bytes read. */ private native function nb_read (iBuf :ByteArray) :int; /** Returns -1 for error, else the number of bytes written. */ private native function nb_write (oBuf :ByteArray) :int; public function flush () :void { // TODO: we should probably respect flush somehow... } public function get endian(): String { return _iBuf.endian; } public function set endian(type: String) :void { _iBuf.endian = type; _oBuf.endian = type; } public function get bytesAvailable () :uint { return _iBuf.bytesAvailable; } public function set objectEncoding (encoding :uint) :void { if (encoding != ObjectEncoding.AMF3) { throw new Error("Only AMF3 supported"); } } public function get objectEncoding () :uint { return ObjectEncoding.AMF3; } // IDataInput public function readBytes(bytes :ByteArray, offset :uint=0, length :uint=0) :void { return _iBuf.readBytes(bytes, offset, length); } public function readBoolean() :Boolean { return _iBuf.readBoolean(); } public function readByte() :int { return _iBuf.readByte(); } public function readUnsignedByte() :uint { return _iBuf.readUnsignedByte(); } public function readShort() :int { return _iBuf.readShort(); } public function readUnsignedShort() :uint { return _iBuf.readUnsignedShort(); } public function readInt() :int { return _iBuf.readInt(); } public function readUnsignedInt() :uint { return _iBuf.readUnsignedInt(); } public function readFloat() :Number { return _iBuf.readFloat(); } public function readDouble() :Number { return _iBuf.readDouble(); } public function readUTF() :String { return _iBuf.readUTF(); } public function readUTFBytes(length :uint) :String { return _iBuf.readUTFBytes(length); } // IDataOutput public function writeBytes(bytes :ByteArray, offset :uint = 0, length :uint = 0) :void { _oBuf.writeBytes(bytes, offset, length); } public function writeBoolean(value :Boolean) :void { _oBuf.writeBoolean(value); } public function writeByte(value :int) :void { _oBuf.writeByte(value); } public function writeShort(value :int) :void { _oBuf.writeShort(value); } public function writeInt(value :int) :void { _oBuf.writeInt(value); } public function writeUnsignedInt(value :uint) :void { _oBuf.writeUnsignedInt(value); } public function writeFloat(value :Number) :void { _oBuf.writeFloat(value); } public function writeDouble(value :Number) :void { _oBuf.writeDouble(value); } public function writeUTF(value :String) :void { _oBuf.writeUTF(value); } public function writeUTFBytes(value :String) :void { _oBuf.writeUTFBytes(value); } // AMF3 bits public function readObject () :* { return AMF3Decoder.decode(this); } public function writeObject (object :*) :void { AMF3Encoder.encode(this, object); } protected function massageBuffer (buffer :ByteArray) :ByteArray { // we only switch buffers if we're wasting 25% and at least 64k if (buffer.position < 0x10000 || 4*buffer.position < buffer.length) { return buffer; } var newBuffer :ByteArray = new ByteArray(); if (buffer.bytesAvailable > 0) { buffer.readBytes(newBuffer, 0, buffer.bytesAvailable); } return newBuffer; } private var _state :int; private var _host :String; private var _port :int; private var _iBuf :ByteArray = new ByteArray(); private var _oBuf :ByteArray = new ByteArray(); // we have to keep our own position in oBuf because writing changes it (?!) private var _oPos :int = 0; private var _bytesTotal :int = 0; private static var _theSocket :Socket = null; private static const ST_VIRGIN :int = 1; private static const ST_WAITING :int = 2; private static const ST_CONNECTED :int = 3; } }
Cut down on the verbosity, but leave these in for now, there's surely a few bugs left.
Cut down on the verbosity, but leave these in for now, there's surely a few bugs left.
ActionScript
bsd-2-clause
greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane
9065e9d1eb8ba227a90b2e5702bed8ce5d8d8e78
exporter/src/main/as/flump/export/Atlas.as
exporter/src/main/as/flump/export/Atlas.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.IDataOutput; import com.adobe.images.PNGEncoder; import flump.SwfTexture; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import com.threerings.util.Arrays; public class Atlas { // The empty border size around the right and bottom edges of each texture, to prevent bleeding public static const PADDING :int = 1; public var name :String; public function Atlas (name :String, w :int, h :int) { this.name = name; _width = w; _height = h; _mask = Arrays.create(_width * _height, false); } public function get area () :int { return _width * _height; } public function get filename () :String { return name + ".png"; } public function get used () :int { var used :int = 0; _nodes.forEach(function (n :Node, ..._) :void { used += n.bounds.width * n.bounds.height; }); return used; } public function writePNG (bytes :IDataOutput) :void { var constructed :Sprite = new Sprite(); _nodes.forEach(function (node :Node, ..._) :void { const tex :SwfTexture = node.texture; const bm :Bitmap = new Bitmap(node.texture.toBitmapData(), "auto", true); constructed.addChild(bm); bm.x = node.bounds.x; bm.y = node.bounds.y; }); const bd :BitmapData = SwfTexture.renderToBitmapData(constructed, _width, _height); bytes.writeBytes(PNGEncoder.encode(bd)); } public function toMold () :AtlasMold { const mold :AtlasMold = new AtlasMold(); mold.file = name + ".png"; _nodes.forEach(function (node :Node, ..._) :void { const tex :SwfTexture = node.texture; const texMold :AtlasTextureMold = new AtlasTextureMold(); texMold.symbol = tex.symbol; texMold.bounds = new Rectangle(node.bounds.x, node.bounds.y, tex.w, tex.h); texMold.offset = new Point(tex.offset.x, tex.offset.y); mold.textures.push(texMold); }); return mold; } // Try to place a texture in this atlas, return true if it fit public function place (tex :SwfTexture) :Boolean { var w :int = tex.w + PADDING; var h :int = tex.h + PADDING; if (w > _width || h > _height) { return false; } var found :Boolean = false; for (var yy :int = 0; yy <= _height - h && !found; ++yy) { for (var xx :int = 0; xx <= _width - w; ++xx) { // if our right-most pixel is masked, jump ahead by that much if (maskAt(xx + w - 1, yy)) { xx += w; continue; } if (!isMasked(xx, yy, w, h)) { _nodes.push(new Node(xx, yy, tex)); setMasked(xx, yy, w, h); found = true; break; } } } return found; } protected function isMasked (x :int, y :int, w :int, h :int) :Boolean { var xMax :int = x + w - 1; var yMax :int = y + h - 1; // fail fast on extents if (maskAt(x, y) || maskAt(x, yMax) || maskAt(xMax, y) || maskAt(xMax, yMax)) { return true; } for (var yy :int = y + 1; yy < yMax; ++yy) { for (var xx :int = x + 1; xx < xMax; ++xx) { if (maskAt(xx, yy)) { return true; } } } return false; } protected function setMasked (x :int, y :int, w: int, h :int) :void { for (var yy :int = y; yy < y + h; ++yy) { for (var xx :int = x; xx < x + w; ++xx) { _mask[(yy * _width) + xx] = true; } } } protected function maskAt (xx :int, yy :int) :Boolean { return _mask[(yy * _width) + xx]; } protected var _nodes :Array = []; protected var _width :int; protected var _height :int; protected var _mask :Array; } } import flash.geom.Rectangle; import flump.SwfTexture; class Node { public var bounds :Rectangle; public var texture :SwfTexture; public function Node (x :int, y :int, texture :SwfTexture) { this.texture = texture; this.bounds = new Rectangle(x, y, texture.w, texture.h); } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.Sprite; import flash.geom.Point; import flash.geom.Rectangle; import flash.utils.IDataOutput; import com.adobe.images.PNGEncoder; import flump.SwfTexture; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import com.threerings.util.Arrays; public class Atlas { // The empty border size around the right and bottom edges of each texture, to prevent bleeding public static const PADDING :int = 2; public var name :String; public function Atlas (name :String, w :int, h :int) { this.name = name; _width = w; _height = h; _mask = Arrays.create(_width * _height, false); } public function get area () :int { return _width * _height; } public function get filename () :String { return name + ".png"; } public function get used () :int { var used :int = 0; _nodes.forEach(function (n :Node, ..._) :void { used += n.bounds.width * n.bounds.height; }); return used; } public function writePNG (bytes :IDataOutput) :void { var constructed :Sprite = new Sprite(); _nodes.forEach(function (node :Node, ..._) :void { const tex :SwfTexture = node.texture; const bm :Bitmap = new Bitmap(node.texture.toBitmapData(), "auto", true); constructed.addChild(bm); bm.x = node.bounds.x; bm.y = node.bounds.y; }); const bd :BitmapData = SwfTexture.renderToBitmapData(constructed, _width, _height); bytes.writeBytes(PNGEncoder.encode(bd)); } public function toMold () :AtlasMold { const mold :AtlasMold = new AtlasMold(); mold.file = name + ".png"; _nodes.forEach(function (node :Node, ..._) :void { const tex :SwfTexture = node.texture; const texMold :AtlasTextureMold = new AtlasTextureMold(); texMold.symbol = tex.symbol; texMold.bounds = new Rectangle(node.bounds.x, node.bounds.y, tex.w, tex.h); texMold.offset = new Point(tex.offset.x, tex.offset.y); mold.textures.push(texMold); }); return mold; } // Try to place a texture in this atlas, return true if it fit public function place (tex :SwfTexture) :Boolean { var w :int = tex.w + PADDING; var h :int = tex.h + PADDING; if (w > _width || h > _height) { return false; } var found :Boolean = false; for (var yy :int = 0; yy <= _height - h && !found; ++yy) { for (var xx :int = 0; xx <= _width - w; ++xx) { // if our right-most pixel is masked, jump ahead by that much if (maskAt(xx + w - 1, yy)) { xx += w; continue; } if (!isMasked(xx, yy, w, h)) { _nodes.push(new Node(xx, yy, tex)); setMasked(xx, yy, w, h); found = true; break; } } } return found; } protected function isMasked (x :int, y :int, w :int, h :int) :Boolean { var xMax :int = x + w - 1; var yMax :int = y + h - 1; // fail fast on extents if (maskAt(x, y) || maskAt(x, yMax) || maskAt(xMax, y) || maskAt(xMax, yMax)) { return true; } for (var yy :int = y + 1; yy < yMax; ++yy) { for (var xx :int = x + 1; xx < xMax; ++xx) { if (maskAt(xx, yy)) { return true; } } } return false; } protected function setMasked (x :int, y :int, w: int, h :int) :void { for (var yy :int = y; yy < y + h; ++yy) { for (var xx :int = x; xx < x + w; ++xx) { _mask[(yy * _width) + xx] = true; } } } protected function maskAt (xx :int, yy :int) :Boolean { return _mask[(yy * _width) + xx]; } protected var _nodes :Array = []; protected var _width :int; protected var _height :int; protected var _mask :Array; } } import flash.geom.Rectangle; import flump.SwfTexture; class Node { public var bounds :Rectangle; public var texture :SwfTexture; public function Node (x :int, y :int, texture :SwfTexture) { this.texture = texture; this.bounds = new Rectangle(x, y, texture.w, texture.h); } }
Increase atlas padding to 2 pixels
Increase atlas padding to 2 pixels I'm seeing edge artifacting at 1. Maybe this should be a configurable setting?
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump
b3948adc9b0312fc6f3e660be56d6c62b4feb33c
src/battlecode/client/viewer/render/DrawDominationBar.as
src/battlecode/client/viewer/render/DrawDominationBar.as
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.Team; import battlecode.events.MatchEvent; import flash.display.GradientType; import flash.geom.Matrix; import mx.containers.Canvas; import mx.containers.HBox; import mx.controls.Label; import mx.events.ResizeEvent; public class DrawDominationBar extends HBox { private var controller:MatchController; private var domBarCanvas:Canvas; private var leftDomLabel:Label; private var rightDomLabel:Label; private var lastRound:uint = 0; public function DrawDominationBar(controller:MatchController) { super(); this.controller = controller; this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); this.height = 50; domBarCanvas = new Canvas(); domBarCanvas.percentHeight = 100; domBarCanvas.percentWidth = 100; domBarCanvas.horizontalScrollPolicy = "off"; domBarCanvas.verticalScrollPolicy = "off"; domBarCanvas.addEventListener(ResizeEvent.RESIZE, onResize); leftDomLabel = new Label(); leftDomLabel.setStyle("color", 0xFFFFFF); leftDomLabel.setStyle("fontSize", 14); leftDomLabel.setStyle("fontWeight", "bold"); leftDomLabel.setStyle("textAlign", "center"); leftDomLabel.setStyle("fontFamily", "Courier New"); rightDomLabel = new Label(); rightDomLabel.setStyle("color", 0xFFFFFF); rightDomLabel.setStyle("fontSize", 14); rightDomLabel.setStyle("fontWeight", "bold"); rightDomLabel.setStyle("textAlign", "center"); rightDomLabel.setStyle("fontFamily", "Courier New"); addChild(domBarCanvas); domBarCanvas.addChild(leftDomLabel); domBarCanvas.addChild(rightDomLabel); } private function onResize(e:ResizeEvent):void { redrawAll(); } private function onRoundChange(e:MatchEvent):void { drawDomBar(); } private function onMatchChange(e:MatchEvent):void { updateTooltip(); drawDomBar(); } public function redrawAll():void { drawDomBar(); } private function updateTooltip():void { this.toolTip = controller.match.getTeamA() + " vs. " + controller.match.getTeamB() + "\n"; this.toolTip += "Game " + (controller.currentMatch + 1) + " of " + controller.totalMatches + "\n"; this.toolTip += "Map: " + controller.match.getMapName() + "\n"; } private function drawDomBar():void { var aPoints:uint = controller.currentState.getPoints(Team.A); var bPoints:uint = controller.currentState.getPoints(Team.B); var centerWidth:Number = this.domBarCanvas.width / 2; var centerHeight:Number = this.domBarCanvas.height / 2; var barMaxWidth:Number = (this.domBarCanvas.width / 2) * .8; this.domBarCanvas.graphics.clear(); var minDomPts:int = 10000000; var sideRatio:Number = minDomPts / 10000000; leftDomLabel.text = "(+" + minDomPts.toString() + ")"; leftDomLabel.y = centerHeight - (leftDomLabel.height / 2) - 10; leftDomLabel.x = centerWidth - barMaxWidth * sideRatio - leftDomLabel.width / 2; rightDomLabel.text = "(+" + minDomPts.toString() + ")"; rightDomLabel.y = centerHeight - (rightDomLabel.height / 2) - 10; rightDomLabel.x = centerWidth + barMaxWidth * sideRatio - rightDomLabel.width / 2; // side spikes this.domBarCanvas.graphics.lineStyle(2, 0xFF6666); this.domBarCanvas.graphics.moveTo(centerWidth - barMaxWidth * sideRatio + 1, centerHeight + 10); this.domBarCanvas.graphics.lineTo(centerWidth - barMaxWidth * sideRatio + 1, centerHeight + 2); this.domBarCanvas.graphics.lineStyle(2, 0x9999FF); this.domBarCanvas.graphics.moveTo(centerWidth + barMaxWidth * sideRatio - 1, centerHeight + 10); this.domBarCanvas.graphics.lineTo(centerWidth + barMaxWidth * sideRatio - 1, centerHeight + 2); // domination var topFill:uint = (aPoints > bPoints) ? 0xFFCCCC : 0xCCCCFF; var bottomFill:uint = (aPoints > bPoints) ? 0xFF0000 : 0x0000FF; var domBarWidth:Number = (aPoints - bPoints) / 10000000 * barMaxWidth; if (domBarWidth < -barMaxWidth) domBarWidth = -barMaxWidth; if (domBarWidth > barMaxWidth) domBarWidth = barMaxWidth; var fillMatrix:Matrix = new Matrix(); fillMatrix.createGradientBox(barMaxWidth, 12, Math.PI/2, centerWidth, centerHeight - 0); this.domBarCanvas.graphics.lineStyle(1, 0xFFFFFF); this.domBarCanvas.graphics.beginGradientFill(GradientType.LINEAR, [topFill, bottomFill], [1, 1], [0, 255], fillMatrix, "pad"); this.domBarCanvas.graphics.drawRect(centerWidth, centerHeight - 0, -domBarWidth, 12); this.domBarCanvas.graphics.endFill(); // center spike this.domBarCanvas.graphics.lineStyle(4, 0xCCCCCC); this.domBarCanvas.graphics.moveTo(centerWidth, centerHeight + 16); this.domBarCanvas.graphics.lineTo(centerWidth, centerHeight - 4); } } }
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.Team; import battlecode.events.MatchEvent; import flash.display.GradientType; import flash.geom.Matrix; import mx.containers.Canvas; import mx.containers.HBox; import mx.events.ResizeEvent; public class DrawDominationBar extends HBox { private var controller:MatchController; private var domBarCanvas:Canvas; public function DrawDominationBar(controller:MatchController) { super(); this.controller = controller; this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); this.height = 50; domBarCanvas = new Canvas(); domBarCanvas.percentHeight = 100; domBarCanvas.percentWidth = 100; domBarCanvas.horizontalScrollPolicy = "off"; domBarCanvas.verticalScrollPolicy = "off"; domBarCanvas.addEventListener(ResizeEvent.RESIZE, onResize); addChild(domBarCanvas); } private function onResize(e:ResizeEvent):void { redrawAll(); } private function onRoundChange(e:MatchEvent):void { drawDomBar(); } private function onMatchChange(e:MatchEvent):void { updateTooltip(); drawDomBar(); } public function redrawAll():void { drawDomBar(); } private function updateTooltip():void { this.toolTip = controller.match.getTeamA() + " vs. " + controller.match.getTeamB() + "\n"; this.toolTip += "Game " + (controller.currentMatch + 1) + " of " + controller.totalMatches + "\n"; this.toolTip += "Map: " + controller.match.getMapName() + "\n"; } private function drawDomBar():void { var aPoints:uint = controller.currentState.getPoints(Team.A); var bPoints:uint = controller.currentState.getPoints(Team.B); var centerWidth:Number = this.domBarCanvas.width / 2; var centerHeight:Number = this.domBarCanvas.height / 2; var barMaxWidth:Number = (this.domBarCanvas.width / 2) * .8; this.domBarCanvas.graphics.clear(); // side spikes this.domBarCanvas.graphics.lineStyle(2, 0xFF6666); this.domBarCanvas.graphics.moveTo(centerWidth - barMaxWidth + 1, centerHeight + 10); this.domBarCanvas.graphics.lineTo(centerWidth - barMaxWidth + 1, centerHeight + 2); this.domBarCanvas.graphics.lineStyle(2, 0x9999FF); this.domBarCanvas.graphics.moveTo(centerWidth + barMaxWidth - 1, centerHeight + 10); this.domBarCanvas.graphics.lineTo(centerWidth + barMaxWidth - 1, centerHeight + 2); // domination var topFill:uint = (aPoints > bPoints) ? 0xFFCCCC : 0xCCCCFF; var bottomFill:uint = (aPoints > bPoints) ? 0xFF0000 : 0x0000FF; var domBarWidth:Number = (aPoints - bPoints) / 10000000 * barMaxWidth; if (domBarWidth < -barMaxWidth) domBarWidth = -barMaxWidth; if (domBarWidth > barMaxWidth) domBarWidth = barMaxWidth; var fillMatrix:Matrix = new Matrix(); fillMatrix.createGradientBox(barMaxWidth, 12, Math.PI/2, centerWidth, centerHeight - 0); this.domBarCanvas.graphics.lineStyle(1, 0xFFFFFF); this.domBarCanvas.graphics.beginGradientFill(GradientType.LINEAR, [topFill, bottomFill], [1, 1], [0, 255], fillMatrix, "pad"); this.domBarCanvas.graphics.drawRect(centerWidth, centerHeight - 0, -domBarWidth, 12); this.domBarCanvas.graphics.endFill(); // center spike this.domBarCanvas.graphics.lineStyle(4, 0xCCCCCC); this.domBarCanvas.graphics.moveTo(centerWidth, centerHeight + 16); this.domBarCanvas.graphics.lineTo(centerWidth, centerHeight - 4); } } }
simplify dom bar
simplify dom bar
ActionScript
mit
trun/battlecode-webclient
491c0305c85966d25e7f251f0efdcec376db624e
krew-framework/krewfw/data_structure/PriorityQueue.as
krew-framework/krewfw/data_structure/PriorityQueue.as
package krewfw.data_structure { /** * Simple priority queue (not so optimized.) * Reasonable data structures such as Heap, is not used yet. */ //------------------------------------------------------------ public class PriorityQueue { private var _queue:Vector.<PriorityNode>; private var _isDirty:Boolean; //------------------------------------------------------------ public function PriorityQueue() { _queue = new Vector.<PriorityNode>(); _isDirty = false; } //------------------------------------------------------------ // public //------------------------------------------------------------ /** * Insert element with priority (small number is high priority.) */ public function enqueue(priority:int, item:*):void { var pNode:PriorityNode = new PriorityNode(priority, item); _queue.push(pNode); _isDirty = true; } /** * Remove and get top-priority element. Multiple elements that have * same priority are returned in no particular order. * If queue is empty, return null. */ public function dequeue():* { if (!_queue.length) { return null; } if (_isDirty) { _sort(); } return _queue.pop().item; } /** * Get top-priority element without removing it. Multiple elements that * have same priority are returned in no particular order. * If queue is empty, return null. */ public function peek():* { if (!_queue.length) { return null; } if (_isDirty) { _sort(); } return _queue[_queue.length - 1].item; } /** * Clear the queue. */ public function clear():void { for (var i:int = 0; i < _queue.length; ++i) { _queue[i] = null; } _queue.length = 0; _isDirty = false; } /** * Kill reference for GC. */ public function dispose():void { clear(); _queue = null; } /** * Get the number of elements of queue. */ public function get length():int { return _queue.length; } //------------------------------------------------------------ // private //------------------------------------------------------------ private function _sort():void { _queue.sort(_sortFunc); _isDirty = false; } /** * Keep top-priority element at end of Array to use pop() instead of shift(). */ private function _sortFunc(a:PriorityNode, b:PriorityNode):int { if (a.priority == b.priority) { return 0; } return (a.priority > b.priority) ? -1 : 1; } } } //==================================================================== internal class PriorityNode { public var priority:int; public var item:*; public function PriorityNode(priority:int, item:*) { this.priority = priority; this.item = item; } }
package krewfw.data_structure { /** * Simple priority queue (not so optimized.) * Reasonable data structures such as Heap, is not used yet. */ //------------------------------------------------------------ public class PriorityQueue { private var _queue:Vector.<PriorityNode>; private var _isDirty:Boolean; public var verbose:Boolean = false; //------------------------------------------------------------ public function PriorityQueue() { _queue = new Vector.<PriorityNode>(); _isDirty = false; } //------------------------------------------------------------ // public //------------------------------------------------------------ /** * Insert element with priority (small number is high priority.) */ public function enqueue(priority:int, item:*):void { var pNode:PriorityNode = new PriorityNode(priority, item); _queue.push(pNode); _isDirty = true; if (verbose) { trace("[PriorityQueue :: enqueue] priority:", priority); dumpPriority(); } } /** * Remove and get top-priority element. Multiple elements that have * same priority are returned in no particular order. * If queue is empty, return null. */ public function dequeue():* { if (verbose) { trace("[PriorityQueue :: dequeue] length:", _queue.length); } if (!_queue.length) { return null; } if (_isDirty) { _sort(); } var topItem:* = _queue.pop().item; if (verbose) { dumpPriority(); } return topItem; } /** * Get top-priority element without removing it. Multiple elements that * have same priority are returned in no particular order. * If queue is empty, return null. */ public function peek():* { if (!_queue.length) { return null; } if (_isDirty) { _sort(); } return _queue[_queue.length - 1].item; } /** * Clear the queue. */ public function clear():void { for (var i:int = 0; i < _queue.length; ++i) { _queue[i] = null; } _queue.length = 0; _isDirty = false; } /** * Kill reference for GC. */ public function dispose():void { clear(); _queue = null; } /** * Get the number of elements of queue. */ public function get length():int { return _queue.length; } //------------------------------------------------------------ // private //------------------------------------------------------------ private function _sort():void { _queue.sort(_sortFunc); _isDirty = false; } /** * Keep top-priority element at end of Array to use pop() instead of shift(). */ private function _sortFunc(a:PriorityNode, b:PriorityNode):int { if (a.priority == b.priority) { return 0; } return (a.priority > b.priority) ? -1 : 1; } //------------------------------------------------------------ // debug //------------------------------------------------------------ public function dumpPriority():void { var priorities:Array = []; for each (var item:PriorityNode in _queue) { priorities.push(item.priority); } trace(" -", priorities); } } } //==================================================================== internal class PriorityNode { public var priority:int; public var item:*; public function PriorityNode(priority:int, item:*) { this.priority = priority; this.item = item; } }
Modify priority queue: add debug trace
Modify priority queue: add debug trace
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
c3d9b3b238bce84ea992e8f5c7c2fa43842dadb8
src/main/as/com/threerings/presents/dobj/DObject.as
src/main/as/com/threerings/presents/dobj/DObject.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/narya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.dobj { import org.osflash.signals.Signal; import flash.errors.IllegalOperationError; import flash.events.EventDispatcher; import com.threerings.util.ClassUtil; import com.threerings.util.Joiner; import com.threerings.util.Log; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; public class DObject // extends EventDispatcher implements Streamable { private static const log :Log = Log.getLog(DObject); public function DObject () { new Signaller(this); } public function getOid ():int { return _oid; } public function getManager () :DObjectManager { return _omgr; } public function addSubscriber (sub :Subscriber) :void { if (_subscribers == null) { _subscribers = [ ]; } if (_subscribers.indexOf(sub) == -1) { _subscribers.push(sub); } } public function removeSubscriber (sub :Subscriber) :void { if (_subscribers == null) { return; } var dex :int = _subscribers.indexOf(sub); if (dex != -1) { _subscribers.splice(dex, 1); if (_subscribers.length == 0) { _omgr.removedLastSubscriber(this, _deathWish); } } } public const messageReceived :Signal = new Signal(String, Array); public const destroyed :Signal = new Signal(); public function setDestroyOnLastSubscriberRemoved (deathWish :Boolean) :void { _deathWish = deathWish; } public function addListener (listener :ChangeListener) :void { if (_listeners == null) { _listeners = [ ]; } else if (_listeners.indexOf(listener) != -1) { log.warning("Refusing repeat listener registration", "dobj", which(), "list", listener, new Error()); return; } _listeners.push(listener); } public function removeListener (listener :ChangeListener) :void { if (_listeners != null) { var dex :int = _listeners.indexOf(listener); if (dex != -1) { _listeners.splice(dex, 1); } } } public function notifyListeners (event :DEvent) :void { if (_listeners == null) { return; } var listenersCopy :Array = _listeners.concat(); for each (var listener :Object in listenersCopy) { // make sure the listener is still a listener // and hasn't been removed while dispatching to another listener.. if (_listeners.indexOf(listener) == -1) { continue; } try { event.friendNotifyListener(listener); if (listener is EventListener) { (listener as EventListener).eventReceived(event); } } catch (e :Error) { log.warning("Listener choked during notification", "list", listener, "event", event, e); } } } /** * Posts a message event on this distrubuted object. */ public function postMessage (name :String, args :Array) :void { postEvent(new MessageEvent(_oid, name, args)); } /** * Posts the specified event either to our dobject manager or to the compound event for which * we are currently transacting. */ public function postEvent (event :DEvent) :void { if (_tevent != null) { _tevent.postEvent(event); } else if (_omgr != null) { _omgr.postEvent(event); } else { log.warning("Unable to post event, object has no omgr", "oid", getOid(), "class", ClassUtil.getClassName(this), "event", event); } } /** * Generates a concise string representation of this object. */ public function which () :String { var j :Joiner = Joiner.createFor(this); whichJoiner(j); return j.toString(); } /** * Used to briefly describe this distributed object. */ protected function whichJoiner (j :Joiner) :void { j.addArgs(_oid); } // documentation inherited public function toString () :String { var j :Joiner = Joiner.createFor(this); toStringJoiner(j); return j.toString(); } /** * Generates a string representation of this object. */ public function toStringJoiner (j :Joiner) :void { j.add("oid", _oid); } /** * Begins a transaction on this distributed object. In some situations, it is desirable to * cause multiple changes to distributed object fields in one unified operation. Starting a * transaction causes all subsequent field modifications to be stored in a single compound * event which can then be committed, dispatching and applying all included events in a single * group. Additionally, the events are dispatched over the network in a single unit which can * significantly enhance network efficiency. * * <p> When the transaction is complete, the caller must call {@link #commitTransaction} to * commit the transaction and release the object back to its normal non-transacting state. If * the caller decides not to commit their transaction, they must call {@link * #cancelTransaction} to cancel the transaction. Failure to do so will cause the pooch to be * totally screwed. * * <p> Note: like all other distributed object operations, transactions are not thread safe. It * is expected that a single thread will handle all distributed object operations and that * thread will begin and complete a transaction before giving up control to unknown code which * might try to operate on the transacting distributed object. * * <p> Note also: if the object is already engaged in a transaction, a transaction participant * count will be incremented to note that an additional call to {@link #commitTransaction} is * required before the transaction should actually be committed. Thus <em>every</em> call to * {@link #startTransaction} must be accompanied by a call to either {@link #commitTransaction} * or {@link #cancelTransaction}. Additionally, if any transaction participant cancels the * transaction, the entire transaction is cancelled for all participants, regardless of whether * the other participants attempted to commit the transaction. */ public function startTransaction () :void { if (_tevent != null) { _tcount++; } else { _tevent = new CompoundEvent(getOid()); } } /** * Commits the transaction in which this distributed object is involved. */ public function commitTransaction () :void { if (_tevent == null) { throw new IllegalOperationError( "Cannot commit: not involved in a transaction [dobj=" + this + "]"); } // if we are nested, we decrement our nesting count rather than committing the transaction if (_tcount > 0) { _tcount--; } else { // we may actually be doing our final commit after someone already cancelled this // transaction, so we need to perform the appropriate action at this point if (!_tcancelled) { _tevent.commit(_omgr); } clearTransaction(); } } /** * Returns true if this object is in the middle of a transaction or false if it is not. */ public function inTransaction () :Boolean { return (_tevent != null); } /** * Cancels the transaction in which this distributed object is involved. */ public function cancelTransaction () :void { if (_tevent == null) { throw new IllegalOperationError( "Cannot cancel: not involved in a transaction [dobj=" + this + "]"); } // if we're in a nested transaction, make a note that it is to be cancelled when all // parties commit and decrement the nest count if (_tcount > 0) { _tcancelled = true; _tcount--; } else { clearTransaction(); } } /** * Removes this object from participation in any transaction in which it might be taking part. */ internal function clearTransaction () :void { // sanity check if (_tcount != 0) { log.warning("Transaction cleared with non-zero nesting count", "dobj", this); _tcount = 0; } // clear our transaction state _tevent = null; _tcancelled = false; } /** * Returns true if this object is active and registered with the distributed object system. If * an object is created via <code>DObjectManager.createObject</code> it will be active until * such time as it is destroyed. */ public final function isActive () :Boolean { return (_omgr != null); } /** * Don't call this function! It initializes this distributed object with the supplied * distributed object manager. This is called by the distributed object manager when an object * is created and registered with the system. * * @see DObjectManager#createObject */ public function setManager (omgr :DObjectManager) :void { _omgr = omgr; } /** * Called by derived instances when an attribute setter method was called. */ protected function requestAttributeChange (name :String, value :Object, oldValue :Object) :void { postEvent(new AttributeChangedEvent(_oid, name, value, oldValue)); } /** * Called by derived instances when an element updater method was called. */ protected function requestElementUpdate ( name :String, index :int, value :Object, oldValue :Object) :void { // dispatch an attribute changed event postEvent(new ElementUpdatedEvent(_oid, name, value, oldValue, index)); } /** * Calls by derived instances when an oid adder method was called. */ protected function requestOidAdd (name :String, oid :int) :void { // dispatch an object added event postEvent(new ObjectAddedEvent(_oid, name, oid)); } /** * Calls by derived instances when an oid remover method was called. */ protected function requestOidRemove (name :String, oid :int) :void { // dispatch an object removed event postEvent(new ObjectRemovedEvent(_oid, name, oid)); } /** * Calls by derived instances when a set adder method was called. */ protected function requestEntryAdd (name :String, entry :DSet_Entry) :void { // dispatch an entry added event postEvent(new EntryAddedEvent(_oid, name, entry)); } /** * Calls by derived instances when a set remover method was called. */ protected function requestEntryRemove (name :String, key :Object) :void { // dispatch an entry removed event postEvent(new EntryRemovedEvent(_oid, name, key, null)); } /** * Calls by derived instances when a set updater method was called. */ protected function requestEntryUpdate (name :String, entry :DSet_Entry) :void { // dispatch an entry updated event postEvent(new EntryUpdatedEvent(_oid, name, entry, null)); } // documentation inherited from interface Streamable public final function writeObject (out :ObjectOutputStream) :void { throw new Error(); // out.writeInt(_oid); } // documentation inherited from interface Streamable public function readObject (ins :ObjectInputStream) :void { _oid = ins.readInt(); } /** Our unique identifier. */ protected var _oid :int; /** A reference to our object manager. */ protected var _omgr :DObjectManager; /** Our event listeners. */ protected var _listeners :Array; /** A list of all subscribers to this object. */ protected var _subscribers :Array; /** The compound event associated with our transaction, if we're currently in a transaction. */ protected var _tevent :CompoundEvent; /** The nesting depth of our current transaction. */ protected var _tcount :int; /** Whether or not our nested transaction has been cancelled. */ protected var _tcancelled :Boolean; /** Indicates whether we want to be destroyed when our last subscriber is removed. */ protected var _deathWish :Boolean = false; } } import com.threerings.presents.dobj.MessageEvent; import com.threerings.presents.dobj.MessageListener; import com.threerings.presents.dobj.ObjectDeathListener; import com.threerings.presents.dobj.ObjectDestroyedEvent; import com.threerings.presents.dobj.DObject; class Signaller implements MessageListener, ObjectDeathListener { public function Signaller (obj :DObject) { _obj = obj; _obj.addListener(this); } public function messageReceived (event :MessageEvent) :void { _obj.messageReceived.dispatch(event.getName(), event.getArgs()); } public function objectDestroyed (event :ObjectDestroyedEvent) :void { _obj.destroyed.dispatch(); } protected var _obj :DObject; }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved // http://code.google.com/p/narya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.presents.dobj { import org.osflash.signals.Signal; import flash.errors.IllegalOperationError; import flash.events.EventDispatcher; import com.threerings.util.ClassUtil; import com.threerings.util.Joiner; import com.threerings.util.Log; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; public class DObject // extends EventDispatcher implements Streamable { /** Dispatched when a message is posted to the DObject */ public const messageReceived :Signal = new Signal(String, Array); /** Dispatched when the DObject is destroyed */ public const destroyed :Signal = new Signal(); public function DObject () { new Signaller(this); } public function getOid ():int { return _oid; } public function getManager () :DObjectManager { return _omgr; } public function addSubscriber (sub :Subscriber) :void { if (_subscribers == null) { _subscribers = [ ]; } if (_subscribers.indexOf(sub) == -1) { _subscribers.push(sub); } } public function removeSubscriber (sub :Subscriber) :void { if (_subscribers == null) { return; } var dex :int = _subscribers.indexOf(sub); if (dex != -1) { _subscribers.splice(dex, 1); if (_subscribers.length == 0) { _omgr.removedLastSubscriber(this, _deathWish); } } } public function setDestroyOnLastSubscriberRemoved (deathWish :Boolean) :void { _deathWish = deathWish; } public function addListener (listener :ChangeListener) :void { if (_listeners == null) { _listeners = [ ]; } else if (_listeners.indexOf(listener) != -1) { log.warning("Refusing repeat listener registration", "dobj", which(), "list", listener, new Error()); return; } _listeners.push(listener); } public function removeListener (listener :ChangeListener) :void { if (_listeners != null) { var dex :int = _listeners.indexOf(listener); if (dex != -1) { _listeners.splice(dex, 1); } } } public function notifyListeners (event :DEvent) :void { if (_listeners == null) { return; } var listenersCopy :Array = _listeners.concat(); for each (var listener :Object in listenersCopy) { // make sure the listener is still a listener // and hasn't been removed while dispatching to another listener.. if (_listeners.indexOf(listener) == -1) { continue; } try { event.friendNotifyListener(listener); if (listener is EventListener) { (listener as EventListener).eventReceived(event); } } catch (e :Error) { log.warning("Listener choked during notification", "list", listener, "event", event, e); } } } /** * Posts a message event on this distrubuted object. */ public function postMessage (name :String, args :Array) :void { postEvent(new MessageEvent(_oid, name, args)); } /** * Posts the specified event either to our dobject manager or to the compound event for which * we are currently transacting. */ public function postEvent (event :DEvent) :void { if (_tevent != null) { _tevent.postEvent(event); } else if (_omgr != null) { _omgr.postEvent(event); } else { log.warning("Unable to post event, object has no omgr", "oid", getOid(), "class", ClassUtil.getClassName(this), "event", event); } } /** * Generates a concise string representation of this object. */ public function which () :String { var j :Joiner = Joiner.createFor(this); whichJoiner(j); return j.toString(); } /** * Used to briefly describe this distributed object. */ protected function whichJoiner (j :Joiner) :void { j.addArgs(_oid); } // documentation inherited public function toString () :String { var j :Joiner = Joiner.createFor(this); toStringJoiner(j); return j.toString(); } /** * Generates a string representation of this object. */ public function toStringJoiner (j :Joiner) :void { j.add("oid", _oid); } /** * Begins a transaction on this distributed object. In some situations, it is desirable to * cause multiple changes to distributed object fields in one unified operation. Starting a * transaction causes all subsequent field modifications to be stored in a single compound * event which can then be committed, dispatching and applying all included events in a single * group. Additionally, the events are dispatched over the network in a single unit which can * significantly enhance network efficiency. * * <p> When the transaction is complete, the caller must call {@link #commitTransaction} to * commit the transaction and release the object back to its normal non-transacting state. If * the caller decides not to commit their transaction, they must call {@link * #cancelTransaction} to cancel the transaction. Failure to do so will cause the pooch to be * totally screwed. * * <p> Note: like all other distributed object operations, transactions are not thread safe. It * is expected that a single thread will handle all distributed object operations and that * thread will begin and complete a transaction before giving up control to unknown code which * might try to operate on the transacting distributed object. * * <p> Note also: if the object is already engaged in a transaction, a transaction participant * count will be incremented to note that an additional call to {@link #commitTransaction} is * required before the transaction should actually be committed. Thus <em>every</em> call to * {@link #startTransaction} must be accompanied by a call to either {@link #commitTransaction} * or {@link #cancelTransaction}. Additionally, if any transaction participant cancels the * transaction, the entire transaction is cancelled for all participants, regardless of whether * the other participants attempted to commit the transaction. */ public function startTransaction () :void { if (_tevent != null) { _tcount++; } else { _tevent = new CompoundEvent(getOid()); } } /** * Commits the transaction in which this distributed object is involved. */ public function commitTransaction () :void { if (_tevent == null) { throw new IllegalOperationError( "Cannot commit: not involved in a transaction [dobj=" + this + "]"); } // if we are nested, we decrement our nesting count rather than committing the transaction if (_tcount > 0) { _tcount--; } else { // we may actually be doing our final commit after someone already cancelled this // transaction, so we need to perform the appropriate action at this point if (!_tcancelled) { _tevent.commit(_omgr); } clearTransaction(); } } /** * Returns true if this object is in the middle of a transaction or false if it is not. */ public function inTransaction () :Boolean { return (_tevent != null); } /** * Cancels the transaction in which this distributed object is involved. */ public function cancelTransaction () :void { if (_tevent == null) { throw new IllegalOperationError( "Cannot cancel: not involved in a transaction [dobj=" + this + "]"); } // if we're in a nested transaction, make a note that it is to be cancelled when all // parties commit and decrement the nest count if (_tcount > 0) { _tcancelled = true; _tcount--; } else { clearTransaction(); } } /** * Removes this object from participation in any transaction in which it might be taking part. */ internal function clearTransaction () :void { // sanity check if (_tcount != 0) { log.warning("Transaction cleared with non-zero nesting count", "dobj", this); _tcount = 0; } // clear our transaction state _tevent = null; _tcancelled = false; } /** * Returns true if this object is active and registered with the distributed object system. If * an object is created via <code>DObjectManager.createObject</code> it will be active until * such time as it is destroyed. */ public final function isActive () :Boolean { return (_omgr != null); } /** * Don't call this function! It initializes this distributed object with the supplied * distributed object manager. This is called by the distributed object manager when an object * is created and registered with the system. * * @see DObjectManager#createObject */ public function setManager (omgr :DObjectManager) :void { _omgr = omgr; } /** * Called by derived instances when an attribute setter method was called. */ protected function requestAttributeChange (name :String, value :Object, oldValue :Object) :void { postEvent(new AttributeChangedEvent(_oid, name, value, oldValue)); } /** * Called by derived instances when an element updater method was called. */ protected function requestElementUpdate ( name :String, index :int, value :Object, oldValue :Object) :void { // dispatch an attribute changed event postEvent(new ElementUpdatedEvent(_oid, name, value, oldValue, index)); } /** * Calls by derived instances when an oid adder method was called. */ protected function requestOidAdd (name :String, oid :int) :void { // dispatch an object added event postEvent(new ObjectAddedEvent(_oid, name, oid)); } /** * Calls by derived instances when an oid remover method was called. */ protected function requestOidRemove (name :String, oid :int) :void { // dispatch an object removed event postEvent(new ObjectRemovedEvent(_oid, name, oid)); } /** * Calls by derived instances when a set adder method was called. */ protected function requestEntryAdd (name :String, entry :DSet_Entry) :void { // dispatch an entry added event postEvent(new EntryAddedEvent(_oid, name, entry)); } /** * Calls by derived instances when a set remover method was called. */ protected function requestEntryRemove (name :String, key :Object) :void { // dispatch an entry removed event postEvent(new EntryRemovedEvent(_oid, name, key, null)); } /** * Calls by derived instances when a set updater method was called. */ protected function requestEntryUpdate (name :String, entry :DSet_Entry) :void { // dispatch an entry updated event postEvent(new EntryUpdatedEvent(_oid, name, entry, null)); } // documentation inherited from interface Streamable public final function writeObject (out :ObjectOutputStream) :void { throw new Error(); // out.writeInt(_oid); } // documentation inherited from interface Streamable public function readObject (ins :ObjectInputStream) :void { _oid = ins.readInt(); } /** Our unique identifier. */ protected var _oid :int; /** A reference to our object manager. */ protected var _omgr :DObjectManager; /** Our event listeners. */ protected var _listeners :Array; /** A list of all subscribers to this object. */ protected var _subscribers :Array; /** The compound event associated with our transaction, if we're currently in a transaction. */ protected var _tevent :CompoundEvent; /** The nesting depth of our current transaction. */ protected var _tcount :int; /** Whether or not our nested transaction has been cancelled. */ protected var _tcancelled :Boolean; /** Indicates whether we want to be destroyed when our last subscriber is removed. */ protected var _deathWish :Boolean = false; private static const log :Log = Log.getLog(DObject); } } import com.threerings.presents.dobj.MessageEvent; import com.threerings.presents.dobj.MessageListener; import com.threerings.presents.dobj.ObjectDeathListener; import com.threerings.presents.dobj.ObjectDestroyedEvent; import com.threerings.presents.dobj.DObject; class Signaller implements MessageListener, ObjectDeathListener { public function Signaller (obj :DObject) { _obj = obj; _obj.addListener(this); } public function messageReceived (event :MessageEvent) :void { _obj.messageReceived.dispatch(event.getName(), event.getArgs()); } public function objectDestroyed (event :ObjectDestroyedEvent) :void { _obj.destroyed.dispatch(); } protected var _obj :DObject; }
Move these variables where they belong and add some documentation. Also apparently whitespace.
Move these variables where they belong and add some documentation. Also apparently whitespace. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@6506 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
30ac6713cb881e4419a04d10300643dd712ca00f
as/main/frame4.as
as/main/frame4.as
 var historia_txt:String =""; var baixa_mc:MovieClip; var puja_mc:MovieClip; var buttonsUI:Array = new Array ("puja_mc", "baixa_mc"); this.historia_txt.html = true; this.historia.htmlText =true; this.historia_txt.wordWrap = true; this.historia_txt.multiline = true; function textScroll():Void { this.onPress = this.oOut; this.onRollOver =this.oOver; this.onRollOut = this.oOut; this.onRelease = this.oOut; }; function oOver():Void { pressing = true; movement = -1; }; function oOut():Void { pressing = false; }; var Private_lv = new LoadVars (); Private_lv.load ("/assets/tendes.txt"); Private_lv.onLoad = function () { this.historia_txt.htmlText = this.Privat; this.play (); textScroll(); };
 var historia_txt:String =""; var baixa_mc:MovieClip; var puja_mc:MovieClip; var buttonsUI:Array = new Array ("puja_mc", "baixa_mc"); this.historia_txt.html = true; this.historia.htmlText =true; this.historia_txt.wordWrap = true; this.historia_txt.multiline = true; this.onEnterFrame = function ():Void { buttonsUI[i].oOver(); this.stop(); }; function textScroll():Void { this.onPress = this.oOut; this.onRollOver =this.oOver; this.onRollOut = this.oOut; this.onRelease = this.oOut; }; function oOver():Void { pressing = true; movement = -1; }; function oOut():Void { pressing = false; }; var Private_lv = new LoadVars (); Private_lv.load ("/assets/tendes.txt"); Private_lv.onLoad = function ():Void { this.historia_txt.htmlText = this.Privat; this.play (); textScroll(); };
Update frame4.as
Update frame4.as
ActionScript
bsd-3-clause
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
2e654c56a91ba0ae27de2fdcee27877e1dbfbf12
src/battlecode/common/RobotType.as
src/battlecode/common/RobotType.as
package battlecode.common { public class RobotType { public static const HQ:String = "HQ"; public static const TOWER:String = "TOWER"; public static const SUPPLYDEPOT:String = "SUPPLYDEPOT"; public static const TECHNOLOGYINSTITUTE:String = "TECHNOLOGYINSTITUTE"; public static const BARRACKS:String = "BARRACKS"; public static const HELIPAD:String = "HELIPAD"; public static const TRAININGFIELD:String = "TRAININGFIELD"; public static const TANKFACTORY:String = "TANKFACTORY"; public static const HANDWASHSTATION:String = "HANDWASHSTATION"; public static const AEROSPACELAB:String = "AEROSPACELAB"; public static const BEAVER:String = "BEAVER"; public static const COMPUTER:String = "COMPUTER"; public static const SOLDIER:String = "SOLDIER"; public static const BASHER:String = "BASHER"; public static const MINER:String = "MINER"; public static const DRONE:String = "DRONE"; public static const TANK:String = "TANK"; public static const COMMANDER:String = "COMMANDER"; public static const LAUNCHER:String = "LAUNCHER"; public static const MISSILE:String = "MISSILE"; public function RobotType() { } public static function values():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB, BEAVER, COMPUTER, SOLDIER, BASHER, MINER, DRONE, TANK, COMMANDER, LAUNCHER, MISSILE ]; } public static function buildings():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB ]; } public static function ground():Array { return [ BEAVER, COMPUTER, SOLDIER, BASHER, MINER, TANK, COMMANDER, LAUNCHER, MISSILE ]; } public static function air():Array { return []; // TODO air types } // TODO fix values public static function maxEnergon(type:String):Number { switch (type) { case HQ: return 2000; case TOWER: return 1000; case SUPPLYDEPOT: case TECHNOLOGYINSTITUTE: case BARRACKS: case HELIPAD: case TRAININGFIELD: case TANKFACTORY: case HANDWASHSTATION: case AEROSPACELAB: return 100; case BEAVER: return 30; case MINER: return 50; case COMPUTER: return 1; case SOLDIER: return 40; case BASHER: return 50; case DRONE: return 70; case TANK: return 160; case COMMANDER: return 120; case LAUNCHER: return 400; case MISSILE: return 3; } throw new ArgumentError("Unknown type: " + type); } public static function movementDelay(type:String):uint { return 1; } public static function movementDelayDiagonal(type:String):uint { return 1; } public static function attackDelay(type:String):uint { return 0; } } }
package battlecode.common { public class RobotType { public static const HQ:String = "HQ"; public static const TOWER:String = "TOWER"; public static const SUPPLYDEPOT:String = "SUPPLYDEPOT"; public static const TECHNOLOGYINSTITUTE:String = "TECHNOLOGYINSTITUTE"; public static const BARRACKS:String = "BARRACKS"; public static const HELIPAD:String = "HELIPAD"; public static const TRAININGFIELD:String = "TRAININGFIELD"; public static const TANKFACTORY:String = "TANKFACTORY"; public static const HANDWASHSTATION:String = "HANDWASHSTATION"; public static const AEROSPACELAB:String = "AEROSPACELAB"; public static const BEAVER:String = "BEAVER"; public static const COMPUTER:String = "COMPUTER"; public static const SOLDIER:String = "SOLDIER"; public static const BASHER:String = "BASHER"; public static const MINER:String = "MINER"; public static const DRONE:String = "DRONE"; public static const TANK:String = "TANK"; public static const COMMANDER:String = "COMMANDER"; public static const LAUNCHER:String = "LAUNCHER"; public static const MISSILE:String = "MISSILE"; public function RobotType() { } public static function values():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB, BEAVER, COMPUTER, SOLDIER, BASHER, MINER, DRONE, TANK, COMMANDER, LAUNCHER, MISSILE ]; } public static function buildings():Array { return [ HQ, TOWER, SUPPLYDEPOT, TECHNOLOGYINSTITUTE, BARRACKS, HELIPAD, TRAININGFIELD, TANKFACTORY, HANDWASHSTATION, AEROSPACELAB ]; } public static function ground():Array { return [ BEAVER, COMPUTER, SOLDIER, BASHER, MINER, TANK, COMMANDER, LAUNCHER, MISSILE ]; } public static function air():Array { return []; // TODO air types } public static function maxEnergon(type:String):Number { switch (type) { case HQ: return 2000; case TOWER: return 1000; case SUPPLYDEPOT: case TECHNOLOGYINSTITUTE: case BARRACKS: case HELIPAD: case TRAININGFIELD: case TANKFACTORY: case HANDWASHSTATION: case AEROSPACELAB: return 100; case BEAVER: return 30; case MINER: return 50; case COMPUTER: return 1; case SOLDIER: return 40; case BASHER: return 50; case DRONE: return 70; case TANK: return 160; case COMMANDER: return 120; case LAUNCHER: return 400; case MISSILE: return 3; } throw new ArgumentError("Unknown type: " + type); } public static function movementDelay(type:String):uint { return 1; } public static function movementDelayDiagonal(type:String):uint { return 1; } public static function attackDelay(type:String):uint { return 0; } } }
remove TODO
remove TODO
ActionScript
mit
trun/battlecode-webclient
98a09e8d754dd7a925e68b3ae20c5c0bb1020738
src/as/com/threerings/cast/MultiFrameBitmap.as
src/as/com/threerings/cast/MultiFrameBitmap.as
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast { import flash.display.Bitmap; import flash.display.Sprite; import flash.geom.Point; import flash.events.Event; import com.threerings.media.Tickable; import com.threerings.util.StringUtil; public class MultiFrameBitmap extends Sprite implements Tickable { public function MultiFrameBitmap (frames :Array, fps :Number) { _frames = frames; _bitmap = new Bitmap(); _fps = fps; _frameRate = fps / 1000.0; addChild(_bitmap); setFrame(0); } public function tick (tickStamp :int) :void { if (_start == 0) { _start = tickStamp; } var elapsedTime :int = (tickStamp - _start); var frameIndex :int = Math.floor(elapsedTime * _frameRate) % _frames.length; setFrame(frameIndex); } protected function setFrame (index :int) :void { if (_curFrameIndex != index) { _bitmap.bitmapData = Bitmap(_frames[index]).bitmapData; _curFrameIndex = index; } } public function getFrame (index :int) :Bitmap { return _frames[index]; } public function getFrameCount () :int { return _frames.length; } public function hitTest (stageX :int, stageY :int) :Boolean { if (_curFrameIndex == -1) { return false; } else { if (_bitmap.hitTestPoint(stageX, stageY, true)) { // Doesn't even hit the bounds... return false; } // Check the actual pixels... var pt :Point = _bitmap.globalToLocal(new Point(stageX, stageY)); return _bitmap.bitmapData.hitTest(new Point(0, 0), 0, pt); } } public function clone () :MultiFrameBitmap { return new MultiFrameBitmap(_frames, _fps); } protected var _frames :Array; protected var _bitmap :Bitmap; protected var _start :int; protected var _frameRate :Number; protected var _fps :Number; protected var _curFrameIndex :int = -1; } }
// // Nenya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.cast { import flash.display.Bitmap; import flash.display.Sprite; import flash.geom.Point; import flash.events.Event; import com.threerings.media.Tickable; import com.threerings.util.StringUtil; public class MultiFrameBitmap extends Sprite implements Tickable { public function MultiFrameBitmap (frames :Array, fps :Number) { _frames = frames; _bitmap = new Bitmap(); _fps = fps; _frameRate = fps / 1000.0; addChild(_bitmap); setFrame(0); } public function tick (tickStamp :int) :void { if (_start == 0) { _start = tickStamp; } var elapsedTime :int = (tickStamp - _start); var frameIndex :int = Math.floor(elapsedTime * _frameRate) % _frames.length; setFrame(frameIndex); } protected function setFrame (index :int) :void { if (_curFrameIndex != index) { _bitmap.bitmapData = Bitmap(_frames[index]).bitmapData; _curFrameIndex = index; } } public function getFrame (index :int) :Bitmap { return _frames[index]; } public function getFrameCount () :int { return _frames.length; } public function hitTest (stageX :int, stageY :int) :Boolean { if (_curFrameIndex == -1) { return false; } else { if (!_bitmap.hitTestPoint(stageX, stageY, true)) { // Doesn't even hit the bounds... return false; } // Check the actual pixels... var pt :Point = _bitmap.globalToLocal(new Point(stageX, stageY)); return _bitmap.bitmapData.hitTest(new Point(0, 0), 0, pt); } } public function clone () :MultiFrameBitmap { return new MultiFrameBitmap(_frames, _fps); } protected var _frames :Array; protected var _bitmap :Bitmap; protected var _start :int; protected var _frameRate :Number; protected var _fps :Number; protected var _curFrameIndex :int = -1; } }
Fix some reversed logic.
Fix some reversed logic. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@990 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
9c93870ae897a189addb4a590ffa4759393d8283
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get depth() : Number { if (_invalidDepth) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( Vector4.ZERO, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { // if (_bindings != null) // unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); updateGeometry(geometry); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { for (var parameter : String in _bindings) { meshBindings.removeCallback(parameter, parameterChangedHandler); sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.concat(); _fsConstants = program._fsConstants.concat(); _fsTextures = program._fsTextures.concat(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getNativeTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( Vector4.ZERO, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { // if (_bindings != null) // unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); updateGeometry(geometry); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { for (var parameter : String in _bindings) { meshBindings.removeCallback(parameter, parameterChangedHandler); sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.concat(); _fsConstants = program._fsConstants.concat(); _fsTextures = program._fsTextures.concat(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getNativeTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { // if (!_enabled) // return ; var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
update DrawCall.depth to do nothing if DrawCall._enabled = false
update DrawCall.depth to do nothing if DrawCall._enabled = false
ActionScript
mit
aerys/minko-as3
91144ace118feee263944af6e5d7650d897f28dc
frameworks/as/projects/FlexJSUI/src/FlexJSUIClasses.as
frameworks/as/projects/FlexJSUI/src/FlexJSUIClasses.as
//////////////////////////////////////////////////////////////////////////////// // // 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 { /** * @private * This class is used to link additional classes into rpc.swc * beyond those that are found by dependecy analysis starting * from the classes specified in manifest.xml. */ internal class FlexJSUIClasses { import org.apache.cordova.camera.Camera; Camera; import org.apache.cordova.Application; Application; import org.apache.cordova.Weinre; Weinre; import org.apache.flex.charts.core.CartesianChart; CartesianChart; import org.apache.flex.charts.core.ChartBase; ChartBase; import org.apache.flex.charts.core.IChart; IChart; import org.apache.flex.charts.core.ICartesianChartLayout; ICartesianChartLayout; import org.apache.flex.charts.core.IChartDataGroup; IChartDataGroup; import org.apache.flex.charts.core.IChartSeries; IChartSeries; import org.apache.flex.charts.core.IHorizontalAxisBead; IHorizontalAxisBead; import org.apache.flex.charts.core.IVerticalAxisBead; IVerticalAxisBead; import org.apache.flex.charts.core.IChartItemRenderer; IChartItemRenderer; import org.apache.flex.charts.core.IConnectedItemRenderer; IConnectedItemRenderer; import org.apache.flex.charts.core.PolarChart; PolarChart; import org.apache.flex.charts.supportClasses.ChartDataGroup; ChartDataGroup; import org.apache.flex.maps.google.Map; Map; import org.apache.flex.html.accessories.NumericOnlyTextInputBead; NumericOnlyTextInputBead; import org.apache.flex.html.accessories.PasswordInputBead; PasswordInputBead; import org.apache.flex.html.accessories.TextPromptBead; TextPromptBead; import org.apache.flex.html.beads.AlertView; AlertView; import org.apache.flex.html.beads.ButtonBarView; ButtonBarView; import org.apache.flex.html.beads.CheckBoxView; CheckBoxView; import org.apache.flex.html.beads.ComboBoxView; ComboBoxView; import org.apache.flex.html.beads.ContainerView; ContainerView; import org.apache.flex.html.beads.ControlBarMeasurementBead; ControlBarMeasurementBead; import org.apache.flex.html.beads.CSSButtonView; CSSButtonView; import org.apache.flex.html.beads.CSSTextButtonView; CSSTextButtonView; import org.apache.flex.html.beads.DropDownListView; DropDownListView; import org.apache.flex.html.beads.CloseButtonView; CloseButtonView; import org.apache.flex.html.beads.ImageButtonView; ImageButtonView; import org.apache.flex.html.beads.ImageView; ImageView; import org.apache.flex.html.beads.ListView; ListView; import org.apache.flex.html.beads.NumericStepperView; NumericStepperView; import org.apache.flex.html.beads.PanelView; PanelView; import org.apache.flex.html.beads.PanelWithControlBarView; PanelWithControlBarView; import org.apache.flex.html.beads.RadioButtonView; RadioButtonView; import org.apache.flex.html.beads.ScrollBarView; ScrollBarView; import org.apache.flex.html.beads.SimpleAlertView; SimpleAlertView; import org.apache.flex.html.beads.SingleLineBorderBead; SingleLineBorderBead; import org.apache.flex.html.beads.SliderView; SliderView; import org.apache.flex.html.beads.SliderThumbView; SliderThumbView; import org.apache.flex.html.beads.SliderTrackView; SliderTrackView; import org.apache.flex.html.beads.SolidBackgroundBead; SolidBackgroundBead; import org.apache.flex.html.beads.SpinnerView; SpinnerView; import org.apache.flex.html.beads.TextButtonMeasurementBead; TextButtonMeasurementBead; import org.apache.flex.html.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead; import org.apache.flex.html.beads.TextAreaView; TextAreaView; import org.apache.flex.html.beads.TextButtonView; TextButtonView; import org.apache.flex.html.beads.TextFieldView; TextFieldView; import org.apache.flex.html.beads.TextInputView; TextInputView; import org.apache.flex.html.beads.TextInputWithBorderView; TextInputWithBorderView; import org.apache.flex.html.beads.models.AlertModel; AlertModel; import org.apache.flex.html.beads.models.ArraySelectionModel; ArraySelectionModel; import org.apache.flex.html.beads.models.ComboBoxModel; ComboBoxModel; import org.apache.flex.html.beads.models.ImageModel; ImageModel; import org.apache.flex.html.beads.models.PanelModel; PanelModel; import org.apache.flex.html.beads.models.SingleLineBorderModel; SingleLineBorderModel; import org.apache.flex.html.beads.models.TextModel; TextModel; import org.apache.flex.html.beads.models.TitleBarModel; TitleBarModel; import org.apache.flex.html.beads.models.ToggleButtonModel; ToggleButtonModel; import org.apache.flex.html.beads.models.ValueToggleButtonModel; ValueToggleButtonModel; import org.apache.flex.html.beads.controllers.AlertController; AlertController; import org.apache.flex.html.beads.controllers.ComboBoxController; ComboBoxController; import org.apache.flex.html.beads.controllers.DropDownListController; DropDownListController; import org.apache.flex.html.beads.controllers.EditableTextKeyboardController; EditableTextKeyboardController; import org.apache.flex.html.beads.controllers.ItemRendererMouseController; ItemRendererMouseController; import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController; import org.apache.flex.html.beads.controllers.SliderMouseController; SliderMouseController; import org.apache.flex.html.beads.controllers.SpinnerMouseController; SpinnerMouseController; import org.apache.flex.html.beads.controllers.VScrollBarMouseController; VScrollBarMouseController; import org.apache.flex.html.beads.layouts.ButtonBarLayout; ButtonBarLayout; import org.apache.flex.html.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout; import org.apache.flex.html.beads.layouts.NonVirtualHorizontalScrollingLayout; NonVirtualHorizontalScrollingLayout; import org.apache.flex.html.beads.layouts.NonVirtualBasicLayout; NonVirtualBasicLayout; import org.apache.flex.html.beads.layouts.VScrollBarLayout; VScrollBarLayout; import org.apache.flex.html.beads.layouts.TileLayout; TileLayout; import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData; import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData; DataItemRendererFactoryForArrayData; import org.apache.flex.html.supportClasses.NonVirtualDataGroup; NonVirtualDataGroup; import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory; import org.apache.flex.core.FilledRectangle; FilledRectangle; import org.apache.flex.core.FormatBase; FormatBase; import org.apache.flex.events.CustomEvent; CustomEvent; import org.apache.flex.events.Event; Event; import org.apache.flex.events.MouseEvent; MouseEvent; import org.apache.flex.events.ValueEvent; ValueEvent; import org.apache.flex.utils.EffectTimer; EffectTimer; import org.apache.flex.utils.Timer; Timer; import org.apache.flex.utils.UIUtils; UIUtils; import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl; import org.apache.flex.core.graphics.GraphicShape; GraphicShape; import org.apache.flex.core.graphics.Rect; Rect; import org.apache.flex.core.graphics.Ellipse; Ellipse; import org.apache.flex.core.graphics.Circle; Circle; import org.apache.flex.core.graphics.Path; Path; import org.apache.flex.core.graphics.SolidColor; SolidColor; import org.apache.flex.core.graphics.SolidColorStroke; SolidColorStroke; import org.apache.flex.core.graphics.Text; Text; import org.apache.flex.core.graphics.GraphicsContainer; GraphicsContainer; import org.apache.flex.core.graphics.LinearGradient; LinearGradient; import org.apache.flex.core.DropType; DropType; import org.apache.flex.core.DataBindingBase; DataBindingBase; import org.apache.flex.effects.PlatformWiper; PlatformWiper; import mx.core.ClassFactory; ClassFactory; import mx.states.AddItems; AddItems; import mx.states.SetEventHandler; SetEventHandler; import mx.states.SetProperty; SetProperty; import mx.states.State; State; } }
//////////////////////////////////////////////////////////////////////////////// // // 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 { /** * @private * This class is used to link additional classes into rpc.swc * beyond those that are found by dependecy analysis starting * from the classes specified in manifest.xml. */ internal class FlexJSUIClasses { import org.apache.cordova.camera.Camera; Camera; import org.apache.cordova.Application; Application; import org.apache.cordova.Weinre; Weinre; import org.apache.flex.charts.core.CartesianChart; CartesianChart; import org.apache.flex.charts.core.ChartBase; ChartBase; import org.apache.flex.charts.core.IChart; IChart; import org.apache.flex.charts.core.ICartesianChartLayout; ICartesianChartLayout; import org.apache.flex.charts.core.IChartDataGroup; IChartDataGroup; import org.apache.flex.charts.core.IChartSeries; IChartSeries; import org.apache.flex.charts.core.IHorizontalAxisBead; IHorizontalAxisBead; import org.apache.flex.charts.core.IVerticalAxisBead; IVerticalAxisBead; import org.apache.flex.charts.core.IChartItemRenderer; IChartItemRenderer; import org.apache.flex.charts.core.IConnectedItemRenderer; IConnectedItemRenderer; import org.apache.flex.charts.core.PolarChart; PolarChart; import org.apache.flex.charts.supportClasses.ChartDataGroup; ChartDataGroup; import org.apache.flex.maps.google.Map; Map; import org.apache.flex.html.accessories.NumericOnlyTextInputBead; NumericOnlyTextInputBead; import org.apache.flex.html.accessories.PasswordInputBead; PasswordInputBead; import org.apache.flex.html.accessories.TextPromptBead; TextPromptBead; import org.apache.flex.html.beads.AlertView; AlertView; import org.apache.flex.html.beads.ButtonBarView; ButtonBarView; import org.apache.flex.html.beads.CheckBoxView; CheckBoxView; import org.apache.flex.html.beads.ComboBoxView; ComboBoxView; import org.apache.flex.html.beads.ContainerView; ContainerView; import org.apache.flex.html.beads.ControlBarMeasurementBead; ControlBarMeasurementBead; import org.apache.flex.html.beads.CSSButtonView; CSSButtonView; import org.apache.flex.html.beads.CSSTextButtonView; CSSTextButtonView; import org.apache.flex.html.beads.DropDownListView; DropDownListView; import org.apache.flex.html.beads.CloseButtonView; CloseButtonView; import org.apache.flex.html.beads.ImageButtonView; ImageButtonView; import org.apache.flex.html.beads.ImageView; ImageView; import org.apache.flex.html.beads.ListView; ListView; import org.apache.flex.html.beads.NumericStepperView; NumericStepperView; import org.apache.flex.html.beads.PanelView; PanelView; import org.apache.flex.html.beads.PanelWithControlBarView; PanelWithControlBarView; import org.apache.flex.html.beads.RadioButtonView; RadioButtonView; import org.apache.flex.html.beads.ScrollBarView; ScrollBarView; import org.apache.flex.html.beads.SimpleAlertView; SimpleAlertView; import org.apache.flex.html.beads.SingleLineBorderBead; SingleLineBorderBead; import org.apache.flex.html.beads.SliderView; SliderView; import org.apache.flex.html.beads.SliderThumbView; SliderThumbView; import org.apache.flex.html.beads.SliderTrackView; SliderTrackView; import org.apache.flex.html.beads.SolidBackgroundBead; SolidBackgroundBead; import org.apache.flex.html.beads.SpinnerView; SpinnerView; import org.apache.flex.html.beads.TextButtonMeasurementBead; TextButtonMeasurementBead; import org.apache.flex.html.beads.TextFieldLabelMeasurementBead; TextFieldLabelMeasurementBead; import org.apache.flex.html.beads.TextAreaView; TextAreaView; import org.apache.flex.html.beads.TextButtonView; TextButtonView; import org.apache.flex.html.beads.TextFieldView; TextFieldView; import org.apache.flex.html.beads.TextInputView; TextInputView; import org.apache.flex.html.beads.TextInputWithBorderView; TextInputWithBorderView; import org.apache.flex.html.beads.models.AlertModel; AlertModel; import org.apache.flex.html.beads.models.ArraySelectionModel; ArraySelectionModel; import org.apache.flex.html.beads.models.ComboBoxModel; ComboBoxModel; import org.apache.flex.html.beads.models.ImageModel; ImageModel; import org.apache.flex.html.beads.models.PanelModel; PanelModel; import org.apache.flex.html.beads.models.SingleLineBorderModel; SingleLineBorderModel; import org.apache.flex.html.beads.models.TextModel; TextModel; import org.apache.flex.html.beads.models.TitleBarModel; TitleBarModel; import org.apache.flex.html.beads.models.ToggleButtonModel; ToggleButtonModel; import org.apache.flex.html.beads.models.ValueToggleButtonModel; ValueToggleButtonModel; import org.apache.flex.html.beads.controllers.AlertController; AlertController; import org.apache.flex.html.beads.controllers.ComboBoxController; ComboBoxController; import org.apache.flex.html.beads.controllers.DropDownListController; DropDownListController; import org.apache.flex.html.beads.controllers.EditableTextKeyboardController; EditableTextKeyboardController; import org.apache.flex.html.beads.controllers.ItemRendererMouseController; ItemRendererMouseController; import org.apache.flex.html.beads.controllers.ListSingleSelectionMouseController; ListSingleSelectionMouseController; import org.apache.flex.html.beads.controllers.SliderMouseController; SliderMouseController; import org.apache.flex.html.beads.controllers.SpinnerMouseController; SpinnerMouseController; import org.apache.flex.html.beads.controllers.VScrollBarMouseController; VScrollBarMouseController; import org.apache.flex.html.beads.layouts.ButtonBarLayout; ButtonBarLayout; import org.apache.flex.html.beads.layouts.NonVirtualVerticalScrollingLayout; NonVirtualVerticalScrollingLayout; import org.apache.flex.html.beads.layouts.NonVirtualHorizontalScrollingLayout; NonVirtualHorizontalScrollingLayout; import org.apache.flex.html.beads.layouts.NonVirtualBasicLayout; NonVirtualBasicLayout; import org.apache.flex.html.beads.layouts.VScrollBarLayout; VScrollBarLayout; import org.apache.flex.html.beads.layouts.TileLayout; TileLayout; import org.apache.flex.html.beads.TextItemRendererFactoryForArrayData; TextItemRendererFactoryForArrayData; import org.apache.flex.html.beads.DataItemRendererFactoryForArrayData; DataItemRendererFactoryForArrayData; import org.apache.flex.html.supportClasses.NonVirtualDataGroup; NonVirtualDataGroup; import org.apache.flex.core.ItemRendererClassFactory; ItemRendererClassFactory; import org.apache.flex.core.FilledRectangle; FilledRectangle; import org.apache.flex.core.FormatBase; FormatBase; import org.apache.flex.events.CustomEvent; CustomEvent; import org.apache.flex.events.Event; Event; import org.apache.flex.events.MouseEvent; MouseEvent; import org.apache.flex.events.ValueEvent; ValueEvent; import org.apache.flex.utils.EffectTimer; EffectTimer; import org.apache.flex.utils.Timer; Timer; import org.apache.flex.utils.UIUtils; UIUtils; import org.apache.flex.core.SimpleStatesImpl; SimpleStatesImpl; import org.apache.flex.core.graphics.GraphicShape; GraphicShape; import org.apache.flex.core.graphics.Rect; Rect; import org.apache.flex.core.graphics.Ellipse; Ellipse; import org.apache.flex.core.graphics.Circle; Circle; import org.apache.flex.core.graphics.Path; Path; import org.apache.flex.core.graphics.SolidColor; SolidColor; import org.apache.flex.core.graphics.SolidColorStroke; SolidColorStroke; import org.apache.flex.core.graphics.Text; Text; import org.apache.flex.core.graphics.GraphicsContainer; GraphicsContainer; import org.apache.flex.core.graphics.LinearGradient; LinearGradient; import org.apache.flex.core.DropType; DropType; import org.apache.flex.core.DataBindingBase; DataBindingBase; import org.apache.flex.effects.PlatformWiper; PlatformWiper; import org.apache.flex.geom.Rectangle; Rectangle; import mx.core.ClassFactory; ClassFactory; import mx.states.AddItems; AddItems; import mx.states.SetEventHandler; SetEventHandler; import mx.states.SetProperty; SetProperty; import mx.states.State; State; } }
add rect to swc
add rect to swc
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
dc339b43b64f7e1b9b5f14a641c3ca9f049a095a
src/aerys/minko/render/resource/texture/TextureResource.as
src/aerys/minko/render/resource/texture/TextureResource.as
package aerys.minko.render.resource.texture { import aerys.minko.render.resource.Context3DResource; import flash.display.BitmapData; import flash.display3D.Context3DTextureFormat; import flash.display3D.textures.Texture; import flash.display3D.textures.TextureBase; import flash.geom.Matrix; import flash.utils.ByteArray; /** * @inheritdoc * @author Jean-Marc Le Roux * */ public class TextureResource implements ITextureResource { private static const MAX_SIZE : uint = 2048; private static const TMP_MATRIX : Matrix = new Matrix(); private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED; private var _texture : Texture = null; private var _mipmap : Boolean = false; private var _bitmapData : BitmapData = null; private var _atf : ByteArray = null; private var _atfFormat : uint = 0; private var _width : Number = 0; private var _height : Number = 0; private var _update : Boolean = false; private var _resize : Boolean = false; public function get width() : uint { return _width; } public function get height() : uint { return _height; } public function TextureResource(width : int = 0, height : int = 0) { if (width != 0 && height != 0) setSize(width, height); } public function setSize(width : uint, height : uint) : void { //http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 if (!(width && !(width & (width - 1))) || !(height && !(height & (height - 1)))) throw new Error('The size must be a power of 2.'); _width = width; _height = height; _resize = true; } public function setContentFromBitmapData(bitmapData : BitmapData, mipmap : Boolean, downSample : Boolean = false) : void { var bitmapWidth : uint = bitmapData.width; var bitmapHeight : uint = bitmapData.height; var w : int = 0; var h : int = 0; if (downSample) { w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E); h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E); } else { w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E); h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E); } if (w > MAX_SIZE) w = MAX_SIZE; if (h > MAX_SIZE) h = MAX_SIZE; if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h) _bitmapData = new BitmapData(w, h, bitmapData.transparent, 0); if (w != bitmapWidth || h != bitmapHeight) { TMP_MATRIX.identity(); TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight); _bitmapData.draw(bitmapData, TMP_MATRIX); } else { _bitmapData.draw(bitmapData); } if (_texture && (mipmap != _mipmap || bitmapData.width != _width || bitmapData.height != _height)) { _texture.dispose(); _texture = null; } _width = _bitmapData.width; _height = _bitmapData.height; _mipmap = mipmap; _update = true; } public function setContentFromATF(atf : ByteArray) : void { _atf = atf; _bitmapData = null; _update = true; atf.position = 6; _atfFormat = atf.readUnsignedByte() & 3; _width = 1 << atf.readUnsignedByte(); _height = 1 << atf.readUnsignedByte(); _mipmap = atf.readUnsignedByte() > 1; atf.position = 0; } public function getNativeTexture(context : Context3DResource) : TextureBase { if ((!_texture || _resize) && _width && _height) { _resize = false; if (_texture) _texture.dispose(); _texture = context.createTexture( _width, _height, _atf && _atfFormat == 2 ? FORMAT_COMPRESSED : FORMAT_BGRA, _bitmapData == null && _atf == null ); _update = true; } if (_update) { _update = false; uploadTextureWithMipMaps(); } _atf = null; _bitmapData = null; if (_texture == null) throw new Error(); return _texture; } private function uploadTextureWithMipMaps() : void { if (_bitmapData) { if (_mipmap) { var level : uint = 0; var size : uint = _width > _height ? _width : _height; var transparent : Boolean = _bitmapData.transparent; var tmp : BitmapData = new BitmapData(size, size, transparent, 0); var transform : Matrix = new Matrix(); while (size >= 1) { tmp.draw(_bitmapData, transform, null, null, null, true); _texture.uploadFromBitmapData(tmp, level); transform.scale(.5, .5); level++; size >>= 1; if (tmp.transparent) tmp.fillRect(tmp.rect, 0); } tmp.dispose(); } else { _texture.uploadFromBitmapData(_bitmapData, 0); } _bitmapData.dispose(); } else if (_atf) { _texture.uploadCompressedTextureFromByteArray(_atf, 0, false); } } public function dispose() : void { if (_texture) { _texture.dispose(); _texture = null; } } } }
package aerys.minko.render.resource.texture { import aerys.minko.render.resource.Context3DResource; import flash.display.BitmapData; import flash.display3D.Context3DTextureFormat; import flash.display3D.textures.Texture; import flash.display3D.textures.TextureBase; import flash.geom.Matrix; import flash.utils.ByteArray; /** * @inheritdoc * @author Jean-Marc Le Roux * */ public class TextureResource implements ITextureResource { private static const MAX_SIZE : uint = 2048; private static const TMP_MATRIX : Matrix = new Matrix(); private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED; private static const FORMAT_COMPRESSED_ALPHA : String = Context3DTextureFormat.COMPRESSED_ALPHA; private var _texture : Texture = null; private var _mipmap : Boolean = false; private var _bitmapData : BitmapData = null; private var _atf : ByteArray = null; private var _atfFormat : uint = 0; private var _width : Number = 0; private var _height : Number = 0; private var _update : Boolean = false; private var _resize : Boolean = false; public function get width() : uint { return _width; } public function get height() : uint { return _height; } public function TextureResource(width : int = 0, height : int = 0) { if (width != 0 && height != 0) setSize(width, height); } public function setSize(width : uint, height : uint) : void { //http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2 if (!(width && !(width & (width - 1))) || !(height && !(height & (height - 1)))) throw new Error('The size must be a power of 2.'); _width = width; _height = height; _resize = true; } public function setContentFromBitmapData(bitmapData : BitmapData, mipmap : Boolean, downSample : Boolean = false) : void { var bitmapWidth : uint = bitmapData.width; var bitmapHeight : uint = bitmapData.height; var w : int = 0; var h : int = 0; if (downSample) { w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E); h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E); } else { w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E); h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E); } if (w > MAX_SIZE) w = MAX_SIZE; if (h > MAX_SIZE) h = MAX_SIZE; if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h) _bitmapData = new BitmapData(w, h, bitmapData.transparent, 0); if (w != bitmapWidth || h != bitmapHeight) { TMP_MATRIX.identity(); TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight); _bitmapData.draw(bitmapData, TMP_MATRIX); } else { _bitmapData.draw(bitmapData); } if (_texture && (mipmap != _mipmap || bitmapData.width != _width || bitmapData.height != _height)) { _texture.dispose(); _texture = null; } _width = _bitmapData.width; _height = _bitmapData.height; _mipmap = mipmap; _update = true; } public function setContentFromATF(atf : ByteArray) : void { _atf = atf; _bitmapData = null; _update = true; atf.position = 6; var formatByte : uint = atf.readUnsignedByte(); _atfFormat = formatByte & 7; _width = 1 << atf.readUnsignedByte(); _height = 1 << atf.readUnsignedByte(); _mipmap = atf.readUnsignedByte() > 1; atf.position = 0; } public function getNativeTexture(context : Context3DResource) : TextureBase { if ((!_texture || _resize) && _width && _height) { _resize = false; if (_texture) _texture.dispose(); var format : String = FORMAT_BGRA; if (_atf) { if (_atfFormat == 5) format = FORMAT_COMPRESSED_ALPHA; else if (_atfFormat == 3) format = FORMAT_COMPRESSED; } _texture = context.createTexture( _width, _height, format, _bitmapData == null && _atf == null ); _update = true; } if (_update) { _update = false; uploadTextureWithMipMaps(); } _atf = null; _bitmapData = null; if (_texture == null) throw new Error(); return _texture; } private function uploadTextureWithMipMaps() : void { if (_bitmapData) { if (_mipmap) { var level : uint = 0; var size : uint = _width > _height ? _width : _height; var transparent : Boolean = _bitmapData.transparent; var tmp : BitmapData = new BitmapData(size, size, transparent, 0); var transform : Matrix = new Matrix(); while (size >= 1) { tmp.draw(_bitmapData, transform, null, null, null, true); _texture.uploadFromBitmapData(tmp, level); transform.scale(.5, .5); level++; size >>= 1; if (tmp.transparent) tmp.fillRect(tmp.rect, 0); } tmp.dispose(); } else { _texture.uploadFromBitmapData(_bitmapData, 0); } _bitmapData.dispose(); } else if (_atf) { _texture.uploadCompressedTextureFromByteArray(_atf, 0); } } public function dispose() : void { if (_texture) { _texture.dispose(); _texture = null; } } } }
Update textureResource to handle atf properly
Update textureResource to handle atf properly
ActionScript
mit
aerys/minko-as3
9e3cb3f82d7487e5f6bf985c1fbdb92ccb0158d2
tamarin-central/thane/thane_core.as
tamarin-central/thane/thane_core.as
// // $Id: $ package flash.errors { public class MemoryError extends Error { public function MemoryError(message:String = "") { super(message); } } public class EOFError extends Error { public function EOFError(message:String = "") { super(message); } } public class IllegalOperationError extends Error { public function IllegalOperationError (str :String = null) { } } } package flash.events { import flash.utils.Dictionary; public class Event { public static const CONNECT :String = "connect"; public static const CLOSE :String = "close"; public static const COMPLETE:String = "complete"; public function Event (type :String, bubbles :Boolean = false, cancelable :Boolean = false) { if (bubbles || cancelable) { throw new Error("Not implemented"); } _type = type; } public function get type () :String { return _type; } public function get target () :Object { return null; } public function clone () :Event { return new Event(_type); } private var _type :String; } public class TextEvent extends Event { public var text :String; public function TextEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "") { super(type, bubbles, cancelable); this.text = text; } } public class ErrorEvent extends TextEvent { public static const ERROR :String = "error"; public function ErrorEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "", id :int = 0) { super(type, bubbles, cancelable, text); _errorId = id; } public function get errorID () :int { return _errorId; } protected var _errorId :int; } public class SecurityErrorEvent extends ErrorEvent { public static const SECURITY_ERROR :String = "securityError"; public function SecurityErrorEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "", id :int = 0) { super(type, bubbles, cancelable); } } public class EventDispatcher { public function addEventListener ( type :String, listener :Function, useCapture :Boolean = false, priority :int = 0, useWeakReference :Boolean = false) :void { if (useCapture || priority != 0 || useWeakReference) { throw new Error("Fancy addEventListener not implemented"); } var listeners :Array = _listenerMap[type] as Array; if (listeners == null) { _listenerMap[type] = listeners = new Array(); } else if (-1 == _listenerMap.indexOf(listener)) { return; } listeners.push(listener); } public function removeEventListener ( type :String, listener :Function, useCapture :Boolean = false) :void { if (useCapture) { throw new Error("Fancy removeListener not implemented"); } var listeners :Array = _listenerMap[type] as Array; if (listeners != null) { var ix :int = listeners.indexOf(listener); if (ix >= 0) { listeners.splice(ix, 1); } } } public function dispatchEvent (event :Event) :Boolean { var listeners :Array = _listenerMap[event.type] as Array; for each (var listener :Function in listeners) { try { listener(event); } catch (err :Error) { trace("Event[" + event + "] dispatch error: " + err); } } // TODO: "A value of true unless preventDefault() is called on the event, // in which case it returns false. " return true; } private var _listenerMap :Dictionary = new Dictionary(); } public class TimerEvent extends Event { public static const TIMER :String = "timer"; public static const TIMER_COMPLETE :String = "timerComplete"; public function TimerEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "") { super(type, bubbles, cancelable); } } } package flash.utils { import flash.events.EventDispatcher; import flash.events.TimerEvent; import avmplus.*; public function describeType (c :Object) :XML { throw new Error("describeType() Not implemented"); } public function getDefinitionByName (name :String) :Class { return Domain.currentDomain.getClass(name.replace("::", ".")); } public function getQualifiedClassName (c :*) :String { return Domain.currentDomain.getClassName(c); } public function getQualifiedSuperclassName (c :*) :String { throw new Error("getQualifiedSuperclassName() not implemented"); } var timers :Dictionary = new Dictionary(); var timerIx :uint = 1; public function setTimeout (closure :Function, delay :Number, ... arguments) :uint { return createTimer(closure, delay, true, arguments); } public function setInterval (closure :Function, delay :Number, ... arguments) :uint { return createTimer(closure, delay, false, arguments); } public function clearTimeout (id :uint): void { destroyTimer(id); } public function clearInterval (id :uint): void { destroyTimer(id); } public function getTimer () :int { return System.getTimer(); } function createTimer (closure :Function, delay :Number, timeout :Boolean, ... arguments) :uint { var timer :Timer = new Timer(delay, timeout ? 1 : 0); var fun :Function = function (event :TimerEvent) :void { if (timeout) { destroyTimer(timerIx); } closure.apply(null, arguments); }; timer.addEventListener(TimerEvent.TIMER, fun); timers[timerIx] = [ timer, fun ]; return timerIx ++; } function destroyTimer (id :uint) :void { var bits :Array = timers[id]; if (bits) { bits[0].removeEventListener(TimerEvent.TIMER, bits[1]); bits[0].stop(); delete timers[id]; } } public interface IDataInput { function readBytes(bytes :ByteArray, offset :uint=0, length :uint=0) :void; function readBoolean() :Boolean; function readByte() :int; function readUnsignedByte() :uint; function readObject () :* function readShort() :int; function readUnsignedShort() :uint; function readInt() :int; function readUnsignedInt() :uint; function readFloat() :Number; function readDouble() :Number; function readUTF() :String; function readUTFBytes(length :uint) :String; function get bytesAvailable() :uint; function get endian() :String; function set endian(type :String) :void; } public interface IDataOutput { function writeBytes(bytes :ByteArray, offset :uint = 0, length :uint = 0) :void; function writeBoolean(value :Boolean) :void; function writeByte(value :int) :void; function writeObject (object :*) :void function writeShort(value :int) :void; function writeInt(value :int) :void; function writeUnsignedInt(value :uint) :void; function writeFloat(value :Number) :void; function writeDouble(value :Number) :void; function writeUTF(value :String) :void; function writeUTFBytes(value :String) :void; function get endian() :String; function set endian(type :String) :void; function get objectEncoding () :uint; function set objectEncoding (encoding :uint) :void; } public interface IExternalizable { function readExternal (input: IDataInput) :void; function writeExternal (output: IDataOutput) :void; } } package flash.net { import avmplus.Domain; public function getClassByAlias (aliasName :String) :Class { var className :String = AMF3.getClassNameByAlias(aliasName); if (className == null) { throw new VerifyError("Alias not registered."); } return Domain.currentDomain.getClass(className); } public function registerClassAlias (aliasName :String, classObject :Class) :void { // TODO: protect against user code AMF3.registerClassAlias(aliasName, classObject); } public class ObjectEncoding { public static const AMF0 :uint = 0; public static const AMF3 :uint = 3; public static const DEFAULT :uint = AMF3; } }
// // $Id: $ package flash.errors { public class MemoryError extends Error { public function MemoryError(message:String = "") { super(message); } } public class EOFError extends Error { public function EOFError(message:String = "") { super(message); } } public class IllegalOperationError extends Error { public function IllegalOperationError (message :String = null) { super(message); } } } package flash.events { import flash.utils.Dictionary; public class Event { public static const CONNECT :String = "connect"; public static const CLOSE :String = "close"; public static const COMPLETE:String = "complete"; public function Event (type :String, bubbles :Boolean = false, cancelable :Boolean = false) { if (bubbles || cancelable) { throw new Error("Not implemented"); } _type = type; } public function get type () :String { return _type; } public function get target () :Object { return null; } public function clone () :Event { return new Event(_type); } private var _type :String; } public class TextEvent extends Event { public var text :String; public function TextEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "") { super(type, bubbles, cancelable); this.text = text; } } public class ErrorEvent extends TextEvent { public static const ERROR :String = "error"; public function ErrorEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "", id :int = 0) { super(type, bubbles, cancelable, text); _errorId = id; } public function get errorID () :int { return _errorId; } protected var _errorId :int; } public class SecurityErrorEvent extends ErrorEvent { public static const SECURITY_ERROR :String = "securityError"; public function SecurityErrorEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "", id :int = 0) { super(type, bubbles, cancelable); } } public class EventDispatcher { public function addEventListener ( type :String, listener :Function, useCapture :Boolean = false, priority :int = 0, useWeakReference :Boolean = false) :void { if (useCapture || priority != 0 || useWeakReference) { throw new Error("Fancy addEventListener not implemented"); } var listeners :Array = _listenerMap[type] as Array; if (listeners == null) { _listenerMap[type] = listeners = new Array(); } else if (-1 == _listenerMap.indexOf(listener)) { return; } listeners.push(listener); } public function removeEventListener ( type :String, listener :Function, useCapture :Boolean = false) :void { if (useCapture) { throw new Error("Fancy removeListener not implemented"); } var listeners :Array = _listenerMap[type] as Array; if (listeners != null) { var ix :int = listeners.indexOf(listener); if (ix >= 0) { listeners.splice(ix, 1); } } } public function dispatchEvent (event :Event) :Boolean { var listeners :Array = _listenerMap[event.type] as Array; for each (var listener :Function in listeners) { try { listener(event); } catch (err :Error) { trace("Event[" + event + "] dispatch error: " + err); } } // TODO: "A value of true unless preventDefault() is called on the event, // in which case it returns false. " return true; } private var _listenerMap :Dictionary = new Dictionary(); } public class TimerEvent extends Event { public static const TIMER :String = "timer"; public static const TIMER_COMPLETE :String = "timerComplete"; public function TimerEvent ( type :String, bubbles :Boolean = false, cancelable :Boolean = false, text :String = "") { super(type, bubbles, cancelable); } } } package flash.utils { import flash.events.EventDispatcher; import flash.events.TimerEvent; import avmplus.*; public function describeType (c :Object) :XML { throw new Error("describeType() Not implemented"); } public function getDefinitionByName (name :String) :Class { return Domain.currentDomain.getClass(name.replace("::", ".")); } public function getQualifiedClassName (c :*) :String { return Domain.currentDomain.getClassName(c); } public function getQualifiedSuperclassName (c :*) :String { throw new Error("getQualifiedSuperclassName() not implemented"); } var timers :Dictionary = new Dictionary(); var timerIx :uint = 1; public function setTimeout (closure :Function, delay :Number, ... arguments) :uint { return createTimer(closure, delay, true, arguments); } public function setInterval (closure :Function, delay :Number, ... arguments) :uint { return createTimer(closure, delay, false, arguments); } public function clearTimeout (id :uint): void { destroyTimer(id); } public function clearInterval (id :uint): void { destroyTimer(id); } public function getTimer () :int { return System.getTimer(); } function createTimer (closure :Function, delay :Number, timeout :Boolean, ... arguments) :uint { var timer :Timer = new Timer(delay, timeout ? 1 : 0); var fun :Function = function (event :TimerEvent) :void { if (timeout) { destroyTimer(timerIx); } closure.apply(null, arguments); }; timer.addEventListener(TimerEvent.TIMER, fun); timers[timerIx] = [ timer, fun ]; return timerIx ++; } function destroyTimer (id :uint) :void { var bits :Array = timers[id]; if (bits) { bits[0].removeEventListener(TimerEvent.TIMER, bits[1]); bits[0].stop(); delete timers[id]; } } public interface IDataInput { function readBytes(bytes :ByteArray, offset :uint=0, length :uint=0) :void; function readBoolean() :Boolean; function readByte() :int; function readUnsignedByte() :uint; function readObject () :* function readShort() :int; function readUnsignedShort() :uint; function readInt() :int; function readUnsignedInt() :uint; function readFloat() :Number; function readDouble() :Number; function readUTF() :String; function readUTFBytes(length :uint) :String; function get bytesAvailable() :uint; function get endian() :String; function set endian(type :String) :void; } public interface IDataOutput { function writeBytes(bytes :ByteArray, offset :uint = 0, length :uint = 0) :void; function writeBoolean(value :Boolean) :void; function writeByte(value :int) :void; function writeObject (object :*) :void function writeShort(value :int) :void; function writeInt(value :int) :void; function writeUnsignedInt(value :uint) :void; function writeFloat(value :Number) :void; function writeDouble(value :Number) :void; function writeUTF(value :String) :void; function writeUTFBytes(value :String) :void; function get endian() :String; function set endian(type :String) :void; function get objectEncoding () :uint; function set objectEncoding (encoding :uint) :void; } public interface IExternalizable { function readExternal (input: IDataInput) :void; function writeExternal (output: IDataOutput) :void; } } package flash.net { import avmplus.Domain; public function getClassByAlias (aliasName :String) :Class { var className :String = AMF3.getClassNameByAlias(aliasName); if (className == null) { throw new VerifyError("Alias not registered."); } return Domain.currentDomain.getClass(className); } public function registerClassAlias (aliasName :String, classObject :Class) :void { // TODO: protect against user code AMF3.registerClassAlias(aliasName, classObject); } public class ObjectEncoding { public static const AMF0 :uint = 0; public static const AMF3 :uint = 3; public static const DEFAULT :uint = AMF3; } }
Tweak fix.
Tweak fix.
ActionScript
bsd-2-clause
greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane
40c48f69de993f85402e6cf4125ac677aa64296e
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _bindingsConsumer : DrawCallBindingsConsumer; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (_bindingsConsumer) _bindingsConsumer.enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { if (_bindingsConsumer != null) { meshBindings.removeConsumer(_bindingsConsumer); sceneBindings.removeConsumer(_bindingsConsumer); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; _bindingsConsumer = new DrawCallBindingsConsumer( _bindings, _cpuConstants, _vsConstants, _fsConstants, _fsTextures ); _bindingsConsumer.enabled = _enabled; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { if (!_vsInputComponents) return ; updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { meshBindings.addConsumer(_bindingsConsumer); sceneBindings.addConsumer(_bindingsConsumer); if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { _bindingsConsumer.setProperty(name, value); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _center : Vector4 = null; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; private var _bindingsConsumer : DrawCallBindingsConsumer; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; if (_bindingsConsumer) _bindingsConsumer.enabled = value; } public function get depth() : Number { if (_invalidDepth && _enabled) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { var worldSpacePosition : Vector4 = _localToWorld.transformVector( _center, TMP_VECTOR4 ); var screenSpacePosition : Vector4 = _worldToScreen.transformVector( worldSpacePosition, TMP_VECTOR4 ); _depth = screenSpacePosition.z / screenSpacePosition.w; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { _invalidDepth = computeDepth; setProgram(program); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { if (_bindingsConsumer != null) { meshBindings.removeConsumer(_bindingsConsumer); sceneBindings.removeConsumer(_bindingsConsumer); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.slice(); _fsConstants = program._fsConstants.slice(); _fsTextures = program._fsTextures.slice(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; _bindingsConsumer = new DrawCallBindingsConsumer( _bindings, _cpuConstants, _vsConstants, _fsConstants, _fsTextures ); _bindingsConsumer.enabled = _enabled; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL); if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(!hasNormals); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals) { geometry.computeNormals(); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { if (!_vsInputComponents) return ; updateGeometry(geometry); _center = geometry.boundingSphere ? geometry.boundingSphere.center : Vector4.ZERO; _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { meshBindings.addConsumer(_bindingsConsumer); sceneBindings.addConsumer(_bindingsConsumer); if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { _bindingsConsumer.setProperty(name, value); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
fix DrawCall.updateGeometry() to avoid re-computing normals if they already exist when computing tangent space
fix DrawCall.updateGeometry() to avoid re-computing normals if they already exist when computing tangent space
ActionScript
mit
aerys/minko-as3
043e86ca1084816409248eaafec2cdcdbff1fbcb
exporter/src/main/as/flump/export/ProjectController.as
exporter/src/main/as/flump/export/ProjectController.as
// // Flump - Copyright 2013 Flump Authors package flump.export { import aspire.util.F; import aspire.util.StringUtil; import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.events.PropertyChangeEvent; import mx.managers.PopUpManager; import spark.components.DataGrid; import spark.components.Window; import spark.events.GridSelectionEvent; public class ProjectController extends ExportController { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function ProjectController (configFile :File = null) { _win = new ProjectWindow(); _win.open(); _errorsGrid = _win.errors; _flashDocsGrid = _win.libraries; _confFile = configFile; if (_confFile == null) { _conf = new ProjectConf(); } else { if (readProjectConfig()) { setImportDirectory(_importDirectory); } else { _importDirectory = null; _confFile = null; _conf = null; } } var curSelection :DocStatus = null; _flashDocsGrid.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _flashDocsGrid.selectedIndices); onSelectedItemChanged(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onSelectedItemChanged); } var newSelection :DocStatus = _flashDocsGrid.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onSelectedItemChanged); } curSelection = newSelection; }); // Reload _win.reload.addEventListener(MouseEvent.CLICK, F.bind(reloadNow)); // Export _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _flashDocsGrid.selectedItems) { exportFlashDocument(status); } }); // Preview _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { FlumpApp.app.showPreviewWindow(_conf, _flashDocsGrid.selectedItem.lib); }); // Export All, Modified _win.exportAll.addEventListener(MouseEvent.CLICK, F.bind(exportAll, false)); _win.exportModified.addEventListener(MouseEvent.CLICK, F.bind(exportAll, true)); // Import/Export directories _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.connect(setImportDirectory); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.connect(F.bind(reloadNow)); _importChooser.changed.connect(F.bind(setProjectDirty, true)); _exportChooser.changed.connect(F.bind(setProjectDirty, true)); // Edit Formats var editFormatsController :EditFormatsController = null; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormatsController == null || editFormatsController.closed) { editFormatsController = new EditFormatsController(_conf); editFormatsController.formatsChanged.connect(updateUiFromConf); editFormatsController.formatsChanged.connect(F.bind(setProjectDirty, true)); } else { editFormatsController.show(); } }); _win.addEventListener(Event.CLOSING, function (e :Event) :void { if (_projectDirty) { e.preventDefault(); promptToSaveChanges(); } }); updateUiFromConf(); updateWindowTitle(); setupMenus(); } public function get projectDirty () :Boolean { return _projectDirty; } public function save (onSuccess :Function = null) :void { if (_confFile == null) { saveAs(onSuccess); } else { saveConf(onSuccess); } } public function saveAs (onSuccess :Function = null) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { // Ensure the filename ends with .flump if (!StringUtil.endsWith(file.name.toLowerCase(), ".flump")) { file = file.parent.resolvePath(file.name + ".flump"); } _confFile = file; saveConf(onSuccess); }); file.browseForSave("Save Flump Configuration"); } public function get configFile () :File { return _confFile; } public function get win () :Window { return _win; } protected function exportAll (modifiedOnly :Boolean) :void { // if we have one or more combined export format, publish them if (hasCombinedExportConfig()) { var valid :Boolean = _flashDocsGrid.dataProvider.toArray() .every(function (status :DocStatus,..._) :Boolean { return status.isValid; }); if (valid) exportCombined(); } // now publish any appropriate single formats if (hasSingleExportConfig()) { for each (var status :DocStatus in _flashDocsGrid.dataProvider.toArray()) { if (status.isValid && (!modifiedOnly || status.isModified)) { exportFlashDocument(status); } } } } protected function promptToSaveChanges () :void { var unsavedWindow :UnsavedChangesWindow = new UnsavedChangesWindow(); unsavedWindow.x = (_win.width - unsavedWindow.width) * 0.5; unsavedWindow.y = (_win.height - unsavedWindow.height) * 0.5; PopUpManager.addPopUp(unsavedWindow, _win, true); unsavedWindow.closeButton.visible = false; unsavedWindow.prompt.text = "Save changes to '" + projectName + "'?"; unsavedWindow.cancel.addEventListener(MouseEvent.CLICK, function (..._) :void { PopUpManager.removePopUp(unsavedWindow); }); unsavedWindow.dontSave.addEventListener(MouseEvent.CLICK, function (..._) :void { PopUpManager.removePopUp(unsavedWindow); _projectDirty = false; _win.close(); }); unsavedWindow.save.addEventListener(MouseEvent.CLICK, function (..._) :void { PopUpManager.removePopUp(unsavedWindow); save(F.bind(_win.close)); }); } protected function setupMenus () :void { if (NativeApplication.supportsMenu) { // If we're on a Mac, the menus will be set up at the application level. return; } _win.nativeWindow.menu = new NativeMenu(); var fileMenuItem :NativeMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New Project"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { FlumpApp.app.newProject(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open Project..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { FlumpApp.app.showOpenProjectDialog(); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project"), 3); saveMenuItem.keyEquivalent = "s"; saveMenuItem.addEventListener(Event.SELECT, F.bind(save)); const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, F.bind(saveAs)); } protected function updateWindowTitle () :void { var name :String = this.projectName; if (_projectDirty) name += "*"; _win.title = name; } protected function saveConf (onSuccess :Function) :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); setProjectDirty(false); updateWindowTitle(); if (onSuccess != null) { onSuccess(); } }); } protected function reloadNow () :void { setImportDirectory(_importChooser.dir); onSelectedItemChanged(); } protected function updateUiFromConf (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } var formatNames :Array = []; var hasCombined :Boolean = false; if (_conf != null) { for each (var export :ExportConf in _conf.exports) { formatNames.push(export.description); hasCombined ||= export.combine; } } _win.formatOverview.text = formatNames.join(", "); _win.exportAll.label = hasCombined ? "Export Combined" : "Export All"; checkValid(); _win.exportModified.enabled = !hasCombined; _win.export.enabled = !hasCombined; updateWindowTitle(); } protected function hasCombinedExportConfig () :Boolean { if (_conf == null) return false; for each (var config :ExportConf in _conf.exports) if (config.combine) return true; return false; } protected function hasSingleExportConfig () :Boolean { if (_conf == null) return false; for each (var config :ExportConf in _conf.exports) if (!config.combine) return true; return false; } protected function onSelectedItemChanged (..._) :void { _win.export.enabled = !hasCombinedExportConfig() && _exportChooser.dir != null && _flashDocsGrid.selectionLength > 0 && _flashDocsGrid.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _flashDocsGrid.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; _win.selectedItem.text = (status == null ? "" : status.path); } protected function createPublisher () :Publisher { if (_exportChooser.dir == null || _conf.exports.length == 0) return null; return new Publisher(_exportChooser.dir, _conf, projectName); } protected function setImportDirectory (dir :File) :void { _importDirectory = dir; _flashDocsGrid.dataProvider.removeAll(); _errorsGrid.dataProvider.removeAll(); if (dir == null) { return; } if (_docFinder != null) { _docFinder.shutdownNow(); } _docFinder = new Executor(); findFlashDocuments(dir, _docFinder, true); _win.reload.enabled = true; } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; try { if (_exportChooser.dir == null) { throw new Error("No export directory specified."); } if (_conf.exports.length == 0) { throw new Error("No export formats specified."); } var published :int = createPublisher().publishSingle(status.lib); if (published == 0) { throw new Error("No suitable formats were found for publishing"); } } catch (e :Error) { log.warning("publishing failed", e); ErrorWindowMgr.showErrorPopup("Publishing Failed", e.message, _win); } stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function exportCombined () :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; try { if (_exportChooser.dir == null) { throw new Error("No export directory specified."); } if (_conf.exports.length == 0) { throw new Error("No export formats specified."); } var published :int = createPublisher().publishCombined(getLibs()); if (published == 0) { throw new Error("No suitable formats were found for publishing"); } } catch (e :Error) { log.warning("publishing failed", e); ErrorWindowMgr.showErrorPopup("Publishing Failed", e.message, _win); } stage.quality = prevQuality; for each (var status :DocStatus in _flashDocsGrid.dataProvider) { status.updateModified(Ternary.FALSE); } } protected function checkModified () :void { var libs :Vector.<XflLibrary> = getLibs(); if (libs == null) return; // not done loading yet // all the docs we know about have been loaded var pub :Publisher = createPublisher(); for (var ii :int = 0; ii < libs.length; ii++) { var status :DocStatus = _flashDocsGrid.dataProvider[ii]; status.updateModified(Ternary.of(pub == null || pub.modified(libs, ii))) } } protected function checkValid () :void { if (getLibs() == null) { _win.exportAll.enabled = false; return; } _win.exportAll.enabled = !hasCombinedExportConfig() || _flashDocsGrid.dataProvider.toArray() .every(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); } override protected function setProjectDirty (val :Boolean) :void { super.setProjectDirty(val); updateWindowTitle(); } override protected function handleParseError (err :ParseError) :void { _errorsGrid.dataProvider.addItem(err); } override protected function docLoadSucceeded (doc :DocStatus, lib :XflLibrary) :void { super.docLoadSucceeded(doc, lib); checkModified(); checkValid(); } override protected function docLoadFailed (file :File, doc :DocStatus, err :*) :void { super.docLoadFailed(file, doc, err); trace("Failed to load " + file.nativePath + ": " + err); throw err; } override protected function addDoc (status :DocStatus) :void { _flashDocsGrid.dataProvider.addItem(status); } override protected function getDocs () :Array { return _flashDocsGrid.dataProvider.toArray(); } protected var _docFinder :Executor; protected var _win :ProjectWindow; protected var _flashDocsGrid :DataGrid; protected var _errorsGrid :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; } }
// // Flump - Copyright 2013 Flump Authors package flump.export { import aspire.util.F; import aspire.util.StringUtil; import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.events.PropertyChangeEvent; import mx.managers.PopUpManager; import spark.components.DataGrid; import spark.components.Window; import spark.events.GridSelectionEvent; public class ProjectController extends ExportController { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function ProjectController (configFile :File = null) { _win = new ProjectWindow(); _win.open(); _errorsGrid = _win.errors; _flashDocsGrid = _win.libraries; _confFile = configFile; if (_confFile == null) { _conf = new ProjectConf(); } else { if (readProjectConfig()) { setImportDirectory(_importDirectory); } else { _importDirectory = null; _confFile = null; _conf = null; } } var curSelection :DocStatus = null; _flashDocsGrid.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _flashDocsGrid.selectedIndices); onSelectedItemChanged(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onSelectedItemChanged); } var newSelection :DocStatus = _flashDocsGrid.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, onSelectedItemChanged); } curSelection = newSelection; }); // Reload _win.reload.addEventListener(MouseEvent.CLICK, F.bind(reloadNow)); // Export _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _flashDocsGrid.selectedItems) { exportFlashDocument(status); } }); // Preview _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { FlumpApp.app.showPreviewWindow(_conf, _flashDocsGrid.selectedItem.lib); }); // Export All, Modified _win.exportAll.addEventListener(MouseEvent.CLICK, F.bind(exportAll, false)); _win.exportModified.addEventListener(MouseEvent.CLICK, F.bind(exportAll, true)); // Import/Export directories _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.connect(setImportDirectory); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.connect(F.bind(reloadNow)); _importChooser.changed.connect(F.bind(setProjectDirty, true)); _exportChooser.changed.connect(F.bind(setProjectDirty, true)); // Edit Formats var editFormatsController :EditFormatsController = null; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormatsController == null || editFormatsController.closed) { editFormatsController = new EditFormatsController(_conf); editFormatsController.formatsChanged.connect(updateUiFromConf); editFormatsController.formatsChanged.connect(F.bind(setProjectDirty, true)); } else { editFormatsController.show(); } }); _win.addEventListener(Event.CLOSING, function (e :Event) :void { if (_projectDirty) { e.preventDefault(); promptToSaveChanges(); } }); updateUiFromConf(); updateWindowTitle(); setupMenus(); } public function get projectDirty () :Boolean { return _projectDirty; } public function save (onSuccess :Function = null) :void { if (_confFile == null) { saveAs(onSuccess); } else { saveConf(onSuccess); } } public function saveAs (onSuccess :Function = null) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { // Ensure the filename ends with .flump if (!StringUtil.endsWith(file.name.toLowerCase(), ".flump")) { file = file.parent.resolvePath(file.name + ".flump"); } _confFile = file; saveConf(onSuccess); }); file.browseForSave("Save Flump Configuration"); } public function get configFile () :File { return _confFile; } public function get win () :Window { return _win; } protected function exportAll (modifiedOnly :Boolean) :void { // if we have one or more combined export format, publish them if (hasCombinedExportConfig()) { var valid :Boolean = _flashDocsGrid.dataProvider.toArray() .every(function (status :DocStatus,..._) :Boolean { return status.isValid; }); if (valid) exportCombined(); } // now publish any appropriate single formats if (hasSingleExportConfig()) { for each (var status :DocStatus in _flashDocsGrid.dataProvider.toArray()) { if (status.isValid && (!modifiedOnly || status.isModified)) { exportFlashDocument(status); } } } } protected function promptToSaveChanges () :void { var unsavedWindow :UnsavedChangesWindow = new UnsavedChangesWindow(); unsavedWindow.x = (_win.width - unsavedWindow.width) * 0.5; unsavedWindow.y = (_win.height - unsavedWindow.height) * 0.5; PopUpManager.addPopUp(unsavedWindow, _win, true); unsavedWindow.closeButton.visible = false; unsavedWindow.prompt.text = "Save changes to '" + projectName + "'?"; unsavedWindow.cancel.addEventListener(MouseEvent.CLICK, function (..._) :void { PopUpManager.removePopUp(unsavedWindow); }); unsavedWindow.dontSave.addEventListener(MouseEvent.CLICK, function (..._) :void { PopUpManager.removePopUp(unsavedWindow); _projectDirty = false; _win.close(); }); unsavedWindow.save.addEventListener(MouseEvent.CLICK, function (..._) :void { PopUpManager.removePopUp(unsavedWindow); save(F.bind(_win.close)); }); } protected function setupMenus () :void { if (NativeApplication.supportsMenu) { // If we're on a Mac, the menus will be set up at the application level. return; } _win.nativeWindow.menu = new NativeMenu(); var fileMenuItem :NativeMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New Project"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { FlumpApp.app.newProject(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open Project..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { FlumpApp.app.showOpenProjectDialog(); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project"), 3); saveMenuItem.keyEquivalent = "s"; saveMenuItem.addEventListener(Event.SELECT, F.bind(save)); const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save Project As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, F.bind(saveAs)); } protected function updateWindowTitle () :void { var name :String = this.projectName; if (_projectDirty) name += "*"; _win.title = name; } protected function saveConf (onSuccess :Function) :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); setProjectDirty(false); updateWindowTitle(); if (onSuccess != null) { onSuccess(); } }); } protected function reloadNow () :void { setImportDirectory(_importChooser.dir); onSelectedItemChanged(); } protected function updateUiFromConf (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } var formatNames :Array = []; var hasCombined :Boolean = false; if (_conf != null) { for each (var exportConf :ExportConf in _conf.exports) { formatNames.push(exportConf.description); hasCombined ||= exportConf.combine; } } _win.formatOverview.text = formatNames.join(", "); _win.exportAll.label = hasCombined ? "Export Combined" : "Export All"; checkValid(); _win.exportModified.enabled = !hasCombined; _win.export.enabled = !hasCombined; updateWindowTitle(); } protected function hasCombinedExportConfig () :Boolean { if (_conf == null) return false; for each (var config :ExportConf in _conf.exports) if (config.combine) return true; return false; } protected function hasSingleExportConfig () :Boolean { if (_conf == null) return false; for each (var config :ExportConf in _conf.exports) if (!config.combine) return true; return false; } protected function onSelectedItemChanged (..._) :void { _win.export.enabled = !hasCombinedExportConfig() && _exportChooser.dir != null && _flashDocsGrid.selectionLength > 0 && _flashDocsGrid.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _flashDocsGrid.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; _win.selectedItem.text = (status == null ? "" : status.path); } protected function createPublisher () :Publisher { if (_exportChooser.dir == null || _conf.exports.length == 0) return null; return new Publisher(_exportChooser.dir, _conf, projectName); } protected function setImportDirectory (dir :File) :void { _importDirectory = dir; _flashDocsGrid.dataProvider.removeAll(); _errorsGrid.dataProvider.removeAll(); if (dir == null) { return; } if (_docFinder != null) { _docFinder.shutdownNow(); } _docFinder = new Executor(); findFlashDocuments(dir, _docFinder, true); _win.reload.enabled = true; } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; try { if (_exportChooser.dir == null) { throw new Error("No export directory specified."); } if (_conf.exports.length == 0) { throw new Error("No export formats specified."); } var published :int = createPublisher().publishSingle(status.lib); if (published == 0) { throw new Error("No suitable formats were found for publishing"); } } catch (e :Error) { log.warning("publishing failed", e); ErrorWindowMgr.showErrorPopup("Publishing Failed", e.message, _win); } stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function exportCombined () :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; try { if (_exportChooser.dir == null) { throw new Error("No export directory specified."); } if (_conf.exports.length == 0) { throw new Error("No export formats specified."); } var published :int = createPublisher().publishCombined(getLibs()); if (published == 0) { throw new Error("No suitable formats were found for publishing"); } } catch (e :Error) { log.warning("publishing failed", e); ErrorWindowMgr.showErrorPopup("Publishing Failed", e.message, _win); } stage.quality = prevQuality; for each (var status :DocStatus in _flashDocsGrid.dataProvider) { status.updateModified(Ternary.FALSE); } } protected function checkModified () :void { var libs :Vector.<XflLibrary> = getLibs(); if (libs == null) return; // not done loading yet // all the docs we know about have been loaded var pub :Publisher = createPublisher(); for (var ii :int = 0; ii < libs.length; ii++) { var status :DocStatus = _flashDocsGrid.dataProvider[ii]; status.updateModified(Ternary.of(pub == null || pub.modified(libs, ii))) } } protected function checkValid () :void { if (getLibs() == null) { _win.exportAll.enabled = false; return; } _win.exportAll.enabled = !hasCombinedExportConfig() || _flashDocsGrid.dataProvider.toArray() .every(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); } override protected function setProjectDirty (val :Boolean) :void { super.setProjectDirty(val); updateWindowTitle(); } override protected function handleParseError (err :ParseError) :void { _errorsGrid.dataProvider.addItem(err); } override protected function docLoadSucceeded (doc :DocStatus, lib :XflLibrary) :void { super.docLoadSucceeded(doc, lib); checkModified(); checkValid(); } override protected function docLoadFailed (file :File, doc :DocStatus, err :*) :void { super.docLoadFailed(file, doc, err); trace("Failed to load " + file.nativePath + ": " + err); throw err; } override protected function addDoc (status :DocStatus) :void { _flashDocsGrid.dataProvider.addItem(status); } override protected function getDocs () :Array { return _flashDocsGrid.dataProvider.toArray(); } protected var _docFinder :Executor; protected var _win :ProjectWindow; protected var _flashDocsGrid :DataGrid; protected var _errorsGrid :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; } }
Remove unused import
Remove unused import
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump
30ff1a7b33fa6d2c884e25b7d3afc89fa933beb5
Agent.as
Agent.as
package { import flash.display.Sprite; import flash.events.Event; import flash.events.DataEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.XMLSocket; import flash.system.System; import flash.utils.getQualifiedClassName; import flash.sampler.*; public class Agent extends Sprite { private static const HOST:String = "localhost"; private static const PORT:int = 42624; private static const PREFIX:String = "[AGENT]"; private var _host:String; private var _port:int; private var _socket:XMLSocket; private var _connected:Boolean; public function Agent() { trace(PREFIX, "Loaded"); _host = loaderInfo.parameters["host"] || HOST; _port = loaderInfo.parameters["port"] || PORT; _socket = new XMLSocket(); _socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fail); _socket.addEventListener(IOErrorEvent.IO_ERROR, fail); _socket.addEventListener(DataEvent.DATA, dataReceived); _socket.addEventListener(Event.CONNECT, connected); _socket.addEventListener(Event.CLOSE, close); connect(); } private function dataReceived(e:DataEvent):void { trace(PREFIX, "Received command", e.data); switch( e.data ) { case "GET MEMORY": _socket.send("MEMORY: " + new Date().time + " " + System.totalMemory); return; case "START SAMPLING": startSampling(); _socket.send("OK START"); return; case "PAUSE SAMPLING": pauseSampling(); _socket.send("OK PAUSE"); trace(getSampleCount()); for each (var s:Sample in getSamples()) { trace(sampleToString(s)); } return; case "STOP SAMPLING": stopSampling(); _socket.send("OK STOP"); return; case "GET SAMPLES": _socket.send("SENDING SAMPLES: " + ) } } private function sampleToString(s:Sample):String { if( s is NewObjectSample ) { var nos:NewObjectSample = s as NewObjectSample; return "[NewObjectSample" + "\n id: " + nos.id + "\n type: " + getQualifiedClassName(nos.type) + "\n time: " + nos.time + "\n stack: " + stackToString(nos.stack) + "\n]"; } else if( s is DeleteObjectSample ) { var dos:DeleteObjectSample = s as DeleteObjectSample; return "[DeleteObjectSample" + "\n id: " + dos.id + "\n size: " + dos.size + "\n time: " + dos.time + "\n stack: " + stackToString(dos.stack) + "\n]"; } return "[Sample" + "\n time: " + s.time + "\n stack: " + stackToString(s.stack) + "\n]"; } private function stackToString(stack:Array):String { if( null == stack ) { return "(none)"; } var separator:String = "\n "; return separator + stack.join(separator); } private function connect():void { trace(PREFIX, "Trying to connect to", _host, ":", _port); try { _socket.connect(_host, _port); } catch (e:Error) { trace(PREFIX, "Unable to connect", e); } } private function connected(e:Event):void { _connected = true; trace(PREFIX, "Connected"); _socket.send("AGENT READY"); } private function close(e:Event):void { _connected = false; trace(PREFIX, "Disconnected"); } private function fail(e:Event):void { _socket.close(); _connected = false; trace(PREFIX, "Communication failure", e); } } }
package { import flash.display.Sprite; import flash.events.Event; import flash.events.DataEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.net.XMLSocket; import flash.system.System; import flash.utils.getTimer; import flash.utils.getQualifiedClassName; import flash.sampler.*; public class Agent extends Sprite { private static const HOST:String = "localhost"; private static const PORT:int = 42624; private static const PREFIX:String = "[AGENT]"; private var _host:String; private var _port:int; private var _socket:XMLSocket; private var _connected:Boolean; public function Agent() { trace(PREFIX, "Loaded"); _host = loaderInfo.parameters["host"] || HOST; _port = loaderInfo.parameters["port"] || PORT; _socket = new XMLSocket(); _socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, fail); _socket.addEventListener(IOErrorEvent.IO_ERROR, fail); _socket.addEventListener(DataEvent.DATA, dataReceived); _socket.addEventListener(Event.CONNECT, connected); _socket.addEventListener(Event.CLOSE, close); connect(); } private function dataReceived(e:DataEvent):void { trace(PREFIX, "Received command", e.data); switch( e.data ) { case "GET MEMORY": _socket.send("MEMORY: " + new Date().time + " " + System.totalMemory); return; case "START SAMPLING": startSampling(); _socket.send("OK START"); return; case "PAUSE SAMPLING": pauseSampling(); _socket.send("OK PAUSE"); return; case "STOP SAMPLING": stopSampling(); _socket.send("OK STOP"); return; case "GET SAMPLES": trace(PREFIX, "Sending", getSampleCount(), "samples at", getTimer()); _socket.send("SENDING SAMPLES: " + getSampleCount()); for each (var s:Sample in getSamples()) { _socket.send(sampleToString(s)); } trace(PREFIX, "Done sending samples"); return; } } private function sampleToString(s:Sample):String { if( s is NewObjectSample ) { var nos:NewObjectSample = s as NewObjectSample; return "[NewObjectSample" + "\n time: " + nos.time + "\n id: " + nos.id + "\n type: " + getQualifiedClassName(nos.type) + stackToString(nos.stack) + "\n]"; } else if( s is DeleteObjectSample ) { var dos:DeleteObjectSample = s as DeleteObjectSample; return "[DeleteObjectSample" + "\n time: " + dos.time + "\n id: " + dos.id + "\n size: " + dos.size + stackToString(dos.stack) + "\n]"; } return "[Sample" + "\n time: " + s.time + stackToString(s.stack) + "\n]"; } private function stackToString(stack:Array):String { if( null == stack ) { return ""; } var separator:String = "\n "; return "\n stack: " + separator + stack.join(separator); } private function connect():void { trace(PREFIX, "Trying to connect to", _host, ":", _port); try { _socket.connect(_host, _port); } catch (e:Error) { trace(PREFIX, "Unable to connect", e); } } private function connected(e:Event):void { _connected = true; trace(PREFIX, "Connected"); _socket.send("AGENT READY"); } private function close(e:Event):void { _connected = false; trace(PREFIX, "Disconnected"); } private function fail(e:Event):void { _socket.close(); _connected = false; trace(PREFIX, "Communication failure", e); } } }
fix sending samples
fix sending samples
ActionScript
apache-2.0
osi/flash-profiler
eb62cbf80b0a3a557f34c2502cd9f568e0686fc7
src/aerys/minko/scene/controller/AbstractScriptController.as
src/aerys/minko/scene/controller/AbstractScriptController.as
package aerys.minko.scene.controller { import aerys.minko.ns.minko_scene; import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.KeyboardManager; import aerys.minko.type.MouseManager; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_scene; public class AbstractScriptController extends EnterFrameController { private var _scene : Scene; private var _started : Dictionary; private var _lastTime : Number; private var _deltaTime : Number; private var _currentTarget : ISceneNode; private var _viewport : Viewport; private var _targetsListLocked : Boolean; private var _targetsToAdd : Vector.<ISceneNode>; private var _targetsToRemove : Vector.<ISceneNode>; private var _updateRate : Number = 0.; protected function get scene() : Scene { return _scene; } protected function get deltaTime() : Number { return _deltaTime; } protected function get keyboard() : KeyboardManager { return _viewport.keyboardManager; } protected function get mouse() : MouseManager { return _viewport.mouseManager; } protected function get viewport() : Viewport { return _viewport; } protected function get updateRate() : Number { return _updateRate; } protected function set updateRate(value : Number) : void { _updateRate = value; } public function AbstractScriptController(targetType : Class = null) { super(targetType); initialize(); } protected function initialize() : void { _started = new Dictionary(true); } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (_scene && scene != _scene) throw new Error( 'The same ScriptController instance can not be used in more than one scene ' + 'at a time.' ); _scene = scene; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene)) _scene = null; } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { _deltaTime = time - _lastTime; if (_updateRate != 0. && deltaTime < 1000. / _updateRate) return; _viewport = viewport; _lastTime = time; lockTargetsList(); beforeUpdate(); var numTargets : uint = this.numTargets; for (var i : uint = 0; i < numTargets; ++i) { var target : ISceneNode = getTarget(i); if (target.scene) { if (!_started[target]) { _started[target] = true; start(target); } update(target); } else if (_started[target]) { _started[target] = false; stop(target); } } afterUpdate(); unlockTargetsList(); } /** * The 'start' method is called on a script target at the first frame occuring after it * has been added to the scene. * * @param target * */ protected function start(target : ISceneNode) : void { // nothing } /** * The 'beforeUpdate' method is called before each target is updated via the 'update' * method. * */ protected function beforeUpdate() : void { // nothing } protected function update(target : ISceneNode) : void { // nothing } /** * The 'afterUpdate' method is called after each target has been updated via the 'update' * method. * */ protected function afterUpdate() : void { // nothing } /** * The 'start' method is called on a script target at the first frame occuring after it * has been removed from the scene. * * @param target * */ protected function stop(target : ISceneNode) : void { // nothing } private function lockTargetsList() : void { _targetsListLocked = true; } private function unlockTargetsList() : void { _targetsListLocked = false; if (_targetsToAdd) { var numTargetsToAdd : uint = _targetsToAdd.length; for (var i : uint = 0; i < numTargetsToAdd; ++i) addTarget(_targetsToAdd[i]); _targetsToAdd = null; } if (_targetsToRemove) { var numTargetsToRemove : uint = _targetsToRemove.length; for (var j : uint = 0; j < numTargetsToRemove; ++j) removeTarget(_targetsToRemove[j]); _targetsToRemove = null; } } override minko_scene function addTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToAdd) _targetsToAdd.push(target); else _targetsToAdd = new <ISceneNode>[target]; } else super.addTarget(target); } override minko_scene function removeTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToRemove) _targetsToRemove.push(target); else _targetsToRemove = new <ISceneNode>[target]; } else super.removeTarget(target); } } }
package aerys.minko.scene.controller { import aerys.minko.ns.minko_scene; import aerys.minko.render.Viewport; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.KeyboardManager; import aerys.minko.type.MouseManager; import flash.display.BitmapData; import flash.utils.Dictionary; use namespace minko_scene; public class AbstractScriptController extends EnterFrameController { private var _scene : Scene; private var _started : Dictionary; private var _time : Number; private var _lastTime : Number; private var _deltaTime : Number; private var _currentTarget : ISceneNode; private var _viewport : Viewport; private var _targetsListLocked : Boolean; private var _targetsToAdd : Vector.<ISceneNode>; private var _targetsToRemove : Vector.<ISceneNode>; private var _updateRate : Number; protected function get scene() : Scene { return _scene; } protected function get time() : Number { return _time; } protected function get deltaTime() : Number { return _deltaTime; } protected function get keyboard() : KeyboardManager { return _viewport.keyboardManager; } protected function get mouse() : MouseManager { return _viewport.mouseManager; } protected function get viewport() : Viewport { return _viewport; } protected function get updateRate() : Number { return _updateRate; } protected function set updateRate(value : Number) : void { _updateRate = value; } public function AbstractScriptController(targetType : Class = null) { super(targetType); initialize(); } protected function initialize() : void { _started = new Dictionary(true); } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (_scene && scene != _scene) throw new Error( 'The same ScriptController instance can not be used in more than one scene ' + 'at a time.' ); _scene = scene; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene)) _scene = null; } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { _deltaTime = time - _lastTime; _time = time; if (_updateRate != 0. && deltaTime < 1000. / _updateRate) return; _viewport = viewport; lockTargetsList(); beforeUpdate(); var numTargets : uint = this.numTargets; for (var i : uint = 0; i < numTargets; ++i) { var target : ISceneNode = getTarget(i); if (target.scene) { if (!_started[target]) { _started[target] = true; start(target); } update(target); } else if (_started[target]) { _started[target] = false; stop(target); } } afterUpdate(); unlockTargetsList(); _lastTime = time; } /** * The 'start' method is called on a script target at the first frame occuring after it * has been added to the scene. * * @param target * */ protected function start(target : ISceneNode) : void { // nothing } /** * The 'beforeUpdate' method is called before each target is updated via the 'update' * method. * */ protected function beforeUpdate() : void { // nothing } protected function update(target : ISceneNode) : void { // nothing } /** * The 'afterUpdate' method is called after each target has been updated via the 'update' * method. * */ protected function afterUpdate() : void { // nothing } /** * The 'start' method is called on a script target at the first frame occuring after it * has been removed from the scene. * * @param target * */ protected function stop(target : ISceneNode) : void { // nothing } private function lockTargetsList() : void { _targetsListLocked = true; } private function unlockTargetsList() : void { _targetsListLocked = false; if (_targetsToAdd) { var numTargetsToAdd : uint = _targetsToAdd.length; for (var i : uint = 0; i < numTargetsToAdd; ++i) addTarget(_targetsToAdd[i]); _targetsToAdd = null; } if (_targetsToRemove) { var numTargetsToRemove : uint = _targetsToRemove.length; for (var j : uint = 0; j < numTargetsToRemove; ++j) removeTarget(_targetsToRemove[j]); _targetsToRemove = null; } } override minko_scene function addTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToAdd) _targetsToAdd.push(target); else _targetsToAdd = new <ISceneNode>[target]; } else super.addTarget(target); } override minko_scene function removeTarget(target : ISceneNode) : void { if (_targetsListLocked) { if (_targetsToRemove) _targetsToRemove.push(target); else _targetsToRemove = new <ISceneNode>[target]; } else super.removeTarget(target); } } }
add AbstractScriptController.time protected property
add AbstractScriptController.time protected property
ActionScript
mit
aerys/minko-as3
88a5363f8a99961ff2ec7431975d733ae5c4b1c5
src/aerys/minko/type/binding/DataBindings.as
src/aerys/minko/type/binding/DataBindings.as
package aerys.minko.type.binding { import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; public final class DataBindings { private var _owner : ISceneNode = null; private var _providers : Vector.<IDataProvider> = new <IDataProvider>[]; private var _bindingNames : Vector.<String> = new Vector.<String>(); private var _bindingNameToValue : Object = {}; private var _bindingNameToChangedSignal : Object = {}; private var _bindingNameToProvider : Object = {}; private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] public function get owner() : ISceneNode { return _owner; } public function get numProviders() : uint { return _providers.length; } public function get numProperties() : uint { return _bindingNames.length; } public function DataBindings(owner : ISceneNode) { _owner = owner; } public function contains(dataProvider : IDataProvider) : Boolean { return _providers.indexOf(dataProvider) != -1; } public function addProvider(provider : IDataProvider) : void { if (_providerToBindingNames[provider]) throw new Error('This provider is already bound.'); var providerBindingNames : Vector.<String> = new <String>[]; var dataDescriptor : Object = provider.dataDescriptor; provider.changed.add(providerChangedHandler); _providerToBindingNames[provider] = providerBindingNames; _providers.push(provider); for (var attrName : String in dataDescriptor) { // if this provider attribute is also a dataprovider, let's also bind it var bindingName : String = dataDescriptor[attrName]; var attribute : Object = provider[attrName]; if (_bindingNames.indexOf(bindingName) != -1) throw new Error( 'Another data provider is already declaring the \'' + bindingName + '\' property.' ); _bindingNameToProvider[bindingName] = provider; _bindingNameToValue[bindingName] = attribute; providerBindingNames.push(bindingName); _bindingNames.push(bindingName); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, attribute); } } public function removeProvider(provider : IDataProvider) : void { var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider]; var tmpValues : Object = {}; if (providerBindingsNames == null) throw new ArgumentError('Unkown provider.'); var numBindings : uint = _bindingNames.length; for (var indexRead : uint = 0, indexWrite : uint = 0; indexRead < numBindings; ++indexRead) { var bindingName : String = _bindingNames[indexRead]; if (providerBindingsNames.indexOf(bindingName) != -1) { tmpValues[bindingName] = _bindingNameToValue[bindingName]; delete _bindingNameToValue[bindingName]; delete _bindingNameToProvider[bindingName]; } else _bindingNames[indexWrite++] = _bindingNames[indexRead]; } _bindingNames.length = indexWrite; provider.changed.remove(providerChangedHandler); _providers.splice(_providers.indexOf(provider), 1); delete _providerToBindingNames[provider]; for each (bindingName in providerBindingsNames) { var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal; if (changedSignal != null) { changedSignal.execute( this, bindingName, tmpValues[bindingName], null ); } } } public function removeAllProviders() : void { var numProviders : uint = this.numProviders; for (var providerId : int = numProviders - 1; providerId >= 0; --providerId) removeProvider(getProviderAt(providerId)); } public function hasCallback(bindingName : String, callback : Function) : Boolean { var signal : Signal = _bindingNameToChangedSignal[bindingName]; return signal != null && signal.hasCallback(callback); } public function addCallback(bindingName : String, callback : Function) : void { _bindingNameToChangedSignal[bindingName] ||= new Signal( 'DataBindings.changed[' + bindingName + ']' ); Signal(_bindingNameToChangedSignal[bindingName]).add(callback); } public function removeCallback(bindingName : String, callback : Function) : void { var signal : Signal = _bindingNameToChangedSignal[bindingName]; if (!signal) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); signal.remove(callback); if (signal.numCallbacks == 0) delete _bindingNameToChangedSignal[bindingName]; } public function getProviderAt(index : uint) : IDataProvider { return _providers[index]; } public function getProviderByBindingName(bindingName : String) : IDataProvider { if (_bindingNameToProvider[bindingName] == null) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); return _bindingNameToProvider[bindingName]; } public function propertyExists(bindingName : String) : Boolean { return _bindingNameToValue.hasOwnProperty(bindingName); } public function getProperty(bindingName : String) : * { if (_bindingNames.indexOf(bindingName) < 0) throw new Error('The property \'' + bindingName + '\' does not exist.'); return _bindingNameToValue[bindingName]; } public function getPropertyName(bindingIndex : uint) : String { if (bindingIndex > numProperties) throw new ArgumentError('No such binding'); return _bindingNames[bindingIndex]; } public function copySharedProvidersFrom(source : DataBindings) : void { var numProviders : uint = source._providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = source._providers[providerId]; if (provider.usage == DataProviderUsage.SHARED) addProvider(provider); } } private function providerChangedHandler(source : IDataProvider, attributeName : String) : void { if (attributeName == null) { throw new Error('DataProviders must change one property at a time.'); } else if (attributeName == 'dataDescriptor') { removeProvider(source); addProvider(source); } else { var bindingName : String = source.dataDescriptor[attributeName]; var oldValue : Object = _bindingNameToValue[bindingName]; var newValue : Object = source[attributeName]; _bindingNameToValue[bindingName] = newValue; if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, oldValue, newValue); } } } }
package aerys.minko.type.binding { import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; public final class DataBindings { private var _owner : ISceneNode = null; private var _providers : Vector.<IDataProvider> = new <IDataProvider>[]; private var _bindingNames : Vector.<String> = new Vector.<String>(); private var _bindingNameToValue : Object = {}; private var _bindingNameToChangedSignal : Object = {}; private var _bindingNameToProvider : Object = {}; private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] public function get owner() : ISceneNode { return _owner; } public function get numProviders() : uint { return _providers.length; } public function get numProperties() : uint { return _bindingNames.length; } public function DataBindings(owner : ISceneNode) { _owner = owner; } public function contains(dataProvider : IDataProvider) : Boolean { return _providers.indexOf(dataProvider) != -1; } public function addProvider(provider : IDataProvider) : void { if (_providerToBindingNames[provider]) throw new Error('This provider is already bound.'); var providerBindingNames : Vector.<String> = new <String>[]; var dataDescriptor : Object = provider.dataDescriptor; provider.changed.add(providerChangedHandler); _providerToBindingNames[provider] = providerBindingNames; _providers.push(provider); for (var attrName : String in dataDescriptor) { // if this provider attribute is also a dataprovider, let's also bind it var bindingName : String = dataDescriptor[attrName]; var attribute : Object = provider[attrName]; if (_bindingNames.indexOf(bindingName) != -1) throw new Error( 'Another data provider is already declaring the \'' + bindingName + '\' property.' ); _bindingNameToProvider[bindingName] = provider; _bindingNameToValue[bindingName] = attribute; providerBindingNames.push(bindingName); _bindingNames.push(bindingName); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, attribute); } } public function removeProvider(provider : IDataProvider) : void { var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider]; var tmpValues : Object = {}; if (providerBindingsNames == null) throw new ArgumentError('Unknown provider.'); var numBindings : uint = _bindingNames.length; for (var indexRead : uint = 0, indexWrite : uint = 0; indexRead < numBindings; ++indexRead) { var bindingName : String = _bindingNames[indexRead]; if (providerBindingsNames.indexOf(bindingName) != -1) { tmpValues[bindingName] = _bindingNameToValue[bindingName]; delete _bindingNameToValue[bindingName]; delete _bindingNameToProvider[bindingName]; } else _bindingNames[indexWrite++] = _bindingNames[indexRead]; } _bindingNames.length = indexWrite; provider.changed.remove(providerChangedHandler); _providers.splice(_providers.indexOf(provider), 1); delete _providerToBindingNames[provider]; for each (bindingName in providerBindingsNames) { var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal; if (changedSignal != null) { changedSignal.execute( this, bindingName, tmpValues[bindingName], null ); } } } public function removeAllProviders() : void { var numProviders : uint = this.numProviders; for (var providerId : int = numProviders - 1; providerId >= 0; --providerId) removeProvider(getProviderAt(providerId)); } public function hasCallback(bindingName : String, callback : Function) : Boolean { var signal : Signal = _bindingNameToChangedSignal[bindingName]; return signal != null && signal.hasCallback(callback); } public function addCallback(bindingName : String, callback : Function) : void { _bindingNameToChangedSignal[bindingName] ||= new Signal( 'DataBindings.changed[' + bindingName + ']' ); Signal(_bindingNameToChangedSignal[bindingName]).add(callback); } public function removeCallback(bindingName : String, callback : Function) : void { var signal : Signal = _bindingNameToChangedSignal[bindingName]; if (!signal) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); signal.remove(callback); if (signal.numCallbacks == 0) delete _bindingNameToChangedSignal[bindingName]; } public function getProviderAt(index : uint) : IDataProvider { return _providers[index]; } public function getProviderByBindingName(bindingName : String) : IDataProvider { if (_bindingNameToProvider[bindingName] == null) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); return _bindingNameToProvider[bindingName]; } public function propertyExists(bindingName : String) : Boolean { return _bindingNameToValue.hasOwnProperty(bindingName); } public function getProperty(bindingName : String) : * { if (_bindingNames.indexOf(bindingName) < 0) throw new Error('The property \'' + bindingName + '\' does not exist.'); return _bindingNameToValue[bindingName]; } public function getPropertyName(bindingIndex : uint) : String { if (bindingIndex > numProperties) throw new ArgumentError('No such binding'); return _bindingNames[bindingIndex]; } public function copySharedProvidersFrom(source : DataBindings) : void { var numProviders : uint = source._providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = source._providers[providerId]; if (provider.usage == DataProviderUsage.SHARED) addProvider(provider); } } private function providerChangedHandler(source : IDataProvider, attributeName : String) : void { if (attributeName == null) { throw new Error('DataProviders must change one property at a time.'); } else if (attributeName == 'dataDescriptor') { removeProvider(source); addProvider(source); } else { var bindingName : String = source.dataDescriptor[attributeName]; var oldValue : Object = _bindingNameToValue[bindingName]; var newValue : Object = source[attributeName]; _bindingNameToValue[bindingName] = newValue; if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, oldValue, newValue); } } } }
fix coding style and typo
fix coding style and typo
ActionScript
mit
aerys/minko-as3
4fcb6ed2467ef578900280a18f7ec0ae97b88fd4
Bin/Data/Scripts/Editor/EditorSpawn.as
Bin/Data/Scripts/Editor/EditorSpawn.as
// Urho3D spawn editor LineEdit@ randomRotationX; LineEdit@ randomRotationY; LineEdit@ randomRotationZ; LineEdit@ randomScaleMinEdit; LineEdit@ randomScaleMaxEdit; LineEdit@ NumberSpawnedObjectsEdit; LineEdit@ spawnRadiusEdit; LineEdit@ spawnCountEdit; Window@ spawnWindow; Vector3 randomRotation=Vector3(0.f,0.f,0.f); float randomScaleMin=1; float randomScaleMax=1; float spawnCount=1; float spawnRadius=0; bool useNormal=true; int numberSpawnedObjects=1; Array<String> spawnedObjectsNames; void CreateSpawnEditor() { if (spawnWindow !is null) return; spawnWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorSpawnWindow.xml")); ui.root.AddChild(spawnWindow); spawnWindow.opacity = uiMaxOpacity; int height = Min(ui.root.height - 60, 500); spawnWindow.SetSize(300, height); CenterDialog(spawnWindow); HideSpawnEditor(); SubscribeToEvent(spawnWindow.GetChild("CloseButton", true), "Released", "HideSpawnEditor"); randomRotationX=spawnWindow.GetChild("RandomRotation.x", true); randomRotationY=spawnWindow.GetChild("RandomRotation.y", true); randomRotationZ=spawnWindow.GetChild("RandomRotation.z", true); randomRotationX.text=String(randomRotation.x); randomRotationY.text=String(randomRotation.y); randomRotationZ.text=String(randomRotation.z); randomScaleMinEdit=spawnWindow.GetChild("RandomScaleMin", true); randomScaleMaxEdit=spawnWindow.GetChild("RandomScaleMax", true); randomScaleMinEdit.text=String(randomScaleMin); randomScaleMaxEdit.text=String(randomScaleMax); CheckBox@ useNormalToggle = spawnWindow.GetChild("UseNormal", true); useNormalToggle.checked = useNormal; NumberSpawnedObjectsEdit=spawnWindow.GetChild("NumberSpawnedObjects", true); NumberSpawnedObjectsEdit.text=String(numberSpawnedObjects); spawnRadiusEdit=spawnWindow.GetChild("SpawnRadius", true); spawnCountEdit=spawnWindow.GetChild("SpawnCount", true); spawnRadiusEdit.text=String(spawnRadius); spawnCountEdit.text=String(spawnCount); SubscribeToEvent(randomRotationX, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationY, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationZ, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomScaleMinEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(randomScaleMaxEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(spawnRadiusEdit, "TextChanged", "EditSpawnRadius"); SubscribeToEvent(spawnCountEdit, "TextChanged", "EditSpawnCount"); SubscribeToEvent(useNormalToggle, "Toggled", "ToggleUseNormal"); SubscribeToEvent(NumberSpawnedObjectsEdit, "TextFinished", "UpdateNumberSpawnedObjects"); SubscribeToEvent(spawnWindow.GetChild("SetSpawnMode", true), "Released", "SetSpawnMode"); RefreshPickedObjects(); } bool ShowSpawnEditor() { spawnWindow.visible = true; spawnWindow.BringToFront(); return true; } void HideSpawnEditor() { spawnWindow.visible = false; } void PickSpawnObject() { @resourcePicker = GetResourcePicker(ShortStringHash("Node")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnObjectDone"); } void EditRandomRotation(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomRotation = Vector3(randomRotationX.text.ToFloat(), randomRotationY.text.ToFloat(), randomRotationZ.text.ToFloat()); UpdateHierarchyItem(editorScene); } void EditRandomScale(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomScaleMin = randomScaleMinEdit.text.ToFloat(); randomScaleMax = randomScaleMaxEdit.text.ToFloat(); UpdateHierarchyItem(editorScene); } void ToggleUseNormal(StringHash eventType, VariantMap& eventData) { useNormal = cast<CheckBox>(eventData["Element"].GetPtr()).checked; } void UpdateNumberSpawnedObjects(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); numberSpawnedObjects=edit.text.ToFloat(); edit.text=String(numberSpawnedObjects); RefreshPickedObjects(); } void EditSpawnRadius(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnRadius=edit.text.ToFloat(); } void EditSpawnCount(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnCount=edit.text.ToFloat(); } void RefreshPickedObjects() { spawnedObjectsNames.Resize(numberSpawnedObjects); ListView@ list = spawnWindow.GetChild("SpawnedObjects", true); list.RemoveAllItems(); for (uint i = 0; i < numberSpawnedObjects; ++i) { UIElement@ parent = CreateAttributeEditorParentWithSeparatedLabel(list, "Object " +(i+1), i, 0, false); UIElement@ container = UIElement(); container.SetLayout(LM_HORIZONTAL, 4, IntRect(10, 0, 4, 0)); container.SetFixedHeight(ATTR_HEIGHT); parent.AddChild(container); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, i, 0); nameEdit.name = "TextureNameEdit" + String(i); Button@ pickButton = CreateResourcePickerButton(container, null, i, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickSpawnedObject"); nameEdit.text = spawnedObjectsNames[i]; SubscribeToEvent(nameEdit, "TextFinished", "EditSpawnedObjectName"); } } void EditSpawnedObjectName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData["Element"].GetPtr(); int index = nameEdit.vars["Index"].GetUInt(); String resourceName = nameEdit.text; XMLFile@ xml = cache.GetResource("XMLFile", resourceName); if(xml !is null) spawnedObjectsNames[index]=resourceName; else spawnedObjectsNames[index]=String(""); RefreshPickedObjects(); } void PickSpawnedObject(StringHash eventType, VariantMap& eventData) { UIElement@ button = eventData["Element"].GetPtr(); resourcePickIndex = button.vars["Index"].GetUInt(); CreateFileSelector("Pick spawned object", "Pick", "Cancel", uiNodePath, uiSceneFilters, uiNodeFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnedObjectNameDone"); } void PickSpawnedObjectNameDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = GetResourceNameFromFullName(eventData["FileName"].GetString()); XMLFile@ xml = cache.GetResource("XMLFile", resourceName); if(xml !is null) spawnedObjectsNames[resourcePickIndex]=resourceName; else spawnedObjectsNames[resourcePickIndex]=String(""); @resourcePicker = null; RefreshPickedObjects(); } void SetSpawnMode(StringHash eventType, VariantMap& eventData) { editMode=EDIT_SPAWN; } void PlaceObject(Vector3 spawnPosition, Vector3 normal) { Quaternion spawnRotation; if(useNormal)spawnRotation=Quaternion(Vector3(0.f,1.f,0.f),normal); int number=RandomInt(0,spawnedObjectsNames.length); XMLFile@ xml = cache.GetResource("XMLFile", spawnedObjectsNames[number]); Node@ spawnedObject =editorScene.InstantiateXML(xml, spawnPosition, spawnRotation); if(spawnedObject is null) { spawnedObjectsNames[number]=spawnedObjectsNames[spawnedObjectsNames.length-1]; --numberSpawnedObjects; RefreshPickedObjects(); return; } spawnedObject.scale=spawnedObject.scale*Random(randomScaleMin, randomScaleMax); spawnedObject.Rotate(Quaternion(Random(-randomRotation.x,randomRotation.x), Random(-randomRotation.y,randomRotation.y),Random(-randomRotation.z,randomRotation.z)),false); CreateNodeAction action; action.Define(spawnedObject); SaveEditAction(action); SetSceneModified(); } void SpawnObject() { if(spawnedObjectsNames.length==0) return; IntRect view = activeViewport.viewport.rect; for(int i=0;i<spawnCount;i++) { Vector2 norm=Vector2(Random(-1,1),Random(-1,1)); norm.Normalize(); norm=norm*(spawnRadius*Random(0,1)); IntVector2 pos = IntVector2(ui.cursorPosition.x+norm.x,ui.cursorPosition.y+norm.y); Ray cameraRay = camera.GetScreenRay( float(pos.x - view.left) / view.width, float(pos.y - view.top) / view.height); if (pickMode < PICK_RIGIDBODIES) { if (editorScene.octree is null) return; RayQueryResult result = editorScene.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, camera.farClip, pickModeDrawableFlags[pickMode], 0x7fffffff); if (result.drawable !is null) PlaceObject(result.position, result.normal); } else { if (editorScene.physicsWorld is null) return; // If we are not running the actual physics update, refresh collisions before raycasting if (!runUpdate) editorScene.physicsWorld.UpdateCollisions(); PhysicsRaycastResult result = editorScene.physicsWorld.RaycastSingle(cameraRay, camera.farClip); if (result.body !is null) PlaceObject(result.position, result.normal); } } }
// Urho3D spawn editor LineEdit@ randomRotationX; LineEdit@ randomRotationY; LineEdit@ randomRotationZ; LineEdit@ randomScaleMinEdit; LineEdit@ randomScaleMaxEdit; LineEdit@ NumberSpawnedObjectsEdit; LineEdit@ spawnRadiusEdit; LineEdit@ spawnCountEdit; Window@ spawnWindow; Vector3 randomRotation=Vector3(0.f,0.f,0.f); float randomScaleMin=1; float randomScaleMax=1; float spawnCount=1; float spawnRadius=0; bool useNormal=true; int numberSpawnedObjects=1; Array<String> spawnedObjectsNames; void CreateSpawnEditor() { if (spawnWindow !is null) return; spawnWindow = ui.LoadLayout(cache.GetResource("XMLFile", "UI/EditorSpawnWindow.xml")); ui.root.AddChild(spawnWindow); spawnWindow.opacity = uiMaxOpacity; int height = Min(ui.root.height - 60, 500); spawnWindow.SetSize(300, height); CenterDialog(spawnWindow); HideSpawnEditor(); SubscribeToEvent(spawnWindow.GetChild("CloseButton", true), "Released", "HideSpawnEditor"); randomRotationX=spawnWindow.GetChild("RandomRotation.x", true); randomRotationY=spawnWindow.GetChild("RandomRotation.y", true); randomRotationZ=spawnWindow.GetChild("RandomRotation.z", true); randomRotationX.text=String(randomRotation.x); randomRotationY.text=String(randomRotation.y); randomRotationZ.text=String(randomRotation.z); randomScaleMinEdit=spawnWindow.GetChild("RandomScaleMin", true); randomScaleMaxEdit=spawnWindow.GetChild("RandomScaleMax", true); randomScaleMinEdit.text=String(randomScaleMin); randomScaleMaxEdit.text=String(randomScaleMax); CheckBox@ useNormalToggle = spawnWindow.GetChild("UseNormal", true); useNormalToggle.checked = useNormal; NumberSpawnedObjectsEdit=spawnWindow.GetChild("NumberSpawnedObjects", true); NumberSpawnedObjectsEdit.text=String(numberSpawnedObjects); spawnRadiusEdit=spawnWindow.GetChild("SpawnRadius", true); spawnCountEdit=spawnWindow.GetChild("SpawnCount", true); spawnRadiusEdit.text=String(spawnRadius); spawnCountEdit.text=String(spawnCount); SubscribeToEvent(randomRotationX, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationY, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomRotationZ, "TextChanged", "EditRandomRotation"); SubscribeToEvent(randomScaleMinEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(randomScaleMaxEdit, "TextChanged", "EditRandomScale"); SubscribeToEvent(spawnRadiusEdit, "TextChanged", "EditSpawnRadius"); SubscribeToEvent(spawnCountEdit, "TextChanged", "EditSpawnCount"); SubscribeToEvent(useNormalToggle, "Toggled", "ToggleUseNormal"); SubscribeToEvent(NumberSpawnedObjectsEdit, "TextFinished", "UpdateNumberSpawnedObjects"); SubscribeToEvent(spawnWindow.GetChild("SetSpawnMode", true), "Released", "SetSpawnMode"); RefreshPickedObjects(); } bool ShowSpawnEditor() { spawnWindow.visible = true; spawnWindow.BringToFront(); return true; } void HideSpawnEditor() { spawnWindow.visible = false; } void PickSpawnObject() { @resourcePicker = GetResourcePicker(ShortStringHash("Node")); if (resourcePicker is null) return; String lastPath = resourcePicker.lastPath; if (lastPath.empty) lastPath = sceneResourcePath; CreateFileSelector("Pick " + resourcePicker.typeName, "OK", "Cancel", lastPath, resourcePicker.filters, resourcePicker.lastFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnObjectDone"); } void EditRandomRotation(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomRotation = Vector3(randomRotationX.text.ToFloat(), randomRotationY.text.ToFloat(), randomRotationZ.text.ToFloat()); UpdateHierarchyItem(editorScene); } void EditRandomScale(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); randomScaleMin = randomScaleMinEdit.text.ToFloat(); randomScaleMax = randomScaleMaxEdit.text.ToFloat(); UpdateHierarchyItem(editorScene); } void ToggleUseNormal(StringHash eventType, VariantMap& eventData) { useNormal = cast<CheckBox>(eventData["Element"].GetPtr()).checked; } void UpdateNumberSpawnedObjects(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); numberSpawnedObjects=edit.text.ToFloat(); edit.text=String(numberSpawnedObjects); RefreshPickedObjects(); } void EditSpawnRadius(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnRadius=edit.text.ToFloat(); } void EditSpawnCount(StringHash eventType, VariantMap& eventData) { LineEdit@ edit = eventData["Element"].GetPtr(); spawnCount=edit.text.ToFloat(); } void RefreshPickedObjects() { spawnedObjectsNames.Resize(numberSpawnedObjects); ListView@ list = spawnWindow.GetChild("SpawnedObjects", true); list.RemoveAllItems(); for (uint i = 0; i < numberSpawnedObjects; ++i) { UIElement@ parent = CreateAttributeEditorParentWithSeparatedLabel(list, "Object " +(i+1), i, 0, false); UIElement@ container = UIElement(); container.SetLayout(LM_HORIZONTAL, 4, IntRect(10, 0, 4, 0)); container.SetFixedHeight(ATTR_HEIGHT); parent.AddChild(container); LineEdit@ nameEdit = CreateAttributeLineEdit(container, null, i, 0); nameEdit.name = "TextureNameEdit" + String(i); Button@ pickButton = CreateResourcePickerButton(container, null, i, 0, "Pick"); SubscribeToEvent(pickButton, "Released", "PickSpawnedObject"); nameEdit.text = spawnedObjectsNames[i]; SubscribeToEvent(nameEdit, "TextFinished", "EditSpawnedObjectName"); } } void EditSpawnedObjectName(StringHash eventType, VariantMap& eventData) { LineEdit@ nameEdit = eventData["Element"].GetPtr(); int index = nameEdit.vars["Index"].GetUInt(); String resourceName = nameEdit.text; XMLFile@ xml = cache.GetResource("XMLFile", resourceName); if(xml !is null) spawnedObjectsNames[index]=resourceName; else spawnedObjectsNames[index]=String(""); RefreshPickedObjects(); } void PickSpawnedObject(StringHash eventType, VariantMap& eventData) { UIElement@ button = eventData["Element"].GetPtr(); resourcePickIndex = button.vars["Index"].GetUInt(); CreateFileSelector("Pick spawned object", "Pick", "Cancel", uiNodePath, uiSceneFilters, uiNodeFilter); SubscribeToEvent(uiFileSelector, "FileSelected", "PickSpawnedObjectNameDone"); } void PickSpawnedObjectNameDone(StringHash eventType, VariantMap& eventData) { StoreResourcePickerPath(); CloseFileSelector(); if (!eventData["OK"].GetBool()) { @resourcePicker = null; return; } String resourceName = GetResourceNameFromFullName(eventData["FileName"].GetString()); XMLFile@ xml = cache.GetResource("XMLFile", resourceName); if(xml !is null) spawnedObjectsNames[resourcePickIndex]=resourceName; else spawnedObjectsNames[resourcePickIndex]=String(""); @resourcePicker = null; RefreshPickedObjects(); } void SetSpawnMode(StringHash eventType, VariantMap& eventData) { editMode=EDIT_SPAWN; } void PlaceObject(Vector3 spawnPosition, Vector3 normal) { Quaternion spawnRotation; if(useNormal)spawnRotation=Quaternion(Vector3(0.f,1.f,0.f),normal); int number=RandomInt(0,spawnedObjectsNames.length); XMLFile@ xml = cache.GetResource("XMLFile", spawnedObjectsNames[number]); Node@ spawnedObject =editorScene.InstantiateXML(xml, spawnPosition, spawnRotation); if(spawnedObject is null) { spawnedObjectsNames[number]=spawnedObjectsNames[spawnedObjectsNames.length-1]; --numberSpawnedObjects; RefreshPickedObjects(); return; } spawnedObject.scale=spawnedObject.scale*Random(randomScaleMin, randomScaleMax); spawnedObject.Rotate(Quaternion(Random(-randomRotation.x,randomRotation.x), Random(-randomRotation.y,randomRotation.y),Random(-randomRotation.z,randomRotation.z)),false); CreateNodeAction action; action.Define(spawnedObject); SaveEditAction(action); SetSceneModified(); } Vector3 RandomizeSpawnPosition(const Vector3&in position) { float angle = Random() * 360.0; float distance = Random() * spawnRadius; return position + Quaternion(0, angle, 0) * Vector3(0, 0, distance); } void SpawnObject() { if(spawnedObjectsNames.length==0) return; IntRect view = activeViewport.viewport.rect; for(int i=0;i<spawnCount;i++) { IntVector2 pos = IntVector2(ui.cursorPosition.x,ui.cursorPosition.y); Ray cameraRay = camera.GetScreenRay( float(pos.x - view.left) / view.width, float(pos.y - view.top) / view.height); if (pickMode < PICK_RIGIDBODIES) { if (editorScene.octree is null) return; RayQueryResult result = editorScene.octree.RaycastSingle(cameraRay, RAY_TRIANGLE, camera.farClip, pickModeDrawableFlags[pickMode], 0x7fffffff); // Randomize in a circle around original hit position if (spawnRadius > 0) { Vector3 position = RandomizeSpawnPosition(result.position); position.y += spawnRadius; result = editorScene.octree.RaycastSingle(Ray(position, Vector3(0, -1, 0)), RAY_TRIANGLE, spawnRadius * 2.0, pickModeDrawableFlags[pickMode], 0x7fffffff); } if (result.drawable !is null) PlaceObject(result.position, result.normal); } else { if (editorScene.physicsWorld is null) return; // If we are not running the actual physics update, refresh collisions before raycasting if (!runUpdate) editorScene.physicsWorld.UpdateCollisions(); PhysicsRaycastResult result = editorScene.physicsWorld.RaycastSingle(cameraRay, camera.farClip); // Randomize in a circle around original hit position if (spawnRadius > 0) { Vector3 position = RandomizeSpawnPosition(result.position); position.y += spawnRadius; result = editorScene.physicsWorld.RaycastSingle(Ray(position, Vector3(0, -1, 0)), spawnRadius * 2.0); } if (result.body !is null) PlaceObject(result.position, result.normal); } } }
Use spawnRadius parameter in world space.
Use spawnRadius parameter in world space.
ActionScript
mit
victorholt/Urho3D,kostik1337/Urho3D,SuperWangKai/Urho3D,PredatorMF/Urho3D,helingping/Urho3D,codedash64/Urho3D,urho3d/Urho3D,bacsmar/Urho3D,henu/Urho3D,c4augustus/Urho3D,PredatorMF/Urho3D,SirNate0/Urho3D,tommy3/Urho3D,xiliu98/Urho3D,luveti/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,bacsmar/Urho3D,SirNate0/Urho3D,c4augustus/Urho3D,orefkov/Urho3D,iainmerrick/Urho3D,henu/Urho3D,MeshGeometry/Urho3D,c4augustus/Urho3D,c4augustus/Urho3D,codedash64/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,carnalis/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,rokups/Urho3D,orefkov/Urho3D,kostik1337/Urho3D,weitjong/Urho3D,carnalis/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,bacsmar/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,luveti/Urho3D,victorholt/Urho3D,MonkeyFirst/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,299299/Urho3D,rokups/Urho3D,victorholt/Urho3D,helingping/Urho3D,codedash64/Urho3D,codedash64/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,MonkeyFirst/Urho3D,codemon66/Urho3D,bacsmar/Urho3D,orefkov/Urho3D,codedash64/Urho3D,weitjong/Urho3D,iainmerrick/Urho3D,rokups/Urho3D,xiliu98/Urho3D,rokups/Urho3D,luveti/Urho3D,victorholt/Urho3D,299299/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,carnalis/Urho3D,299299/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,MeshGeometry/Urho3D,MeshGeometry/Urho3D,xiliu98/Urho3D,codemon66/Urho3D,urho3d/Urho3D,xiliu98/Urho3D,fire/Urho3D-1,codemon66/Urho3D,eugeneko/Urho3D,kostik1337/Urho3D,abdllhbyrktr/Urho3D,SirNate0/Urho3D,carnalis/Urho3D,codemon66/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,abdllhbyrktr/Urho3D,299299/Urho3D,rokups/Urho3D,luveti/Urho3D,kostik1337/Urho3D,orefkov/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,299299/Urho3D,iainmerrick/Urho3D,xiliu98/Urho3D,eugeneko/Urho3D,tommy3/Urho3D,fire/Urho3D-1,SuperWangKai/Urho3D,weitjong/Urho3D,luveti/Urho3D,iainmerrick/Urho3D,helingping/Urho3D,c4augustus/Urho3D,fire/Urho3D-1,urho3d/Urho3D,rokups/Urho3D,henu/Urho3D,tommy3/Urho3D,weitjong/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,codemon66/Urho3D,urho3d/Urho3D,abdllhbyrktr/Urho3D,abdllhbyrktr/Urho3D,eugeneko/Urho3D,SirNate0/Urho3D,kostik1337/Urho3D,victorholt/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,iainmerrick/Urho3D,PredatorMF/Urho3D
f4bea3b233073598dc65d16c647a67087bf6e07a
src/aerys/minko/type/clone/CloneOptions.as
src/aerys/minko/type/clone/CloneOptions.as
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.controller.mesh.SkinningController; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.enum.DataProviderUsage; public class CloneOptions { private var _clonedControllerTypes : Vector.<Class> = new <Class>[]; private var _ignoredControllerTypes : Vector.<Class> = new <Class>[]; private var _reassignedControllerTypes : Vector.<Class> = new <Class>[]; private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { } public static function get defaultCloneOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push(AnimationController, SkinningController); cloneOptions._ignoredControllerTypes.push(MeshVisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push(MeshVisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public function addControllerAction(controllerClass : Class, action : uint) : void { switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } } public function removeControllerAction(controllerClass : Class) : void { throw new Error('Implement me.'); } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
package aerys.minko.type.clone { import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.AnimationController; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.controller.mesh.SkinningController; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.binding.IDataProvider; import aerys.minko.type.enum.DataProviderUsage; public class CloneOptions { private var _clonedControllerTypes : Vector.<Class> = new <Class>[]; private var _ignoredControllerTypes : Vector.<Class> = new <Class>[]; private var _reassignedControllerTypes : Vector.<Class> = new <Class>[]; private var _defaultControllerAction : uint = ControllerCloneAction.REASSIGN; public function get defaultControllerAction() : uint { return _defaultControllerAction; } public function set defaultControllerAction(v : uint) : void { if (v != ControllerCloneAction.CLONE && v != ControllerCloneAction.IGNORE && v != ControllerCloneAction.REASSIGN) throw new Error('Unknown action type.'); _defaultControllerAction = v; } public function CloneOptions() { } public static function get defaultCloneOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._clonedControllerTypes.push(AnimationController, SkinningController); cloneOptions._ignoredControllerTypes.push(MeshVisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN; return cloneOptions; } public static function get cloneAllOptions() : CloneOptions { var cloneOptions : CloneOptions = new CloneOptions(); cloneOptions._ignoredControllerTypes.push(MeshVisibilityController, CameraController); cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE; return cloneOptions; } public function addControllerAction(controllerClass : Class, action : uint) : void { switch (action) { case ControllerCloneAction.CLONE: _clonedControllerTypes.push(controllerClass); break; case ControllerCloneAction.IGNORE: _ignoredControllerTypes.push(controllerClass); break; case ControllerCloneAction.REASSIGN: _reassignedControllerTypes.push(controllerClass); break; default: throw new Error('Unknown action type.'); } } public function removeControllerAction(controllerClass : Class) : void { throw new Error('Implement me.'); } public function getActionForController(controller : AbstractController) : uint { var numControllersToClone : uint = _clonedControllerTypes.length; var numControllersToIgnore : uint = _ignoredControllerTypes.length; var numControllersToReassign : uint = _reassignedControllerTypes.length; var controllerId : uint; for (controllerId = 0; controllerId < numControllersToClone; ++controllerId) if (controller is _clonedControllerTypes[controllerId]) return ControllerCloneAction.CLONE; for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId) if (controller is _ignoredControllerTypes[controllerId]) return ControllerCloneAction.IGNORE; for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId) if (controller is _reassignedControllerTypes[controllerId]) return ControllerCloneAction.REASSIGN; return _defaultControllerAction; } } }
Fix minor bug on CloneOptions
Fix minor bug on CloneOptions
ActionScript
mit
aerys/minko-as3
85b3b3114d827f40c3f0d37ddcfa276887d947b5
src/as/com/threerings/util/CommandEvent.as
src/as/com/threerings/util/CommandEvent.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.errors.IllegalOperationError; import flash.events.Event; import flash.events.IEventDispatcher; public class CommandEvent extends Event { /** The event type for all controller events. */ public static const COMMAND :String = "commandEvt"; /** * Use this method to dispatch CommandEvents. */ public static function dispatch ( disp :IEventDispatcher, cmdOrFn :Object, arg :Object = null) :void { if (cmdOrFn is Function) { var fn :Function = (cmdOrFn as Function); // build our args array var args :Array; if (arg is Array) { // if we were passed an array, treat it as the arg array. // Note: if you want to pass a single array param, you've // got to wrap it in another array, so sorry. args = arg as Array; } else { args = [ arg ]; } try { fn.apply(null, args); } catch (err :Error) { if (arg == null) { try { // try with no args fn(); err = null; // on success, clear the error } catch (err2 :Error) { err = err2; } } if (err != null) { var log :Log = Log.getLog(CommandEvent); log.warning("Unable to call command callback, stack trace follows."); log.logStackTrace(err); } } } else if (cmdOrFn is String) { var cmd :String = String(cmdOrFn); // Create the event to dispatch var event :CommandEvent = create(cmd, arg); // Dispatch it. A return value of true means that the event was // never cancelled, so we complain. if (disp == null || disp.dispatchEvent(event)) { Log.getLog(CommandEvent).warning("Unhandled controller command " + "[cmd=" + cmd + ", arg=" + arg + "]."); } } else { throw new ArgumentError("Argument 'cmdOrFn' must be a command (String) or a Function"); } } /** The command. */ public var command :String; /** An optional argument. */ public var arg :Object; /** * Command events may not be directly constructed, use the dispatch * method to do your work. */ public function CommandEvent (command :String, arg :Object) { super(COMMAND, true, true); if (_blockConstructor) { throw new IllegalOperationError(); } this.command = command; this.arg = arg; } /** * Mark this command as handled, stopping its propagation up the * hierarchy. */ public function markAsHandled () :void { preventDefault(); stopImmediatePropagation(); } override public function clone () :Event { return create(command, arg); } override public function toString () :String { return "CommandEvent[" + command + " (" + arg + ")]"; } /** * A factory method for privately creating command events. */ protected static function create (cmd :String, arg :Object) :CommandEvent { var event :CommandEvent; _blockConstructor = false; try { event = new CommandEvent(cmd, arg); } finally { _blockConstructor = true; } return event; } /** Used to prevent unauthorized construction. */ protected static var _blockConstructor :Boolean = true; } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util { import flash.errors.IllegalOperationError; import flash.events.Event; import flash.events.IEventDispatcher; public class CommandEvent extends Event { /** The event type for all controller events. */ public static const COMMAND :String = "commandEvt"; /** * Use this method to dispatch CommandEvents. */ public static function dispatch ( disp :IEventDispatcher, cmdOrFn :Object, arg :Object = null) :void { if (cmdOrFn is Function) { var fn :Function = (cmdOrFn as Function); // build our args array var args :Array; if (arg is Array) { // if we were passed an array, treat it as the arg array. // Note: if you want to pass a single array param, you've // got to wrap it in another array, so sorry. args = arg as Array; } else { args = [ arg ]; } try { fn.apply(null, args); } catch (err :Error) { if (arg == null) { try { // try with no args fn(); err = null; // on success, clear the error } catch (err2 :Error) { err = err2; } } if (err != null) { var log :Log = Log.getLog(CommandEvent); log.warning("Unable to call command callback, stack trace follows."); log.logStackTrace(err); } } } else if (cmdOrFn is String) { var cmd :String = String(cmdOrFn); // Create the event to dispatch var event :CommandEvent = create(cmd, arg); // Dispatch it. A return value of true means that the event was // never cancelled, so we complain. if (disp == null || disp.dispatchEvent(event)) { Log.getLog(CommandEvent).warning("Unhandled controller command " + "[cmd=" + cmd + ", arg=" + arg + ", disp=" + disp + "]."); } } else { throw new ArgumentError("Argument 'cmdOrFn' must be a command (String) or a Function"); } } /** The command. */ public var command :String; /** An optional argument. */ public var arg :Object; /** * Command events may not be directly constructed, use the dispatch * method to do your work. */ public function CommandEvent (command :String, arg :Object) { super(COMMAND, true, true); if (_blockConstructor) { throw new IllegalOperationError(); } this.command = command; this.arg = arg; } /** * Mark this command as handled, stopping its propagation up the * hierarchy. */ public function markAsHandled () :void { preventDefault(); stopImmediatePropagation(); } override public function clone () :Event { return create(command, arg); } override public function toString () :String { return "CommandEvent[" + command + " (" + arg + ")]"; } /** * A factory method for privately creating command events. */ protected static function create (cmd :String, arg :Object) :CommandEvent { var event :CommandEvent; _blockConstructor = false; try { event = new CommandEvent(cmd, arg); } finally { _blockConstructor = true; } return event; } /** Used to prevent unauthorized construction. */ protected static var _blockConstructor :Boolean = true; } }
Include the dispatcher here so we know if it was null or unresponsive.
Include the dispatcher here so we know if it was null or unresponsive. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5102 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
606457c1e86dc6da0a3b205cd98884c9a9cb444f
src/com/esri/builder/views/HelpButton.as
src/com/esri/builder/views/HelpButton.as
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // 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.esri.builder.views { import com.esri.builder.views.popups.HelpPopUp; import flash.events.MouseEvent; import flash.geom.Rectangle; import mx.core.FlexGlobals; import mx.core.LayoutDirection; import mx.core.UIComponent; import mx.managers.PopUpManager; import spark.components.supportClasses.ButtonBase; [Exclude(kind="property", name="toolTip")] public class HelpButton extends ButtonBase { [Bindable] public var title:String; [Bindable] public var helpText:String; private var helpPopUp:HelpPopUp; public function HelpButton() { addEventListener(MouseEvent.ROLL_OVER, rollOverHandler, false, 0, true); addEventListener(MouseEvent.ROLL_OUT, rollOutHandler, false, 0, true); } protected function rollOverHandler(event:MouseEvent):void { if (!helpPopUp) { helpPopUp = createHelpPopUp(); PopUpManager.addPopUp(helpPopUp, this); positionHelpPopUp(this, helpPopUp); } } private function createHelpPopUp():HelpPopUp { helpPopUp = new HelpPopUp(); helpPopUp.title = title; helpPopUp.content = helpText; return helpPopUp; } private function positionHelpPopUp(button:UIComponent, popUp:UIComponent):void { var app:UIComponent = FlexGlobals.topLevelApplication as UIComponent; var appBounds:Rectangle = app.getVisibleRect(); var buttonRect:Rectangle = button.getBounds(app); var popUpRect:Rectangle = new Rectangle(buttonRect.x, buttonRect.y, popUp.width, popUp.height); var isLTR:Boolean = (layoutDirection == LayoutDirection.LTR); var leftOffset:Number = isLTR ? -popUpRect.width - anchorHalfWidth : buttonRect.width + anchorHalfWidth; var rightOffset:Number = isLTR ? buttonRect.width + anchorHalfWidth : -popUpRect.width - anchorHalfWidth; var leftPopUpRect:Rectangle = popUpRect.clone(); var rightPopUpRect:Rectangle = popUpRect.clone(); var bottomPopUpRect:Rectangle = popUpRect.clone(); var topPopUpRect:Rectangle = popUpRect.clone(); leftPopUpRect.x += leftOffset; rightPopUpRect.x += rightOffset; bottomPopUpRect.y += buttonRect.height; topPopUpRect.y += -popUpRect.height; var leftIntersectionRect:Rectangle = appBounds.intersection(leftPopUpRect); var rightIntersectionRect:Rectangle = appBounds.intersection(rightPopUpRect); var bottomIntersectionRect:Rectangle = appBounds.intersection(bottomPopUpRect); var topIntersectionRect:Rectangle = appBounds.intersection(topPopUpRect); var horizontalPosition:String; if (isLTR) { if (leftIntersectionRect.width > rightIntersectionRect.width) { popUp.x = leftPopUpRect.x; horizontalPosition = "LEFT"; } else { popUp.x = rightPopUpRect.x; horizontalPosition = "RIGHT"; } } else { if (leftIntersectionRect.width < rightIntersectionRect.width) { popUp.x = app.width - rightPopUpRect.x - rightPopUpRect.width; horizontalPosition = "LEFT"; } else { popUp.x = app.width - leftPopUpRect.x - leftPopUpRect.width; horizontalPosition = "RIGHT"; } } var verticalPosition:String; if (Math.round(topIntersectionRect.height) > Math.round(bottomIntersectionRect.height)) { popUp.y = topPopUpRect.y; verticalPosition = "TOP"; } else if (Math.round(topIntersectionRect.height) < Math.round(bottomIntersectionRect.height)) { popUp.y = bottomPopUpRect.y; verticalPosition = "BOTTOM"; } else { popUp.y = buttonRect.y + (buttonRect.height - popUpRect.height) * 0.5; verticalPosition = "MIDDLE"; } var popUpPosition:String = verticalPosition + "_" + horizontalPosition; positionHelpPopUpAnchor(popUpPosition); } public function get anchorHalfWidth():Number { return helpPopUp.anchor.width; } private function positionHelpPopUpAnchor(popUpPosition:String):void { //we assume help pop-up anchor points to the right: < switch (popUpPosition) { case "MIDDLE_RIGHT": { helpPopUp.anchor.left = -anchorHalfWidth; helpPopUp.anchor.verticalCenter = 0; break; } case "MIDDLE_LEFT": { helpPopUp.anchor.right = -anchorHalfWidth; helpPopUp.anchor.rotation = 180; helpPopUp.anchor.verticalCenter = 0; break; } case "TOP_RIGHT": { helpPopUp.anchor.left = -anchorHalfWidth; helpPopUp.anchor.bottom = -anchorHalfWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = -45; break; } case "TOP_LEFT": { helpPopUp.anchor.right = -anchorHalfWidth; helpPopUp.anchor.bottom = -anchorHalfWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = -135; break; } case "BOTTOM_RIGHT": { helpPopUp.anchor.top = -anchorHalfWidth; helpPopUp.anchor.left = -anchorHalfWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = 45; break; } case "BOTTOM_LEFT": { helpPopUp.anchor.top = -anchorHalfWidth; helpPopUp.anchor.right = -anchorHalfWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = 135; break; } } } protected function rollOutHandler(event:MouseEvent):void { if (helpPopUp) { PopUpManager.removePopUp(helpPopUp); helpPopUp = null; } } } }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008-2013 Esri. All Rights Reserved. // // 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.esri.builder.views { import com.esri.builder.views.popups.HelpPopUp; import flash.events.MouseEvent; import flash.geom.Rectangle; import mx.core.FlexGlobals; import mx.core.LayoutDirection; import mx.core.UIComponent; import mx.managers.PopUpManager; import spark.components.supportClasses.ButtonBase; [Exclude(kind="property", name="toolTip")] public class HelpButton extends ButtonBase { [Bindable] public var title:String; [Bindable] public var helpText:String; private var helpPopUp:HelpPopUp; public function HelpButton() { addEventListener(MouseEvent.ROLL_OVER, rollOverHandler, false, 0, true); addEventListener(MouseEvent.ROLL_OUT, rollOutHandler, false, 0, true); } protected function rollOverHandler(event:MouseEvent):void { if (!helpPopUp) { helpPopUp = createHelpPopUp(); PopUpManager.addPopUp(helpPopUp, this); positionHelpPopUp(this, helpPopUp); } } private function createHelpPopUp():HelpPopUp { helpPopUp = new HelpPopUp(); helpPopUp.title = title; helpPopUp.content = helpText; return helpPopUp; } private function positionHelpPopUp(button:UIComponent, popUp:UIComponent):void { var app:UIComponent = FlexGlobals.topLevelApplication as UIComponent; var appBounds:Rectangle = app.getVisibleRect(); var buttonRect:Rectangle = button.getBounds(app); var popUpRect:Rectangle = new Rectangle(buttonRect.x, buttonRect.y, popUp.width, popUp.height); var isLTR:Boolean = (layoutDirection == LayoutDirection.LTR); var anchorWidth:Number = helpPopUp.anchor.width; var leftOffset:Number = isLTR ? -popUpRect.width - anchorWidth : buttonRect.width + anchorWidth; var rightOffset:Number = isLTR ? buttonRect.width + anchorWidth : -popUpRect.width - anchorWidth; var leftPopUpRect:Rectangle = popUpRect.clone(); var rightPopUpRect:Rectangle = popUpRect.clone(); var bottomPopUpRect:Rectangle = popUpRect.clone(); var topPopUpRect:Rectangle = popUpRect.clone(); leftPopUpRect.x += leftOffset; rightPopUpRect.x += rightOffset; bottomPopUpRect.y += buttonRect.height; topPopUpRect.y += -popUpRect.height; var leftIntersectionRect:Rectangle = appBounds.intersection(leftPopUpRect); var rightIntersectionRect:Rectangle = appBounds.intersection(rightPopUpRect); var bottomIntersectionRect:Rectangle = appBounds.intersection(bottomPopUpRect); var topIntersectionRect:Rectangle = appBounds.intersection(topPopUpRect); var horizontalPosition:String; if (isLTR) { if (leftIntersectionRect.width > rightIntersectionRect.width) { popUp.x = leftPopUpRect.x; horizontalPosition = "LEFT"; } else { popUp.x = rightPopUpRect.x; horizontalPosition = "RIGHT"; } } else { if (leftIntersectionRect.width < rightIntersectionRect.width) { popUp.x = app.width - rightPopUpRect.x - rightPopUpRect.width; horizontalPosition = "LEFT"; } else { popUp.x = app.width - leftPopUpRect.x - leftPopUpRect.width; horizontalPosition = "RIGHT"; } } var verticalPosition:String; if (Math.round(topIntersectionRect.height) > Math.round(bottomIntersectionRect.height)) { popUp.y = topPopUpRect.y; verticalPosition = "TOP"; } else if (Math.round(topIntersectionRect.height) < Math.round(bottomIntersectionRect.height)) { popUp.y = bottomPopUpRect.y; verticalPosition = "BOTTOM"; } else { popUp.y = buttonRect.y + (buttonRect.height - popUpRect.height) * 0.5; verticalPosition = "MIDDLE"; } var popUpPosition:String = verticalPosition + "_" + horizontalPosition; positionHelpPopUpAnchor(popUpPosition); } private function positionHelpPopUpAnchor(popUpPosition:String):void { var anchorWidth:Number = helpPopUp.anchor.width; //we assume help pop-up anchor points to the right: < switch (popUpPosition) { case "MIDDLE_RIGHT": { helpPopUp.anchor.left = -anchorWidth; helpPopUp.anchor.verticalCenter = 0; break; } case "MIDDLE_LEFT": { helpPopUp.anchor.right = -anchorWidth; helpPopUp.anchor.rotation = 180; helpPopUp.anchor.verticalCenter = 0; break; } case "TOP_RIGHT": { helpPopUp.anchor.left = -anchorWidth; helpPopUp.anchor.bottom = -anchorWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = -45; break; } case "TOP_LEFT": { helpPopUp.anchor.right = -anchorWidth; helpPopUp.anchor.bottom = -anchorWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = -135; break; } case "BOTTOM_RIGHT": { helpPopUp.anchor.top = -anchorWidth; helpPopUp.anchor.left = -anchorWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = 45; break; } case "BOTTOM_LEFT": { helpPopUp.anchor.top = -anchorWidth; helpPopUp.anchor.right = -anchorWidth; helpPopUp.anchor.scaleX = 2.5; helpPopUp.anchor.rotation = 135; break; } } } protected function rollOutHandler(event:MouseEvent):void { if (helpPopUp) { PopUpManager.removePopUp(helpPopUp); helpPopUp = null; } } } }
Clean up.
Clean up.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
08e5da2c5b31f3c9b26874ac421f23253b74495e
test/trace/global-variable-properties.as
test/trace/global-variable-properties.as
// makeswf -v 7 -r 1 -o global-variable-properties-7.swf global-variable-properties.as #include "trace_properties.as" trace_properties (_global.Infinity, "_global", "Infinity"); trace_properties (_global.NaN, "_global", "NaN"); trace_properties (_global.o, "_global", "o"); // _global.flash is undefined, so we need to check extra //trace (hasOwnProperty (_global, "flash")); //trace_properties (_global.flash, "_global", "flash"); loadMovie ("FSCommand:quit", "");
// makeswf -v 7 -r 1 -o global-variable-properties-7.swf global-variable-properties.as #include "trace_properties.as" trace_properties (_global.Infinity, "_global", "Infinity"); trace_properties (_global.NaN, "_global", "NaN"); trace_properties (_global.o, "_global", "o"); // Need to unhide it first on version < 8 //ASSetPropFlags (_global, "flash", 0, 5248); //trace_properties (_global.flash, "_global", "flash"); loadMovie ("FSCommand:quit", "");
Update comment that was wrong in global-variable-properties.as
Update comment that was wrong in global-variable-properties.as
ActionScript
lgpl-2.1
mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec
926f1b8d6ee455789a6582f6381df61d8ed5ae93
src/aerys/minko/render/material/basic/BasicShader.as
src/aerys/minko/render/material/basic/BasicShader.as
package aerys.minko.render.material.basic { import aerys.minko.render.RenderTarget; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.DiffuseShaderPart; import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.BlendingSource; import aerys.minko.type.enum.DepthTest; import aerys.minko.type.enum.StencilAction; import aerys.minko.type.enum.TriangleCulling; /** * The BasicShader is a simple shader program handling hardware vertex * animations (skinning and morphing), a diffuse color or a texture and * a directional light. * * <table class="bindingsSummary"> * <tr> * <th>Property Name</th> * <th>Source</th> * <th>Type</th> * <th>Description</th> * <th>Requires</th> * </tr> * <tr> * <td>lightEnabled</td> * <td>Scene</td> * <td>Boolean</td> * <td>Whether the light is enabled or not on the scene.</td> * <td>lightDirection, lightAmbient, lightAmbientColor, lightDiffuse, lightDiffuseColor</td> * </tr> * <tr> * <td>lightDirection</td> * <td>Scene</td> * <td>Vector4</td> * <td>The direction of the light.</td> * <td></td> * </tr> * <tr> * <td>lightAmbient</td> * <td>Scene</td> * <td>Number</td> * <td>The ambient factor of the light.</td> * <td></td> * </tr> * <tr> * <td>lightAmbientColor</td> * <td>Scene</td> * <td>uint or Vector4</td> * <td>The ambient color of the light.</td> * <td></td> * </tr> * <tr> * <td>lightDiffuse</td> * <td>Scene</td> * <td>Number</td> * <td>The diffuse factor of the light</td> * <td></td> * </tr> * <tr> * <td>lightDiffuseColor</td> * <td>Scene</td> * <td>uint or Vector4</td> * <td>The diffuse color of the light.</td> * <td></td> * </tr> * <tr> * <td>lightEnabled</td> * <td>Mesh</td> * <td>Boolean</td> * <td>Whether the light is enabled or not on the mesh.</td> * <td></td> * </tr> * <tr> * <td>diffuseMap</td> * <td>Mesh</td> * <td>TextureResource</td> * <td>The texture to use for rendering.</td> * <td></td> * </tr> * <tr> * <td>diffuseColor</td> * <td>Mesh</td> * <td>uint or Vector4</td> * <td>The color to use for rendering. If the "diffuseMap" binding is set, this * value is not used.</td> * <td></td> * </tr> * </table> * * @author Jean-Marc Le Roux * */ public class BasicShader extends Shader { private var _vertexAnimationPart : VertexAnimationShaderPart; private var _diffuseShaderPart : DiffuseShaderPart; protected function get diffuse() : DiffuseShaderPart { return _diffuseShaderPart; } protected function get vertexAnimation() : VertexAnimationShaderPart { return _vertexAnimationPart; } /** * @param priority Default value is 0. * @param target Default value is null. */ public function BasicShader(target : RenderTarget = null, priority : Number = 0.) { super(target, priority); // init shader parts _vertexAnimationPart = new VertexAnimationShaderPart(this); _diffuseShaderPart = new DiffuseShaderPart(this); } override protected function initializeSettings(settings : ShaderSettings) : void { super.initializeSettings(settings); // depth test settings.depthWriteEnabled = meshBindings.getProperty( BasicProperties.DEPTH_WRITE_ENABLED, true ); settings.depthTest = meshBindings.getProperty( BasicProperties.DEPTH_TEST, DepthTest.LESS ); settings.triangleCulling = meshBindings.getProperty( BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK ); // stencil operations settings.stencilTriangleFace = meshBindings.getProperty( BasicProperties.STENCIL_TRIANGLE_FACE, TriangleCulling.BOTH ); settings.stencilCompareMode = meshBindings.getProperty( BasicProperties.STENCIL_COMPARE_MODE, DepthTest.EQUAL ); settings.stencilActionOnBothPass = meshBindings.getProperty( BasicProperties.STENCIL_ACTION_BOTH_PASS, StencilAction.KEEP ); settings.stencilActionOnDepthFail = meshBindings.getProperty( BasicProperties.STENCIL_ACTION_DEPTH_FAIL, StencilAction.KEEP ); settings.stencilActionOnDepthPassStencilFail = meshBindings.getProperty( BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, StencilAction.KEEP ); settings.stencilReferenceValue = meshBindings.getProperty( BasicProperties.STENCIL_REFERENCE_VALUE, 0 ); settings.stencilReadMask = meshBindings.getProperty( BasicProperties.STENCIL_READ_MASK, 255 ); settings.stencilWriteMask = meshBindings.getProperty( BasicProperties.STENCIL_WRITE_MASK, 255 ); // blending and priority var blending : uint = meshBindings.getProperty( BasicProperties.BLENDING, Blending.OPAQUE ); if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA) { settings.priority -= 0.5; settings.depthSortDrawCalls = true; } settings.blending = blending; settings.enabled = true; settings.scissorRectangle = null; } /** * @return The position of the vertex in clip space (normalized * screen space). * */ override protected function getVertexPosition() : SFloat { return localToScreen( _vertexAnimationPart.getAnimatedVertexPosition() ); } /** * @return The pixel color using a diffuse color/map and an optional * directional light. */ override protected function getPixelColor() : SFloat { return _diffuseShaderPart.getDiffuseColor(); } } }
package aerys.minko.render.material.basic { import aerys.minko.render.RenderTarget; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.ShaderSettings; import aerys.minko.render.shader.part.DiffuseShaderPart; import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.BlendingDestination; import aerys.minko.type.enum.BlendingSource; import aerys.minko.type.enum.DepthTest; import aerys.minko.type.enum.StencilAction; import aerys.minko.type.enum.TriangleCulling; /** * The BasicShader is a simple shader program handling hardware vertex * animations (skinning and morphing), a diffuse color or a texture and * a directional light. * * <table class="bindingsSummary"> * <tr> * <th>Property Name</th> * <th>Source</th> * <th>Type</th> * <th>Description</th> * <th>Requires</th> * </tr> * <tr> * <td>lightEnabled</td> * <td>Scene</td> * <td>Boolean</td> * <td>Whether the light is enabled or not on the scene.</td> * <td>lightDirection, lightAmbient, lightAmbientColor, lightDiffuse, lightDiffuseColor</td> * </tr> * <tr> * <td>lightDirection</td> * <td>Scene</td> * <td>Vector4</td> * <td>The direction of the light.</td> * <td></td> * </tr> * <tr> * <td>lightAmbient</td> * <td>Scene</td> * <td>Number</td> * <td>The ambient factor of the light.</td> * <td></td> * </tr> * <tr> * <td>lightAmbientColor</td> * <td>Scene</td> * <td>uint or Vector4</td> * <td>The ambient color of the light.</td> * <td></td> * </tr> * <tr> * <td>lightDiffuse</td> * <td>Scene</td> * <td>Number</td> * <td>The diffuse factor of the light</td> * <td></td> * </tr> * <tr> * <td>lightDiffuseColor</td> * <td>Scene</td> * <td>uint or Vector4</td> * <td>The diffuse color of the light.</td> * <td></td> * </tr> * <tr> * <td>lightEnabled</td> * <td>Mesh</td> * <td>Boolean</td> * <td>Whether the light is enabled or not on the mesh.</td> * <td></td> * </tr> * <tr> * <td>diffuseMap</td> * <td>Mesh</td> * <td>TextureResource</td> * <td>The texture to use for rendering.</td> * <td></td> * </tr> * <tr> * <td>diffuseColor</td> * <td>Mesh</td> * <td>uint or Vector4</td> * <td>The color to use for rendering. If the "diffuseMap" binding is set, this * value is not used.</td> * <td></td> * </tr> * </table> * * @author Jean-Marc Le Roux * */ public class BasicShader extends Shader { private var _vertexAnimationPart : VertexAnimationShaderPart; private var _diffuseShaderPart : DiffuseShaderPart; protected function get diffuse() : DiffuseShaderPart { return _diffuseShaderPart; } protected function get vertexAnimation() : VertexAnimationShaderPart { return _vertexAnimationPart; } /** * @param priority Default value is 0. * @param target Default value is null. */ public function BasicShader(target : RenderTarget = null, priority : Number = 0.) { super(target, priority); // init shader parts _vertexAnimationPart = new VertexAnimationShaderPart(this); _diffuseShaderPart = new DiffuseShaderPart(this); } override protected function initializeSettings(settings : ShaderSettings) : void { super.initializeSettings(settings); // depth test settings.depthWriteEnabled = meshBindings.getProperty( BasicProperties.DEPTH_WRITE_ENABLED, true ); settings.depthTest = meshBindings.getProperty( BasicProperties.DEPTH_TEST, DepthTest.LESS ); settings.triangleCulling = meshBindings.getProperty( BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK ); // stencil operations settings.stencilTriangleFace = meshBindings.getProperty( BasicProperties.STENCIL_TRIANGLE_FACE, TriangleCulling.BOTH ); settings.stencilCompareMode = meshBindings.getProperty( BasicProperties.STENCIL_COMPARE_MODE, DepthTest.EQUAL ); settings.stencilActionOnBothPass = meshBindings.getProperty( BasicProperties.STENCIL_ACTION_BOTH_PASS, StencilAction.KEEP ); settings.stencilActionOnDepthFail = meshBindings.getProperty( BasicProperties.STENCIL_ACTION_DEPTH_FAIL, StencilAction.KEEP ); settings.stencilActionOnDepthPassStencilFail = meshBindings.getProperty( BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, StencilAction.KEEP ); settings.stencilReferenceValue = meshBindings.getProperty( BasicProperties.STENCIL_REFERENCE_VALUE, 0 ); settings.stencilReadMask = meshBindings.getProperty( BasicProperties.STENCIL_READ_MASK, 255 ); settings.stencilWriteMask = meshBindings.getProperty( BasicProperties.STENCIL_WRITE_MASK, 255 ); // blending and priority var blending : uint = meshBindings.getProperty( BasicProperties.BLENDING, Blending.OPAQUE ); if ((blending & 0xff0000) != BlendingDestination.ZERO) { settings.priority -= 0.5; settings.depthSortDrawCalls = true; } settings.blending = blending; settings.enabled = true; settings.scissorRectangle = null; } /** * @return The position of the vertex in clip space (normalized * screen space). * */ override protected function getVertexPosition() : SFloat { return localToScreen( _vertexAnimationPart.getAnimatedVertexPosition() ); } /** * @return The pixel color using a diffuse color/map and an optional * directional light. */ override protected function getPixelColor() : SFloat { return _diffuseShaderPart.getDiffuseColor(); } } }
Fix auto depth sorting according to blending destination
Fix auto depth sorting according to blending destination
ActionScript
mit
aerys/minko-as3
740b997fab9672c1d7078ca071cb8f761a391898
exporter/src/main/as/flump/export/Packer.as
exporter/src/main/as/flump/export/Packer.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.geom.Point; import flump.SwfTexture; import flump.mold.KeyframeMold; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import com.threerings.util.Comparators; public class Packer { public const atlases :Vector.<Atlas> = new Vector.<Atlas>(); public function Packer (lib :XflLibrary, scale :Number=1.0, prefix :String="", suffix :String="") { for each (var tex :XflTexture in lib.textures) { _unpacked.push(SwfTexture.fromTexture(lib.swf, tex, scale)); } for each (var movie :MovieMold in lib.movies) { if (!movie.flipbook) continue; for each (var kf :KeyframeMold in movie.layers[0].keyframes) { _unpacked.push(SwfTexture.fromFlipbook(lib, movie, kf.index, scale)); } } _unpacked.sort(Comparators.createReverse(Comparators.createFields(["a", "w", "h"]))); while (_unpacked.length > 0) { // Add a new atlas const size :Point = findOptimalSize(); atlases.push(new Atlas(prefix + "atlas" + atlases.length + suffix, size.x, size.y)); // Try to pack each texture into any atlas for (var ii :int = 0; ii < _unpacked.length; ++ii) { var unpacked :SwfTexture = _unpacked[ii]; if (unpacked.w > MAX_SIZE || unpacked.h > MAX_SIZE) { throw new Error("Too large to fit in an atlas"); } for each (var atlas :Atlas in atlases) { // TODO(bruno): Support rotated textures? if (atlas.place(unpacked)) { _unpacked.splice(ii--, 1); break; } } } } } // Estimate the optimal size for the next atlas protected function findOptimalSize () :Point { var area :int = 0; var maxW :int = 0; var maxH :int = 0; for each (var tex :SwfTexture in _unpacked) { const w :int = tex.w + Atlas.PADDING; const h :int = tex.h + Atlas.PADDING; area += w * h; maxW = Math.max(maxW, w); maxH = Math.max(maxH, h); } const size :Point = new Point(nextPowerOfTwo(maxW), nextPowerOfTwo(maxH)); // Double the area until it's big enough while (size.x * size.y < area) { if (size.x < size.y) size.x *= 2; else size.y *= 2; } size.x = Math.min(size.x, MAX_SIZE); size.y = Math.min(size.y, MAX_SIZE); return size; } protected static function nextPowerOfTwo (n :int) :int { var p :int = 1; while (p < n) p *= 2; return p; } protected const _unpacked :Vector.<SwfTexture> = new Vector.<SwfTexture>(); // Maximum width or height of a texture atlas private static const MAX_SIZE :int = 1024; } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.geom.Point; import flump.SwfTexture; import flump.mold.KeyframeMold; import flump.mold.MovieMold; import flump.xfl.XflLibrary; import flump.xfl.XflTexture; import com.threerings.util.Comparators; public class Packer { public const atlases :Vector.<Atlas> = new Vector.<Atlas>(); public function Packer (lib :XflLibrary, scale :Number=1.0, prefix :String="", suffix :String="") { for each (var tex :XflTexture in lib.textures) { _unpacked.push(SwfTexture.fromTexture(lib.swf, tex, scale)); } for each (var movie :MovieMold in lib.movies) { if (!movie.flipbook) continue; for each (var kf :KeyframeMold in movie.layers[0].keyframes) { _unpacked.push(SwfTexture.fromFlipbook(lib, movie, kf.index, scale)); } } _unpacked.sort(Comparators.createReverse(Comparators.createFields(["a", "w", "h"]))); while (_unpacked.length > 0) { // Add a new atlas const size :Point = findOptimalSize(); atlases.push(new Atlas(prefix + "atlas" + atlases.length + suffix, size.x, size.y)); // Try to pack each texture into any atlas for (var ii :int = 0; ii < _unpacked.length; ++ii) { var unpacked :SwfTexture = _unpacked[ii]; if (unpacked.w > MAX_SIZE || unpacked.h > MAX_SIZE) { throw new Error("Too large to fit in an atlas: " + unpacked.w + ", " + unpacked.h + " " + unpacked.symbol); } for each (var atlas :Atlas in atlases) { // TODO(bruno): Support rotated textures? if (atlas.place(unpacked)) { _unpacked.splice(ii--, 1); break; } } } } } // Estimate the optimal size for the next atlas protected function findOptimalSize () :Point { var area :int = 0; var maxW :int = 0; var maxH :int = 0; for each (var tex :SwfTexture in _unpacked) { const w :int = tex.w + Atlas.PADDING; const h :int = tex.h + Atlas.PADDING; area += w * h; maxW = Math.max(maxW, w); maxH = Math.max(maxH, h); } const size :Point = new Point(nextPowerOfTwo(maxW), nextPowerOfTwo(maxH)); // Double the area until it's big enough while (size.x * size.y < area) { if (size.x < size.y) size.x *= 2; else size.y *= 2; } size.x = Math.min(size.x, MAX_SIZE); size.y = Math.min(size.y, MAX_SIZE); return size; } protected static function nextPowerOfTwo (n :int) :int { var p :int = 1; while (p < n) p *= 2; return p; } protected const _unpacked :Vector.<SwfTexture> = new Vector.<SwfTexture>(); // Maximum width or height of a texture atlas private static const MAX_SIZE :int = 2048; } }
Bump the max atlas size up to 2048
Bump the max atlas size up to 2048
ActionScript
mit
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,funkypandagame/flump
683ac2ac260befbe5113cc57dd47890ffd0cc366
src/milkshape/media/flash/src/cc/milkshape/main/SubMenu.as
src/milkshape/media/flash/src/cc/milkshape/main/SubMenu.as
package cc.milkshape.main { import cc.milkshape.preloader.events.PreloaderEvent; import cc.milkshape.utils.Constance; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.events.MouseEvent; public class SubMenu extends SubMenuClp { public function SubMenu() { rss.buttonMode = true; terms.buttonMode = true; rss.slug = 'rss'; terms.slug = 'terms'; rss.addEventListener(MouseEvent.MOUSE_OVER, _overHandler); rss.addEventListener(MouseEvent.MOUSE_OUT, _outHandler); rss.addEventListener(MouseEvent.CLICK, _clickHandlerRSS); terms.addEventListener(MouseEvent.MOUSE_OVER, _overHandler); terms.addEventListener(MouseEvent.MOUSE_OUT, _outHandler); terms.addEventListener(MouseEvent.CLICK, _clickHandlerTerms); } private function _overHandler(e:MouseEvent):void { e.currentTarget.gotoAndPlay('over'); } private function _outHandler(e:MouseEvent):void { e.currentTarget.gotoAndPlay('out'); } private function _clickHandlerTerms(e:MouseEvent):void { dispatchEvent(new PreloaderEvent(PreloaderEvent.LOAD, {url: Constance.TERMS_SWF})); } private function _clickHandlerRSS(e:MouseEvent):void { navigateToURL(new URLRequest(Constance.url('/square/feeds/rss/')), 'blank'); } } }
package cc.milkshape.main { import cc.milkshape.preloader.events.PreloaderEvent; import cc.milkshape.utils.Constance; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.events.MouseEvent; public class SubMenu extends SubMenuClp { public function SubMenu() { rss.buttonMode = true; terms.buttonMode = true; rss.slug = 'rss'; terms.slug = 'terms'; rss.addEventListener(MouseEvent.MOUSE_OVER, _overHandler); rss.addEventListener(MouseEvent.MOUSE_OUT, _outHandler); rss.addEventListener(MouseEvent.CLICK, _clickHandlerRSS); terms.addEventListener(MouseEvent.MOUSE_OVER, _overHandler); terms.addEventListener(MouseEvent.MOUSE_OUT, _outHandler); terms.addEventListener(MouseEvent.CLICK, _clickHandlerTerms); } private function _overHandler(e:MouseEvent):void { e.currentTarget.gotoAndPlay('over'); } private function _outHandler(e:MouseEvent):void { e.currentTarget.gotoAndPlay('out'); } private function _clickHandlerTerms(e:MouseEvent):void { dispatchEvent(new PreloaderEvent(PreloaderEvent.LOAD, {url: Constance.TERMS_SWF})); } private function _clickHandlerRSS(e:MouseEvent):void { navigateToURL(new URLRequest(Constance.url('square/feeds/rss/')), 'blank'); } } }
fix submenu
fix submenu
ActionScript
mit
thoas/i386,thoas/i386,thoas/i386,thoas/i386
16ae222d689b8f14f9b0bbda0ecf6d2517abeec7
src/aerys/minko/scene/SceneIterator.as
src/aerys/minko/scene/SceneIterator.as
package aerys.minko.scene { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.binding.DataBindings; import avmplus.getQualifiedClassName; import flash.utils.Dictionary; import flash.utils.Proxy; import flash.utils.describeType; import flash.utils.flash_proxy; import flash.utils.getQualifiedClassName; public dynamic class SceneIterator extends Proxy { private static const TYPE_CACHE : Dictionary = new Dictionary(true); private static const OPERATORS : Vector.<String> = new <String>[ '//', '/', '[', ']', '..', '.', '~=', '?=', '=', '@', '*', '(', ')', '>=', '>', '<=', '<', '==', '=' ]; private static const REGEX_TRIM : RegExp = /^\s+|\s+$/; private var _path : String = null; private var _selection : Vector.<ISceneNode> = null; private var _modifier : String = null; public function get length() : uint { return _selection.length; } public function SceneIterator(path : String, selection : Vector.<ISceneNode>, modifier : String = "") { super(); _modifier = modifier; initialize(path, selection); } public function toString() : String { return _selection.toString(); } // override flash_proxy function setProperty(name : *, value : *):void // { // var propertyName : String = name; // // for each (var node : ISceneNode in _selection) // getValueObject(node, _modifier)[propertyName] = value; // } override flash_proxy function getProperty(name : *) : * { var index : int = parseInt(name); if (index == name) return index < _selection.length ? _selection[index] : null; else { throw new Error( 'Unable to get a property on a set of objects. ' + 'You must use the [] operator to fetch one of the objects.' ); } } override flash_proxy function nextNameIndex(index : int) : int { return index < _selection.length ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { return _selection[int(index - 1)]; } // override flash_proxy function callProperty(name:*, ...parameters):* // { // var methodName : String = name; // // for each (var node : ISceneNode in _selection) // { // var method : Function = getValueObject(node, _modifier)[methodName]; // // method.apply(null, parameters); // } // // return this; // } private function initialize(path : String, selection : Vector.<ISceneNode>) : void { _path = path; // update root var token : String = getToken(); _selection = selection.slice(); if (token == "/") { selectRoots(); nextToken(token); } // parse while (token = getToken()) { switch (token) { case '//' : nextToken(token); selectDescendants(); break ; case '/' : nextToken(token); selectChildren(); break ; default : nextToken(token); parseNodeType(token); break ; } } } private function getToken(doNext : Boolean = false) : String { var token : String = null; if (!_path) return null; _path = _path.replace(/^\s+/, ''); var nextOpIndex : int = int.MAX_VALUE; for each (var op : String in OPERATORS) { var opIndex : int = _path.indexOf(op); if (opIndex > 0 && opIndex < nextOpIndex) nextOpIndex = opIndex; if (opIndex == 0) { token = op; break ; } } if (!token) token = _path.substring(0, nextOpIndex); if (doNext) nextToken(token); return token; } private function getValueToken() : Object { var value : Object = null; _path = _path.replace(/^\s+/, ''); if (_path.charAt(0) == "'") { var endOfStringIndex : int = _path.indexOf("'", 1); if (endOfStringIndex < 0) throw new Error("Unterminated string expression."); var stringValue : String = _path.substring(1, endOfStringIndex); _path = _path.substring(endOfStringIndex + 1); value = stringValue; } else { var token : String = getToken(true); if (token == 'true') value = true; else if (token == 'false') value = false; else if (token.indexOf('0x') == 0) value = parseInt(token, 16); } return value; } private function nextToken(token : String) : void { _path = _path.substring(_path.indexOf(token) + token.length); } private function selectChildren(typeName : String = null) : void { var selection : Vector.<ISceneNode> = _selection.slice(); if (typeName != null) typeName = typeName.toLowerCase(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node is Group) { var group : Group = node as Group; var numChildren : uint = group.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : ISceneNode = group.getChildAt(i); var className : String = getQualifiedClassName(child) var childType : String = className.substr(className.lastIndexOf(':') + 1); if (typeName == null || childType.toLowerCase() == typeName) _selection.push(child); } } } } private function selectRoots() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) if (_selection.indexOf(node.root) < 0) _selection.push(node); } private function selectDescendants() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { _selection.push(node); if (node is Group) (node as Group).getDescendantsByType(ISceneNode, _selection); } } private function selectParents() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node.parent) _selection.push(node.parent); else _selection.push(node); } } private function parseNodeType(nodeType : String) : void { if (nodeType == '.') { // nothing } if (nodeType == '..') selectParents(); else if (nodeType == '*') selectChildren(); else selectChildren(nodeType); // apply predicates var token : String = getToken(); while (token == '[') { nextToken(token); parsePredicate(); token = getToken(); } } private function parsePredicate() : void { var propertyName : String = getToken(true); var isBinding : Boolean = propertyName == '@'; if (isBinding) propertyName = getToken(true); var index : int = parseInt(propertyName); if (propertyName == 'hasController') filterOnController(); if (propertyName == 'hasProperty') filterOnProperty(); else if (propertyName == 'position') filterOnPosition(); else if (propertyName == 'last') filterLast(); else if (propertyName == 'first') filterFirst(); else if (index.toString() == propertyName) { if (index < _selection.length) { _selection[0] = _selection[index]; _selection.length = 1; } else _selection.length = 0; } else filterOnValue(propertyName, isBinding); checkNextToken(']'); } private function filterLast() : void { checkNextToken('('); checkNextToken(')'); _selection[0] = _selection[uint(_selection.length - 1)]; _selection.length = 1; } private function filterFirst() : void { checkNextToken('('); checkNextToken(')'); _selection.length = 1; } private function filterOnValue(propertyName : String, isBinding : Boolean = false) : void { var operator : String = getToken(true); var chunks : Array = [propertyName]; while (operator == '.') { chunks.push(getToken(true)); operator = getToken(true); } var value : Object = getValueToken(); var numNodes : uint = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var nodeValue : Object = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName); else { try { nodeValue = getValueObject(node, chunks); if (!compare(operator, nodeValue, value)) removeFromSelection(i); } catch (e : Error) { removeFromSelection(i); } } } } private function compare(operator : String, a : Object, b : Object) : Boolean { switch (operator) { case '>' : return a > b; case '>=' : return a >= b; case '<' : return a >= b; case '<=' : return a <= b; case '=' : case '==' : return a == b; case '~=' : var matches : Array = String(a).match(b); return matches && matches.length != 0; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } private function filterOnController() : Object { checkNextToken('('); var controllerName : String = getToken(true); checkNextToken(')'); var numNodes : uint = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var numControllers : uint = node.numControllers; var keepSceneNode : Boolean = false; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controllerType : String = getQualifiedClassName(node.getController(controllerId)); controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1); if (controllerType == controllerName) { keepSceneNode = true; break; } } if (!keepSceneNode) removeFromSelection(i); } return null; } private function filterOnPosition() : void { checkNextToken('('); checkNextToken(')'); var operator : String = getToken(true); var value : uint = uint(parseInt(getToken(true))); switch (operator) { case '>': ++value; case '>=': _selection = _selection.slice(value); break; case '<': --value; case '<=': _selection = _selection.slice(0, value); break; case '=': case '==': _selection[0] = _selection[value]; _selection.length = 1; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } private function filterOnProperty() : void { checkNextToken('('); var chunks : Array = [getToken(true)]; var operator : String = getToken(true); while (operator == '.') { chunks.push(operator); operator = getToken(true); } if (operator != ')') throwParseError(')', operator); var numNodes : uint = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { try { getValueObject(_selection[i], chunks); } catch (e : Error) { removeFromSelection(i); } } } private function getValueObject(source : Object, chunks : Array) : Object { if (chunks) for each (var chunk : String in chunks) source = source[chunk]; return source; } private function removeFromSelection(index : uint) : void { var numNodes : uint = _selection.length - 1; _selection[index] = _selection[numNodes]; _selection.length = numNodes; } private function checkNextToken(expected : String) : void { var token : String = getToken(true); if (token != expected) throwParseError(expected, token); } private function throwParseError(expected : String, got : String) : void { throw new Error( 'Parse error: expected \'' + expected + '\', got \'' + got + '\'.' ); } } }
package aerys.minko.scene { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.binding.DataBindings; import flash.utils.Dictionary; import flash.utils.Proxy; import flash.utils.describeType; import flash.utils.flash_proxy; import flash.utils.getQualifiedClassName; public dynamic class SceneIterator extends Proxy { private static const TYPE_CACHE : Dictionary = new Dictionary(true); private static const OPERATORS : Vector.<String> = new <String>[ '//', '/', '[', ']', '..', '.', '~=', '?=', '=', '@', '*', '(', ')', '>=', '>', '<=', '<', '==', '=' ]; private static const REGEX_TRIM : RegExp = /^\s+|\s+$/; private var _path : String = null; private var _selection : Vector.<ISceneNode> = null; private var _modifier : String = null; public function get length() : uint { return _selection.length; } public function SceneIterator(path : String, selection : Vector.<ISceneNode>, modifier : String = "") { super(); _modifier = modifier; initialize(path, selection); } public function toString() : String { return _selection.toString(); } // override flash_proxy function setProperty(name : *, value : *):void // { // var propertyName : String = name; // // for each (var node : ISceneNode in _selection) // getValueObject(node, _modifier)[propertyName] = value; // } override flash_proxy function getProperty(name : *) : * { var index : int = parseInt(name); if (index == name) return index < _selection.length ? _selection[index] : null; else { throw new Error( 'Unable to get a property on a set of objects. ' + 'You must use the [] operator to fetch one of the objects.' ); } } override flash_proxy function nextNameIndex(index : int) : int { return index < _selection.length ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { return _selection[int(index - 1)]; } // override flash_proxy function callProperty(name:*, ...parameters):* // { // var methodName : String = name; // // for each (var node : ISceneNode in _selection) // { // var method : Function = getValueObject(node, _modifier)[methodName]; // // method.apply(null, parameters); // } // // return this; // } private function initialize(path : String, selection : Vector.<ISceneNode>) : void { _path = path; // update root var token : String = getToken(); _selection = selection.slice(); if (token == "/") { selectRoots(); nextToken(token); } // parse while (token = getToken()) { switch (token) { case '//' : nextToken(token); selectDescendants(); break ; case '/' : nextToken(token); selectChildren(); break ; default : nextToken(token); parseNodeType(token); break ; } } } private function getToken(doNext : Boolean = false) : String { var token : String = null; if (!_path) return null; _path = _path.replace(/^\s+/, ''); var nextOpIndex : int = int.MAX_VALUE; for each (var op : String in OPERATORS) { var opIndex : int = _path.indexOf(op); if (opIndex > 0 && opIndex < nextOpIndex) nextOpIndex = opIndex; if (opIndex == 0) { token = op; break ; } } if (!token) token = _path.substring(0, nextOpIndex); if (doNext) nextToken(token); return token; } private function getValueToken() : Object { var value : Object = null; _path = _path.replace(/^\s+/, ''); if (_path.charAt(0) == "'") { var endOfStringIndex : int = _path.indexOf("'", 1); if (endOfStringIndex < 0) throw new Error("Unterminated string expression."); var stringValue : String = _path.substring(1, endOfStringIndex); _path = _path.substring(endOfStringIndex + 1); value = stringValue; } else { var token : String = getToken(true); if (token == 'true') value = true; else if (token == 'false') value = false; else if (token.indexOf('0x') == 0) value = parseInt(token, 16); } return value; } private function nextToken(token : String) : void { _path = _path.substring(_path.indexOf(token) + token.length); } private function selectChildren(typeName : String = null) : void { var selection : Vector.<ISceneNode> = _selection.slice(); if (typeName != null) typeName = typeName.toLowerCase(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node is Group) { var group : Group = node as Group; var numChildren : uint = group.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : ISceneNode = group.getChildAt(i); var className : String = getQualifiedClassName(child) var childType : String = className.substr(className.lastIndexOf(':') + 1); if (typeName == null || childType.toLowerCase() == typeName) _selection.push(child); } } } } private function selectRoots() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) if (_selection.indexOf(node.root) < 0) _selection.push(node); } private function selectDescendants() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { _selection.push(node); if (node is Group) (node as Group).getDescendantsByType(ISceneNode, _selection); } } private function selectParents() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node.parent) _selection.push(node.parent); else _selection.push(node); } } private function parseNodeType(nodeType : String) : void { if (nodeType == '.') { // nothing } if (nodeType == '..') selectParents(); else if (nodeType == '*') selectChildren(); else selectChildren(nodeType); // apply predicates var token : String = getToken(); while (token == '[') { nextToken(token); parsePredicate(); token = getToken(); } } private function parsePredicate() : void { var propertyName : String = getToken(true); var isBinding : Boolean = propertyName == '@'; if (isBinding) propertyName = getToken(true); var index : int = parseInt(propertyName); if (propertyName == 'hasController') filterOnController(); if (propertyName == 'hasProperty') filterOnProperty(); else if (propertyName == 'position') filterOnPosition(); else if (propertyName == 'last') filterLast(); else if (propertyName == 'first') filterFirst(); else if (index.toString() == propertyName) { if (index < _selection.length) { _selection[0] = _selection[index]; _selection.length = 1; } else _selection.length = 0; } else filterOnValue(propertyName, isBinding); checkNextToken(']'); } private function filterLast() : void { checkNextToken('('); checkNextToken(')'); _selection[0] = _selection[uint(_selection.length - 1)]; _selection.length = 1; } private function filterFirst() : void { checkNextToken('('); checkNextToken(')'); _selection.length = 1; } private function filterOnValue(propertyName : String, isBinding : Boolean = false) : void { var operator : String = getToken(true); var chunks : Array = [propertyName]; while (operator == '.') { chunks.push(getToken(true)); operator = getToken(true); } var value : Object = getValueToken(); var numNodes : uint = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var nodeValue : Object = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName); else { try { nodeValue = getValueObject(node, chunks); if (!compare(operator, nodeValue, value)) removeFromSelection(i); } catch (e : Error) { removeFromSelection(i); } } } } private function compare(operator : String, a : Object, b : Object) : Boolean { switch (operator) { case '>' : return a > b; case '>=' : return a >= b; case '<' : return a >= b; case '<=' : return a <= b; case '=' : case '==' : return a == b; case '~=' : var matches : Array = String(a).match(b); return matches && matches.length != 0; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } private function filterOnController() : Object { checkNextToken('('); var controllerName : String = getToken(true); checkNextToken(')'); var numNodes : uint = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var numControllers : uint = node.numControllers; var keepSceneNode : Boolean = false; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controllerType : String = getQualifiedClassName(node.getController(controllerId)); controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1); if (controllerType == controllerName) { keepSceneNode = true; break; } } if (!keepSceneNode) removeFromSelection(i); } return null; } private function filterOnPosition() : void { checkNextToken('('); checkNextToken(')'); var operator : String = getToken(true); var value : uint = uint(parseInt(getToken(true))); switch (operator) { case '>': ++value; case '>=': _selection = _selection.slice(value); break; case '<': --value; case '<=': _selection = _selection.slice(0, value); break; case '=': case '==': _selection[0] = _selection[value]; _selection.length = 1; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } private function filterOnProperty() : void { checkNextToken('('); var chunks : Array = [getToken(true)]; var operator : String = getToken(true); while (operator == '.') { chunks.push(operator); operator = getToken(true); } if (operator != ')') throwParseError(')', operator); var numNodes : uint = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { try { getValueObject(_selection[i], chunks); } catch (e : Error) { removeFromSelection(i); } } } private function getValueObject(source : Object, chunks : Array) : Object { if (chunks) for each (var chunk : String in chunks) source = source[chunk]; return source; } private function removeFromSelection(index : uint) : void { var numNodes : uint = _selection.length - 1; _selection[index] = _selection[numNodes]; _selection.length = numNodes; } private function checkNextToken(expected : String) : void { var token : String = getToken(true); if (token != expected) throwParseError(expected, token); } private function throwParseError(expected : String, got : String) : void { throw new Error( 'Parse error: expected \'' + expected + '\', got \'' + got + '\'.' ); } } }
fix ambiguous reference to getQualifiedClassName()
fix ambiguous reference to getQualifiedClassName()
ActionScript
mit
aerys/minko-as3
a2c9b43a015cc82da87dccab15c359b2e6f26a12
src/aerys/minko/scene/node/Group.as
src/aerys/minko/scene/node/Group.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.SceneIterator; import aerys.minko.type.Signal; import aerys.minko.type.Sort; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.parser.ParserOptions; import aerys.minko.type.math.Ray; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * Group objects can contain other scene nodes and applies a 3D * transformation to its descendants. * * @author Jean-Marc Le Roux */ public class Group extends AbstractVisibleSceneNode { minko_scene var _children : Vector.<ISceneNode>; minko_scene var _numChildren : uint; private var _numDescendants : uint; private var _descendantAdded : Signal; private var _descendantRemoved : Signal; /** * The number of children of the Group. */ public function get numChildren() : uint { return _numChildren; } /** * The number of descendants of the Group. * * @return * */ public function get numDescendants() : uint { return _numDescendants; } /** * The signal executed when a descendant is added to the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>newParent : Group, the Group the descendant was actually added to</li> * <li>descendant : ISceneNode, the descendant that was just added</li> * </ul> * * @return * */ public function get descendantAdded() : Signal { return _descendantAdded } /** * The signal executed when a descendant is removed from the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>oldParent : Group, the Group the descendant was actually removed from</li> * <li>descendant : ISceneNode, the descendant that was just removed</li> * </ul> * * @return * */ public function get descendantRemoved() : Signal { return _descendantRemoved; } public function Group(...children) { super(); initializeChildren(children); } override protected function initializeSignals() : void { super.initializeSignals(); _descendantAdded = new Signal('Group.descendantAdded'); _descendantRemoved = new Signal('Group.descendantRemoved'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); _descendantAdded.add(descendantAddedHandler); _descendantRemoved.add(descendantRemovedHandler); added.add(addedHandler); removed.add(removedHandler); } protected function initializeChildren(children : Array) : void { _children = new <ISceneNode>[]; while (children.length == 1 && children[0] is Array) children = children[0]; var childrenNum : uint = children.length; for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex) addChild(ISceneNode(children[childrenIndex])); } private function descendantAddedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.add(_descendantAdded.execute); childGroup.descendantRemoved.add(_descendantRemoved.execute); } } _numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function descendantRemovedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.remove(_descendantAdded.execute); childGroup.descendantRemoved.remove(_descendantRemoved.execute); } } _numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function addedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.added.execute(child, ancestor); } } private function removedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.removed.execute(child, ancestor); } } /** * Return true if the specified scene node is a child of the Group, false otherwise. * * @param scene * @return * */ public function contains(scene : ISceneNode) : Boolean { return getChildIndex(scene) >= 0; } /** * Return the index of the speficied scene node or -1 if it is not in the Group. * * @param child * @return * */ public function getChildIndex(child : ISceneNode) : int { if (child == null) throw new Error('The \'child\' parameter cannot be null.'); for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : ISceneNode { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the group. * * @param scene The child to add. */ public function addChild(node : ISceneNode) : Group { return addChildAt(node, _numChildren); } /** * Add a child to the group at the specified position. * * @param node * @param position * @return * */ public function addChildAt(node : ISceneNode, position : uint) : Group { if (!node) throw new Error('Parameter \'scene\' must not be null.'); node.parent = this; for (var i : int = _numChildren - 1; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = node; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : ISceneNode) : Group { return removeChildAt(getChildIndex(child)); } public function removeChildAt(position : uint) : Group { if (position >= _numChildren || position < 0) throw new Error('The scene node is not a child of the caller.'); (_children[position] as ISceneNode).parent = null; return this; } /** * Remove all the children. * * @return * */ public function removeAllChildren() : Group { while (_numChildren) removeChildAt(0); return this; } /** * Return the child at the specified position. * * @param position * @return * */ public function getChildAt(position : uint) : ISceneNode { return position < _numChildren ? _children[position] : null; } /** * Returns the list of descendant scene nodes that have the specified type. * * @param type * @param descendants * @return * */ public function getDescendantsByType(type : Class, descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode> { descendants ||= new Vector.<ISceneNode>(); for (var i : int = 0; i < _numChildren; ++i) { var child : ISceneNode = _children[i]; var group : Group = child as Group; if (child is type) descendants.push(child); if (group) group.getDescendantsByType(type, descendants); } return descendants; } public function toString() : String { return '[' + getQualifiedClassName(this) + ' ' + name + ']'; } /** * Load the 3D scene corresponding to the specified URLRequest object * and add it directly to the group. * * @param request * @param options * @return * */ public function load(request : URLRequest, options : ParserOptions = null) : ILoader { var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.load(request); return loader; } /** * Load the 3D scene corresponding to the specified Class object * and add it directly to the group. * * @param classObject * @param options * @return */ public function loadClass(classObject : Class, options : ParserOptions = null) : SceneLoader { var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadClass(classObject); return loader; } /** * Load the 3D scene corresponding to the specified ByteArray object * and add it directly to the group. * * @param bytes * @param options * @return * */ public function loadBytes(bytes : ByteArray, options : ParserOptions = null) : ILoader { var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadBytes(bytes); return loader; } /** * Return the set of nodes matching the specified XPath query. * * @param xpath * @return * */ public function get(xpath : String) : SceneIterator { return new SceneIterator(xpath, new <ISceneNode>[this]); } private function loaderCompleteHandler(loader : ILoader, scene : ISceneNode) : void { addChild(scene); } /** * Return all the Mesh objects hit by the specified ray. * * @param ray * @param maxDistance * @return * */ public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : SceneIterator { var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh); var numMeshes : uint = meshes.length; var hit : Array = []; var depth : Vector.<Number> = new <Number>[]; var numItems : uint = 0; for (var i : uint = 0; i < numMeshes; ++i) { var mesh : Mesh = meshes[i] as Mesh; var hitDepth : Number = mesh.cast(ray, maxDistance); if (hitDepth >= 0.0) { hit[numItems] = mesh; depth[numItems] = hitDepth; ++numItems; } } if (numItems > 1) Sort.flashSort(depth, hit, numItems); return new SceneIterator(null, Vector.<ISceneNode>(hit)); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Group = new Group(); clone.name = name; clone.transform.copyFrom(transform); for (var childId : uint = 0; childId < _numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(_children[childId]); var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode()); clone.addChild(clonedChild); } return clone; } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.SceneIterator; import aerys.minko.type.Signal; import aerys.minko.type.Sort; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.parser.ParserOptions; import aerys.minko.type.math.Ray; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * Group objects can contain other scene nodes and applies a 3D * transformation to its descendants. * * @author Jean-Marc Le Roux */ public class Group extends AbstractVisibleSceneNode { minko_scene var _children : Vector.<ISceneNode>; minko_scene var _numChildren : uint; private var _numDescendants : uint; private var _descendantAdded : Signal; private var _descendantRemoved : Signal; /** * The number of children of the Group. */ public function get numChildren() : uint { return _numChildren; } /** * The number of descendants of the Group. * * @return * */ public function get numDescendants() : uint { return _numDescendants; } /** * The signal executed when a descendant is added to the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>newParent : Group, the Group the descendant was actually added to</li> * <li>descendant : ISceneNode, the descendant that was just added</li> * </ul> * * @return * */ public function get descendantAdded() : Signal { return _descendantAdded } /** * The signal executed when a descendant is removed from the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>oldParent : Group, the Group the descendant was actually removed from</li> * <li>descendant : ISceneNode, the descendant that was just removed</li> * </ul> * * @return * */ public function get descendantRemoved() : Signal { return _descendantRemoved; } public function Group(...children) { super(); initializeChildren(children); } override protected function initializeSignals() : void { super.initializeSignals(); _descendantAdded = new Signal('Group.descendantAdded'); _descendantRemoved = new Signal('Group.descendantRemoved'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); _descendantAdded.add(descendantAddedHandler); _descendantRemoved.add(descendantRemovedHandler); added.add(addedHandler); removed.add(removedHandler); } protected function initializeChildren(children : Array) : void { _children = new <ISceneNode>[]; while (children.length == 1 && children[0] is Array) children = children[0]; var childrenNum : uint = children.length; for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex) addChild(ISceneNode(children[childrenIndex])); } private function descendantAddedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.add(_descendantAdded.execute); childGroup.descendantRemoved.add(_descendantRemoved.execute); } } _numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function descendantRemovedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.remove(_descendantAdded.execute); childGroup.descendantRemoved.remove(_descendantRemoved.execute); } } _numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function addedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.added.execute(child, ancestor); } } private function removedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.removed.execute(child, ancestor); } } /** * Return true if the specified scene node is a child of the Group, false otherwise. * * @param scene * @return * */ public function contains(scene : ISceneNode) : Boolean { return getChildIndex(scene) >= 0; } /** * Return the index of the speficied scene node or -1 if it is not in the Group. * * @param child * @return * */ public function getChildIndex(child : ISceneNode) : int { if (child == null) throw new Error('The \'child\' parameter cannot be null.'); for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : ISceneNode { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the group. * * @param scene The child to add. */ public function addChild(node : ISceneNode) : Group { return addChildAt(node, _numChildren); } /** * Add a child to the group at the specified position. * * @param node * @param position * @return * */ public function addChildAt(node : ISceneNode, position : uint) : Group { if (!node) throw new Error('Parameter \'scene\' must not be null.'); node.parent = this; for (var i : int = _numChildren - 1; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = node; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : ISceneNode) : Group { return removeChildAt(getChildIndex(child)); } public function removeChildAt(position : uint) : Group { if (position >= _numChildren) throw new Error('The scene node is not a child of the caller.'); (_children[position] as ISceneNode).parent = null; return this; } /** * Remove all the children. * * @return * */ public function removeAllChildren() : Group { while (_numChildren) removeChildAt(0); return this; } /** * Return the child at the specified position. * * @param position * @return * */ public function getChildAt(position : uint) : ISceneNode { return position < _numChildren ? _children[position] : null; } /** * Returns the list of descendant scene nodes that have the specified type. * * @param type * @param descendants * @return * */ public function getDescendantsByType(type : Class, descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode> { descendants ||= new Vector.<ISceneNode>(); for (var i : int = 0; i < _numChildren; ++i) { var child : ISceneNode = _children[i]; var group : Group = child as Group; if (child is type) descendants.push(child); if (group) group.getDescendantsByType(type, descendants); } return descendants; } public function toString() : String { return '[' + getQualifiedClassName(this) + ' ' + name + ']'; } /** * Load the 3D scene corresponding to the specified URLRequest object * and add it directly to the group. * * @param request * @param options * @return * */ public function load(request : URLRequest, options : ParserOptions = null) : ILoader { var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.load(request); return loader; } /** * Load the 3D scene corresponding to the specified Class object * and add it directly to the group. * * @param classObject * @param options * @return */ public function loadClass(classObject : Class, options : ParserOptions = null) : SceneLoader { var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadClass(classObject); return loader; } /** * Load the 3D scene corresponding to the specified ByteArray object * and add it directly to the group. * * @param bytes * @param options * @return * */ public function loadBytes(bytes : ByteArray, options : ParserOptions = null) : ILoader { var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadBytes(bytes); return loader; } /** * Return the set of nodes matching the specified XPath query. * * @param xpath * @return * */ public function get(xpath : String) : SceneIterator { return new SceneIterator(xpath, new <ISceneNode>[this]); } private function loaderCompleteHandler(loader : ILoader, scene : ISceneNode) : void { addChild(scene); } /** * Return all the Mesh objects hit by the specified ray. * * @param ray * @param maxDistance * @return * */ public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : SceneIterator { var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh); var numMeshes : uint = meshes.length; var hit : Array = []; var depth : Vector.<Number> = new <Number>[]; var numItems : uint = 0; for (var i : uint = 0; i < numMeshes; ++i) { var mesh : Mesh = meshes[i] as Mesh; var hitDepth : Number = mesh.cast(ray, maxDistance); if (hitDepth >= 0.0) { hit[numItems] = mesh; depth[numItems] = hitDepth; ++numItems; } } if (numItems > 1) Sort.flashSort(depth, hit, numItems); return new SceneIterator(null, Vector.<ISceneNode>(hit)); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Group = new Group(); clone.name = name; clone.transform.copyFrom(transform); for (var childId : uint = 0; childId < _numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(_children[childId]); var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode()); clone.addChild(clonedChild); } return clone; } } }
remove useless position < 0 test in Group.removeChildAt() since the specified position is uint
remove useless position < 0 test in Group.removeChildAt() since the specified position is uint
ActionScript
mit
aerys/minko-as3
52929e9909996bc1db1bd53f05b674b1e2f9af13
src/aerys/minko/scene/node/Group.as
src/aerys/minko/scene/node/Group.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.SceneIterator; import aerys.minko.type.Signal; import aerys.minko.type.Sort; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.parser.ParserOptions; import aerys.minko.type.math.Ray; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * Group objects can contain other scene nodes and applies a 3D * transformation to its descendants. * * @author Jean-Marc Le Roux */ public class Group extends AbstractVisibleSceneNode { minko_scene var _children : Vector.<ISceneNode>; minko_scene var _numChildren : uint; private var _numDescendants : uint; private var _descendantAdded : Signal; private var _descendantRemoved : Signal; /** * The number of children of the Group. */ public function get numChildren() : uint { return _numChildren; } /** * The number of descendants of the Group. * * @return * */ public function get numDescendants() : uint { return _numDescendants; } /** * The signal executed when a descendant is added to the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>newParent : Group, the Group the descendant was actually added to</li> * <li>descendant : ISceneNode, the descendant that was just added</li> * </ul> * * @return * */ public function get descendantAdded() : Signal { return _descendantAdded } /** * The signal executed when a descendant is removed from the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>oldParent : Group, the Group the descendant was actually removed from</li> * <li>descendant : ISceneNode, the descendant that was just removed</li> * </ul> * * @return * */ public function get descendantRemoved() : Signal { return _descendantRemoved; } public function Group(...children) { super(); initializeChildren(children); } override protected function initializeSignals() : void { super.initializeSignals(); _descendantAdded = new Signal('Group.descendantAdded'); _descendantRemoved = new Signal('Group.descendantRemoved'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); _descendantAdded.add(descendantAddedHandler); _descendantRemoved.add(descendantRemovedHandler); added.add(addedHandler); removed.add(removedHandler); } protected function initializeChildren(children : Array) : void { _children = new <ISceneNode>[]; while (children.length == 1 && children[0] is Array) children = children[0]; var childrenNum : uint = children.length; for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex) addChild(ISceneNode(children[childrenIndex])); } private function descendantAddedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.add(_descendantAdded.execute); childGroup.descendantRemoved.add(_descendantRemoved.execute); } } _numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function descendantRemovedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.remove(_descendantAdded.execute); childGroup.descendantRemoved.remove(_descendantRemoved.execute); } } _numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function addedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.added.execute(child, ancestor); } } private function removedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.removed.execute(child, ancestor); } } /** * Return true if the specified scene node is a child of the Group, false otherwise. * * @param scene * @return * */ public function contains(scene : ISceneNode) : Boolean { return getChildIndex(scene) >= 0; } /** * Return the index of the speficied scene node or -1 if it is not in the Group. * * @param child * @return * */ public function getChildIndex(child : ISceneNode) : int { if (child == null) throw new Error('The \'child\' parameter cannot be null.'); for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : ISceneNode { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the group. * * @param scene The child to add. */ public function addChild(node : ISceneNode) : Group { return addChildAt(node, _numChildren); } /** * Add a child to the group at the specified position. * * @param node * @param position * @return * */ public function addChildAt(node : ISceneNode, position : uint) : Group { if (!node) throw new Error('Parameter \'scene\' must not be null.'); node.parent = this; for (var i : int = _numChildren - 1; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = node; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : ISceneNode) : Group { return removeChildAt(getChildIndex(child)); } public function removeChildAt(position : uint) : Group { if (position >= _numChildren) throw new Error('The scene node is not a child of the caller.'); (_children[position] as ISceneNode).parent = null; return this; } /** * Remove all the children. * * @return * */ public function removeAllChildren() : Group { while (_numChildren) removeChildAt(0); return this; } /** * Return the child at the specified position. * * @param position * @return * */ public function getChildAt(position : uint) : ISceneNode { return position < _numChildren ? _children[position] : null; } /** * Returns the list of descendant scene nodes that have the specified type. * * @param type * @param descendants * @return * */ public function getDescendantsByType(type : Class, descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode> { descendants ||= new Vector.<ISceneNode>(); for (var i : int = 0; i < _numChildren; ++i) { var child : ISceneNode = _children[i]; var group : Group = child as Group; if (child is type) descendants.push(child); if (group) group.getDescendantsByType(type, descendants); } return descendants; } public function toString() : String { return '[' + getQualifiedClassName(this) + ' ' + name + ']'; } /** * Load the 3D scene corresponding to the specified URLRequest object * and add it directly to the group. * * @param request * @param options * @return * */ public function load(request : URLRequest, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.load(request); return loader; } /** * Load the 3D scene corresponding to the specified Class object * and add it directly to the group. * * @param classObject * @param options * @return */ public function loadClass(classObject : Class, options : ParserOptions = null) : SceneLoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadClass(classObject); return loader; } /** * Load the 3D scene corresponding to the specified ByteArray object * and add it directly to the group. * * @param bytes * @param options * @return * */ public function loadBytes(bytes : ByteArray, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadBytes(bytes); return loader; } /** * Return the set of nodes matching the specified XPath query. * * @param xpath * @return * */ public function get(xpath : String) : SceneIterator { return new SceneIterator(xpath, new <ISceneNode>[this]); } private function loaderCompleteHandler(loader : ILoader, scene : ISceneNode) : void { addChild(scene); } /** * Return all the Mesh objects hit by the specified ray. * * @param ray * @param maxDistance * @return * */ public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY, tag : uint = 1) : SceneIterator { var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh); var numMeshes : uint = meshes.length; var hit : Array = []; var depth : Vector.<Number> = new <Number>[]; var numItems : uint = 0; for (var i : uint = 0; i < numMeshes; ++i) { var mesh : Mesh = meshes[i] as Mesh; var hitDepth : Number = mesh.cast(ray, maxDistance, tag); if (hitDepth >= 0.0) { hit[numItems] = mesh; depth[numItems] = hitDepth; ++numItems; } } if (numItems > 1) Sort.flashSort(depth, hit, numItems); return new SceneIterator(null, Vector.<ISceneNode>(hit)); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Group = new Group(); clone.name = name; clone.transform.copyFrom(transform); for (var childId : uint = 0; childId < _numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(_children[childId]); var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode()); clone.addChild(clonedChild); } return clone; } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.SceneIterator; import aerys.minko.type.Signal; import aerys.minko.type.Sort; import aerys.minko.type.loader.ILoader; import aerys.minko.type.loader.SceneLoader; import aerys.minko.type.loader.parser.ParserOptions; import aerys.minko.type.math.Ray; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * Group objects can contain other scene nodes and applies a 3D * transformation to its descendants. * * @author Jean-Marc Le Roux */ public class Group extends AbstractVisibleSceneNode { minko_scene var _children : Vector.<ISceneNode>; minko_scene var _numChildren : uint; private var _numDescendants : uint; private var _descendantAdded : Signal; private var _descendantRemoved : Signal; /** * The number of children of the Group. */ public function get numChildren() : uint { return _numChildren; } /** * The number of descendants of the Group. * * @return * */ public function get numDescendants() : uint { return _numDescendants; } /** * The signal executed when a descendant is added to the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>newParent : Group, the Group the descendant was actually added to</li> * <li>descendant : ISceneNode, the descendant that was just added</li> * </ul> * * @return * */ public function get descendantAdded() : Signal { return _descendantAdded } /** * The signal executed when a descendant is removed from the Group. * Callbacks for this signal must accept the following arguments: * <ul> * <li>oldParent : Group, the Group the descendant was actually removed from</li> * <li>descendant : ISceneNode, the descendant that was just removed</li> * </ul> * * @return * */ public function get descendantRemoved() : Signal { return _descendantRemoved; } public function Group(...children) { super(); initializeChildren(children); } override protected function initializeSignals() : void { super.initializeSignals(); _descendantAdded = new Signal('Group.descendantAdded'); _descendantRemoved = new Signal('Group.descendantRemoved'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); _descendantAdded.add(descendantAddedHandler); _descendantRemoved.add(descendantRemovedHandler); added.add(addedHandler); removed.add(removedHandler); } protected function initializeChildren(children : Array) : void { _children = new <ISceneNode>[]; while (children.length == 1 && children[0] is Array) children = children[0]; var childrenNum : uint = children.length; for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex) addChild(ISceneNode(children[childrenIndex])); } private function descendantAddedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.add(_descendantAdded.execute); childGroup.descendantRemoved.add(_descendantRemoved.execute); } } _numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function descendantRemovedHandler(group : Group, child : ISceneNode) : void { if (group == this) { var childGroup : Group = child as Group; if (childGroup) { childGroup.descendantAdded.remove(_descendantAdded.execute); childGroup.descendantRemoved.remove(_descendantRemoved.execute); } } _numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1; } private function addedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.added.execute(child, ancestor); } } private function removedHandler(child : ISceneNode, ancestor : Group) : void { var numChildren : uint = this.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : ISceneNode = _children[childId]; child.removed.execute(child, ancestor); } } /** * Return true if the specified scene node is a child of the Group, false otherwise. * * @param scene * @return * */ public function contains(scene : ISceneNode) : Boolean { return getChildIndex(scene) >= 0; } /** * Return the index of the speficied scene node or -1 if it is not in the Group. * * @param child * @return * */ public function getChildIndex(child : ISceneNode) : int { if (child == null) throw new Error('The \'child\' parameter cannot be null.'); for (var i : int = 0; i < _numChildren; i++) if (_children[i] === child) return i; return -1; } public function getChildByName(name : String) : ISceneNode { for (var i : int = 0; i < _numChildren; i++) if (_children[i].name === name) return _children[i]; return null; } /** * Add a child to the group. * * @param scene The child to add. */ public function addChild(node : ISceneNode) : Group { return addChildAt(node, _numChildren); } /** * Add a child to the group at the specified position. * * @param node * @param position * @return * */ public function addChildAt(node : ISceneNode, position : uint) : Group { if (!node) throw new Error('Parameter \'node\' must not be null.'); node.parent = this; for (var i : int = _numChildren - 1; i > position; --i) _children[i] = _children[int(i - 1)]; _children[position] = node; return this; } /** * Remove a child from the container. * * @param myChild The child to remove. * @return Whether the child was actually removed or not. */ public function removeChild(child : ISceneNode) : Group { return removeChildAt(getChildIndex(child)); } public function removeChildAt(position : uint) : Group { if (position >= _numChildren) throw new Error('The scene node is not a child of the caller.'); (_children[position] as ISceneNode).parent = null; return this; } /** * Remove all the children. * * @return * */ public function removeAllChildren() : Group { while (_numChildren) removeChildAt(0); return this; } /** * Return the child at the specified position. * * @param position * @return * */ public function getChildAt(position : uint) : ISceneNode { return position < _numChildren ? _children[position] : null; } /** * Returns the list of descendant scene nodes that have the specified type. * * @param type * @param descendants * @return * */ public function getDescendantsByType(type : Class, descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode> { descendants ||= new Vector.<ISceneNode>(); for (var i : int = 0; i < _numChildren; ++i) { var child : ISceneNode = _children[i]; var group : Group = child as Group; if (child is type) descendants.push(child); if (group) group.getDescendantsByType(type, descendants); } return descendants; } public function toString() : String { return '[' + getQualifiedClassName(this) + ' ' + name + ']'; } /** * Load the 3D scene corresponding to the specified URLRequest object * and add it directly to the group. * * @param request * @param options * @return * */ public function load(request : URLRequest, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.load(request); return loader; } /** * Load the 3D scene corresponding to the specified Class object * and add it directly to the group. * * @param classObject * @param options * @return */ public function loadClass(classObject : Class, options : ParserOptions = null) : SceneLoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadClass(classObject); return loader; } /** * Load the 3D scene corresponding to the specified ByteArray object * and add it directly to the group. * * @param bytes * @param options * @return * */ public function loadBytes(bytes : ByteArray, options : ParserOptions = null) : ILoader { if (options != null && scene != null && options.assets == null) options.assets = scene.assets; var loader : SceneLoader = new SceneLoader(options); loader.complete.add(loaderCompleteHandler); loader.loadBytes(bytes); return loader; } /** * Return the set of nodes matching the specified XPath query. * * @param xpath * @return * */ public function get(xpath : String) : SceneIterator { return new SceneIterator(xpath, new <ISceneNode>[this]); } private function loaderCompleteHandler(loader : ILoader, scene : ISceneNode) : void { addChild(scene); } /** * Return all the Mesh objects hit by the specified ray. * * @param ray * @param maxDistance * @return * */ public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY, tag : uint = 1) : SceneIterator { var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh); var numMeshes : uint = meshes.length; var hit : Array = []; var depth : Vector.<Number> = new <Number>[]; var numItems : uint = 0; for (var i : uint = 0; i < numMeshes; ++i) { var mesh : Mesh = meshes[i] as Mesh; var hitDepth : Number = mesh.cast(ray, maxDistance, tag); if (hitDepth >= 0.0) { hit[numItems] = mesh; depth[numItems] = hitDepth; ++numItems; } } if (numItems > 1) Sort.flashSort(depth, hit, numItems); return new SceneIterator(null, Vector.<ISceneNode>(hit)); } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Group = new Group(); clone.name = name; clone.transform.copyFrom(transform); for (var childId : uint = 0; childId < _numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(_children[childId]); var clonedChild : AbstractSceneNode = AbstractSceneNode(child.cloneNode()); clone.addChild(clonedChild); } return clone; } } }
fix typo in error message
fix typo in error message
ActionScript
mit
aerys/minko-as3
78efbcd061e40e4104a9150b4e45735f51bc3ebe
src/ageofai/home/model/HomeModel.as
src/ageofai/home/model/HomeModel.as
/** * Created by vizoli on 4/9/16. */ package ageofai.home.model { import ageofai.cost.constant.CUnitCost; import ageofai.home.ai.HomeAI; import ageofai.home.constant.CHome; import ageofai.home.event.HomeEvent; import ageofai.home.vo.HomeVO; import ageofai.villager.vo.VillagerVO; import caurina.transitions.Tweener; import common.mvc.model.base.BaseModel; import flash.events.TimerEvent; import flash.utils.Timer; public class HomeModel extends BaseModel implements IHomeModel { private var _homes:Vector.<HomeVO>; private var _homeAI:HomeAI; public function HomeModel() { this._homeAI = new HomeAI(); } public function tick():void { this.calculateVillagerCreation(); } private function calculateVillagerCreation():void { for ( var i:int = 0; i < this._homes.length; i++ ) { if ( !this._homes[ i ].villagerIsCreating ) { if ( this._homeAI.isNewVillagerAvailable( this._homes[ i ].food, this._homes[ i ].villagers.length ) ) { this._homes[ i ].villagerIsCreating = true; this.updateFoodAmount( this._homes[ i ], this._homes[ i ].food - CUnitCost.VILLAGER.food ); this._homes[ i ].food -= CUnitCost.VILLAGER.food; var home:HomeVO = this._homes[ i ]; var creationTimer:Timer = new Timer( CHome.VILLAGER_CREATION_TIME / CHome.VILLAGER_CREATION_TIMELY, CHome.VILLAGER_CREATION_TIMELY ); creationTimer.addEventListener( TimerEvent.TIMER, function ():void { var homeEvent:HomeEvent = new HomeEvent( HomeEvent.VILLAGER_CREATION_IN_PROGRESS ); homeEvent.progressPercentage = creationTimer.currentCount * CHome.VILLAGER_CREATION_TIMELY; homeEvent.homeVO = home; dispatch( homeEvent ); } ); Tweener.addTween( this, { time: 2, onComplete: creationTimerCompleteHandler, onCompleteParams: [ home ] } ); creationTimer.start(); } } } } private function creationTimerCompleteHandler( homeVO:HomeVO ):void { homeVO.villagerIsCreating = false; trace( '@@@@@===============>>>>>', homeVO.id ); var homeEvent:HomeEvent = new HomeEvent( HomeEvent.REQUEST_TO_CREATE_VILLAGER ); homeEvent.homeVO = homeVO; this.dispatch( homeEvent ); } public function setInitHomes( homes:Vector.<HomeVO> ):void { this._homes = homes; this.setHomeVOIds(); } private function setHomeVOIds():void { for ( var i:int = 0; i < this._homes.length; i++ ) { this._homes[ i ].id = i; } } public function addVillager( homeVO:HomeVO, villagerVO:VillagerVO ):void { homeVO.villagers.push( villagerVO ); } public function updateFoodAmount( homeVO:HomeVO, amount:int ):void { homeVO.food = amount; var event:HomeEvent = new HomeEvent( HomeEvent.FOOD_AMOUNT_UPDATED ); event.homeVO = homeVO; this.dispatch( event ); } public function updateWoodAmount( homeVO:HomeVO, amount:int ):void { homeVO.wood = amount; var event:HomeEvent = new HomeEvent( HomeEvent.WOOD_AMOUNT_UPDATED ); event.homeVO = homeVO; this.dispatch( event ); } public function getHomeByVillager( villagerVO:VillagerVO ):HomeVO { for ( var i:int = 0; i < this._homes.length; i++ ) { for ( var j:int = 0; j < this._homes[ i ].villagers.length; j++ ) { if ( this._homes[ i ].villagers[ j ] == villagerVO ) { return this._homes[ i ]; } } } return null; } } }
/** * Created by vizoli on 4/9/16. */ package ageofai.home.model { import ageofai.cost.constant.CUnitCost; import ageofai.home.ai.HomeAI; import ageofai.home.constant.CHome; import ageofai.home.event.HomeEvent; import ageofai.home.vo.HomeVO; import ageofai.villager.vo.VillagerVO; import flash.utils.Dictionary; import caurina.transitions.Tweener; import common.mvc.model.base.BaseModel; import flash.events.TimerEvent; import flash.utils.Timer; public class HomeModel extends BaseModel implements IHomeModel { private var _homes:Vector.<HomeVO>; private var _homeAI:HomeAI; private var _progressDic:Dictionary = new Dictionary(true); public function HomeModel() { this._homeAI = new HomeAI(); } public function tick():void { this.calculateVillagerCreation(); } private function calculateVillagerCreation():void { for ( var i:int = 0; i < this._homes.length; i++ ) { if ( !this._homes[ i ].villagerIsCreating ) { if ( this._homeAI.isNewVillagerAvailable( this._homes[ i ].food, this._homes[ i ].villagers.length ) ) { this._homes[ i ].villagerIsCreating = true; this.updateFoodAmount( this._homes[ i ], this._homes[ i ].food - CUnitCost.VILLAGER.food ); this._homes[ i ].food -= CUnitCost.VILLAGER.food; var home:HomeVO = this._homes[ i ]; var creationTimer:Timer = new Timer( CHome.VILLAGER_CREATION_TIME / CHome.VILLAGER_CREATION_TIMELY, CHome.VILLAGER_CREATION_TIMELY ); creationTimer.addEventListener( TimerEvent.TIMER, creationTimerHandler ); _progressDic[creationTimer] = home; Tweener.addTween( this, { time: 2, onComplete: creationTimerCompleteHandler, onCompleteParams: [ home ] } ); creationTimer.start(); } } } } private function creationTimerHandler(e:TimerEvent):void { var home:HomeVO = _progressDic[e.currentTarget]; var homeEvent:HomeEvent = new HomeEvent( HomeEvent.VILLAGER_CREATION_IN_PROGRESS ); homeEvent.progressPercentage = e.currentTarget.currentCount * CHome.VILLAGER_CREATION_TIMELY; homeEvent.homeVO = home; dispatch( homeEvent ); } private function creationTimerCompleteHandler( homeVO:HomeVO ):void { homeVO.villagerIsCreating = false; trace( '@@@@@===============>>>>>', homeVO.id ); var homeEvent:HomeEvent = new HomeEvent( HomeEvent.REQUEST_TO_CREATE_VILLAGER ); homeEvent.homeVO = homeVO; this.dispatch( homeEvent ); } public function setInitHomes( homes:Vector.<HomeVO> ):void { this._homes = homes; this.setHomeVOIds(); } private function setHomeVOIds():void { for ( var i:int = 0; i < this._homes.length; i++ ) { this._homes[ i ].id = i; } } public function addVillager( homeVO:HomeVO, villagerVO:VillagerVO ):void { homeVO.villagers.push( villagerVO ); } public function updateFoodAmount( homeVO:HomeVO, amount:int ):void { homeVO.food = amount; var event:HomeEvent = new HomeEvent( HomeEvent.FOOD_AMOUNT_UPDATED ); event.homeVO = homeVO; this.dispatch( event ); } public function updateWoodAmount( homeVO:HomeVO, amount:int ):void { homeVO.wood = amount; var event:HomeEvent = new HomeEvent( HomeEvent.WOOD_AMOUNT_UPDATED ); event.homeVO = homeVO; this.dispatch( event ); } public function getHomeByVillager( villagerVO:VillagerVO ):HomeVO { for ( var i:int = 0; i < this._homes.length; i++ ) { for ( var j:int = 0; j < this._homes[ i ].villagers.length; j++ ) { if ( this._homes[ i ].villagers[ j ] == villagerVO ) { return this._homes[ i ]; } } } return null; } } }
fix creation progress
fix creation progress
ActionScript
apache-2.0
goc-flashplusplus/ageofai
f46f8459c86a628e573b6d4c73f18e057e8a7506
src/org/mangui/osmf/plugins/HLSDynamicPlugin.as
src/org/mangui/osmf/plugins/HLSDynamicPlugin.as
package org.mangui.osmf.plugins { import flash.display.Sprite; import flash.system.Security; import org.mangui.osmf.plugins.HLSPlugin; import org.osmf.media.PluginInfo; public class HLSDynamicPlugin extends Sprite { private var _pluginInfo:PluginInfo; public function HLSDynamicPlugin() { super(); Security.allowDomain("*"); _pluginInfo = new HLSPlugin(); } public function get pluginInfo():PluginInfo{ return _pluginInfo; } } }
package org.mangui.osmf.plugins { import flash.display.Sprite; import flash.system.Security; import org.osmf.media.PluginInfo; public class HLSDynamicPlugin extends Sprite { private var _pluginInfo:PluginInfo; public function HLSDynamicPlugin() { super(); Security.allowDomain("*"); _pluginInfo = new HLSPlugin(); } public function get pluginInfo():PluginInfo{ return _pluginInfo; } } }
remove unused import
remove unused import
ActionScript
mpl-2.0
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
2e4e7af924e7d155aac8824f8f038d679e54ee9d
sdk-remote/src/tests/examples/urbi-send.as
sdk-remote/src/tests/examples/urbi-send.as
-*- shell-script -*- URBI_INIT me=$as_me medir=$(echo "$as_me" | sed -e 's/\..*//').dir rm -rf $medir mkdir $medir cd $medir xrun "--help" urbi-send --help xrun "--version" urbi-send --version
-*- shell-script -*- URBI_INIT me=$as_me medir=$(absolute "$0").dir rm -rf $medir mkdir -p $medir cd $medir xrun "--help" urbi-send --help xrun "--version" urbi-send --version
Fix clean rules.
Fix clean rules. * src/tests/examples/urbi-send.as (medir): Fix its value.
ActionScript
bsd-3-clause
aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi
151a021f65845534acb384cfcb598daaeccebda4
src/as/com/threerings/bureau/data/AgentObject.as
src/as/com/threerings/bureau/data/AgentObject.as
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2008 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.bureau.data { import com.threerings.presents.dobj.DObject; public class AgentObject extends DObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>bureauId</code> field. */ public static const BUREAU_ID :String = "bureauId"; /** The field name of the <code>bureauType</code> field. */ public static const BUREAU_TYPE :String = "bureauType"; /** The field name of the <code>agentCode</code> field. */ public static const AGENT_CODE :String = "agentCode"; // AUTO-GENERATED: FIELDS END /** The id of the bureau the agent is running in. This is normally a unique id corresponding * to the game or item that requires some server-side processing. */ public var bureauId :String; /** The type of bureau that the agent is running in. This is normally derived from the kind * of media that the game or item has specified for its code and determines the method of * launching the bureau when the first agent is requested. */ public var bureauType :String; /** The location of the code for the agent. This could be a URL to an action script file or * some other description that the bureau can use to load and execute the agent's code. */ public var agentCode :String; // AUTO-GENERATED: METHODS START /** * Requests that the <code>bureauId</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public function setBureauId (value :String) :void { var ovalue :String = this.bureauId; requestAttributeChange( BUREAU_ID, value, ovalue); this.bureauId = value; } /** * Requests that the <code>bureauType</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public function setBureauType (value :String) :void { var ovalue :String = this.bureauType; requestAttributeChange( BUREAU_TYPE, value, ovalue); this.bureauType = value; } /** * Requests that the <code>agentCode</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public function setAgentCode (value :String) :void { var ovalue :String = this.agentCode; requestAttributeChange( AGENT_CODE, value, ovalue); this.agentCode = value; } // AUTO-GENERATED: METHODS END } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2008 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library 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 2.1 of the License, or // (at your option) any later version. // // This library 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 this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.bureau.data { import com.threerings.io.ObjectInputStream; import com.threerings.presents.dobj.DObject; public class AgentObject extends DObject { // AUTO-GENERATED: FIELDS START /** The field name of the <code>bureauId</code> field. */ public static const BUREAU_ID :String = "bureauId"; /** The field name of the <code>bureauType</code> field. */ public static const BUREAU_TYPE :String = "bureauType"; /** The field name of the <code>agentCode</code> field. */ public static const AGENT_CODE :String = "agentCode"; // AUTO-GENERATED: FIELDS END /** The id of the bureau the agent is running in. This is normally a unique id corresponding * to the game or item that requires some server-side processing. */ public var bureauId :String; /** The type of bureau that the agent is running in. This is normally derived from the kind * of media that the game or item has specified for its code and determines the method of * launching the bureau when the first agent is requested. */ public var bureauType :String; /** The location of the code for the agent. This could be a URL to an action script file or * some other description that the bureau can use to load and execute the agent's code. */ public var agentCode :String; // AUTO-GENERATED: METHODS START /** * Requests that the <code>bureauId</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public function setBureauId (value :String) :void { var ovalue :String = this.bureauId; requestAttributeChange( BUREAU_ID, value, ovalue); this.bureauId = value; } /** * Requests that the <code>bureauType</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public function setBureauType (value :String) :void { var ovalue :String = this.bureauType; requestAttributeChange( BUREAU_TYPE, value, ovalue); this.bureauType = value; } /** * Requests that the <code>agentCode</code> field be set to the * specified value. The local value will be updated immediately and an * event will be propagated through the system to notify all listeners * that the attribute did change. Proxied copies of this object (on * clients) will apply the value change when they received the * attribute changed notification. */ public function setAgentCode (value :String) :void { var ovalue :String = this.agentCode; requestAttributeChange( AGENT_CODE, value, ovalue); this.agentCode = value; } // AUTO-GENERATED: METHODS END // from interface Streamable override public function readObject (ins :ObjectInputStream) :void { super.readObject(ins); bureauId = ins.readField(String) as String; bureauType = ins.readField(String) as String; agentCode = ins.readField(String) as String; } } }
Configure the AgentObject from the stream.
Configure the AgentObject from the stream. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5088 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
4a9c31c958b977ca465c136c23ee9542dcb84de8
Arguments/src/classes/Language.as
Arguments/src/classes/Language.as
package classes { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.ByteArray; import mx.controls.Alert; import org.osmf.layout.AbsoluteLayoutFacet; public class Language { //I will set the language to either GERMAN, RUSSIAN or ENGLISH //based on this, you could read the values into the variables //by default, the language is EN-US public static const GERMAN:String = "GER"; public static const ENGLISH:String = "EN-US"; public static const RUSSIAN:String = "RUS"; public static var language:String = GERMAN; public static var xml:XML; private static var ready:Boolean=false; public static function init():void { [Embed(source="../../../translation.xml", mimeType="application/octet-stream")] const MyData:Class; var byteArray:ByteArray = new MyData() as ByteArray; var x:XML = new XML(byteArray.readUTFBytes(byteArray.length)); xml = x; ready=true; } /**The key function. Use this to look up a label from the translation document according to the set language.*/ public static function lookup(label:String):String{ if(!ready){ init(); } trace("Now looking up:" + label); var lbl:XMLList = xml.descendants(label); var lang:XMLList = lbl.descendants(language); var output:String = lang.attribute("text"); if(!output){ output = "error | ошибка | fehler --- There was a problem getting the text for this item. The label was: " + label; } trace("Output is: " + output); return output; } } }
package classes { /** AGORA - an interactive and web-based argument mapping tool that stimulates reasoning, reflection, critique, deliberation, and creativity in individual argument construction and in collaborative or adversarial settings. Copyright (C) 2011 Georgia Institute of Technology This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import flash.events.Event; import flash.events.IOErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.ByteArray; import mx.controls.Alert; import org.osmf.layout.AbsoluteLayoutFacet; public class Language { //I will set the language to either GERMAN, RUSSIAN or ENGLISH //based on this, you could read the values into the variables //by default, the language is EN-US public static const GERMAN:String = "GER"; public static const ENGLISH:String = "EN-US"; public static const RUSSIAN:String = "RUS"; public static var language:String = ENGLISH; public static var xml:XML; private static var ready:Boolean=false; public static function init():void { [Embed(source="../../../translation.xml", mimeType="application/octet-stream")] const MyData:Class; var byteArray:ByteArray = new MyData() as ByteArray; var x:XML = new XML(byteArray.readUTFBytes(byteArray.length)); xml = x; ready=true; } /**The key function. Use this to look up a label from the translation document according to the set language.*/ public static function lookup(label:String):String{ if(!ready){ init(); } trace("Now looking up:" + label); var lbl:XMLList = xml.descendants(label); var lang:XMLList = lbl.descendants(language); var output:String = lang.attribute("text"); if(!output){ output = "error | ошибка | fehler --- There was a problem getting the text for this item. The label was: " + label; } trace("Output is: " + output); return output; } } }
Move default to English once more
Move default to English once more
ActionScript
agpl-3.0
MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA
f390af8237f1f6320f5932e247f3e20328025eb8
src/aerys/minko/render/DrawCall.as
src/aerys/minko/render/DrawCall.as
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.render.geometry.Geometry; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get depth() : Number { if (_invalidDepth) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { _localToWorld.transformVector(Vector4.ZERO, TMP_VECTOR4); _depth = _worldToScreen.transformVector(TMP_VECTOR4, TMP_VECTOR4).z; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { if (_bindings != null) unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); updateGeometry(geometry); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { trace('unset bindings'); for (var parameter : String in _bindings) { meshBindings.removeCallback(parameter, parameterChangedHandler); sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.concat(); _fsConstants = program._fsConstants.concat(); _fsTextures = program._fsTextures.concat(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(StreamUsage.DYNAMIC); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(StreamUsage.DYNAMIC); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { trace('set bindings'); for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getNativeTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { var binding : IBinder = _bindings[name] as IBinder; trace(name); if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
package aerys.minko.render { import aerys.minko.ns.minko_render; import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.StreamUsage; import aerys.minko.render.geometry.stream.VertexStream; import aerys.minko.render.geometry.stream.format.VertexComponent; import aerys.minko.render.geometry.stream.format.VertexFormat; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.resource.VertexBuffer3DResource; import aerys.minko.render.resource.texture.ITextureResource; import aerys.minko.render.shader.binding.IBinder; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.enum.Blending; import aerys.minko.type.enum.ColorMask; import aerys.minko.type.enum.TriangleCulling; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display3D.Context3DProgramType; import flash.utils.Dictionary; /** * DrawCall objects contain all the shader constants and buffer settings required * to perform drawing operations using the Stage3D API. * @author Jean-Marc Le Roux * */ public final class DrawCall { use namespace minko_render; private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX; private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT; private static const NUM_TEXTURES : uint = 8; private static const NUM_VERTEX_BUFFERS : uint = 8; private static const TMP_VECTOR4 : Vector4 = new Vector4(); private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true); private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true); private var _bindings : Object = null; private var _vsInputComponents : Vector.<VertexComponent> = null; private var _vsInputIndices : Vector.<uint> = null; private var _cpuConstants : Dictionary = null; private var _vsConstants : Vector.<Number> = null; private var _fsConstants : Vector.<Number> = null; private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true); // states private var _indexBuffer : IndexBuffer3DResource = null; private var _firstIndex : int = 0; private var _numTriangles : int = -1; private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true); private var _numVertexComponents: uint = 0; private var _offsets : Vector.<int> = new Vector.<int>(8, true); private var _formats : Vector.<String> = new Vector.<String>(8, true); private var _blending : uint = 0; private var _blendingSource : String = null; private var _blendingDest : String = null; private var _triangleCulling : uint = 0; private var _triangleCullingStr : String = null; private var _colorMask : uint = 0; private var _colorMaskR : Boolean = true; private var _colorMaskG : Boolean = true; private var _colorMaskB : Boolean = true; private var _colorMaskA : Boolean = true; private var _enabled : Boolean = true; private var _depth : Number = 0.; private var _invalidDepth : Boolean = false; private var _localToWorld : Matrix4x4 = null; private var _worldToScreen : Matrix4x4 = null; public function get vertexComponents() : Vector.<VertexComponent> { return _vsInputComponents; } public function get blending() : uint { return _blending; } public function set blending(value : uint) : void { _blending = value; _blendingSource = Blending.STRINGS[int(value & 0xffff)]; _blendingDest = Blending.STRINGS[int(value >>> 16)] } public function get triangleCulling() : uint { return _triangleCulling; } public function set triangleCulling(value : uint) : void { _triangleCulling = value; _triangleCullingStr = TriangleCulling.STRINGS[value]; } public function get colorMask() : uint { return _colorMask; } public function set colorMask(value : uint) : void { _colorMask = value; _colorMaskR = (value & ColorMask.RED) != 0; _colorMaskG = (value & ColorMask.GREEN) != 0; _colorMaskB = (value & ColorMask.BLUE) != 0; _colorMaskA = (value & ColorMask.ALPHA) != 0; } public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get depth() : Number { if (_invalidDepth) { _invalidDepth = false; if (_localToWorld != null && _worldToScreen != null) { _localToWorld.transformVector(Vector4.ZERO, TMP_VECTOR4); _depth = _worldToScreen.transformVector(TMP_VECTOR4, TMP_VECTOR4).z; } } return _depth; } public function configure(program : Program3DResource, geometry : Geometry, meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { if (_bindings != null) unsetBindings(meshBindings, sceneBindings); _invalidDepth = computeDepth; setProgram(program); updateGeometry(geometry); setGeometry(geometry); setBindings(meshBindings, sceneBindings, computeDepth); } public function unsetBindings(meshBindings : DataBindings, sceneBindings : DataBindings) : void { for (var parameter : String in _bindings) { meshBindings.removeCallback(parameter, parameterChangedHandler); sceneBindings.removeCallback(parameter, parameterChangedHandler); } if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler)) sceneBindings.removeCallback('worldToScreen', transformChangedHandler); if (meshBindings.hasCallback('localToWorld', transformChangedHandler)) meshBindings.removeCallback('localToWorld', transformChangedHandler); } private function setProgram(program : Program3DResource) : void { _cpuConstants = new Dictionary(); _vsConstants = program._vsConstants.concat(); _fsConstants = program._fsConstants.concat(); _fsTextures = program._fsTextures.concat(); _vsInputComponents = program._vertexInputComponents; _vsInputIndices = program._vertexInputIndices; _bindings = program._bindings; triangleCulling = TriangleCulling.FRONT; blending = Blending.NORMAL; colorMask = ColorMask.RGBA; } /** * Ask geometry to compute additional vertex data if needed for this drawcall. */ public function updateGeometry(geometry : Geometry) : void { var vertexFormat : VertexFormat = geometry.format; if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0 && !vertexFormat.hasComponent(VertexComponent.TANGENT)) { geometry.computeTangentSpace(StreamUsage.DYNAMIC); } else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !vertexFormat.hasComponent(VertexComponent.NORMAL)) { geometry.computeNormals(StreamUsage.DYNAMIC); } } /** * Obtain a reference to each buffer and offset that apply() may possibly need. * */ public function setGeometry(geometry : Geometry, frame : uint = 0) : void { _numVertexComponents = _vsInputComponents.length; _indexBuffer = geometry.indexStream.resource; _firstIndex = geometry.firstIndex; _numTriangles = geometry.numTriangles; for (var i : uint = 0; i < _numVertexComponents; ++i) { var component : VertexComponent = _vsInputComponents[i]; var index : uint = _vsInputIndices[i]; if (component) { var vertexStream : IVertexStream = geometry.getVertexStream(index + frame); var stream : VertexStream = vertexStream.getStreamByComponent(component); if (stream == null) { throw new Error( 'Missing vertex component: \'' + component.toString() + '\'.' ); } _vertexBuffers[i] = stream.resource; _formats[i] = component.nativeFormatString; _offsets[i] = stream.format.getOffsetForComponent(component); } } } /** * @fixme There is a bug here * @fixme We splitted properties between scene and mesh * @fixme it should be done on the compiler also to avoid this ugly hack */ private function setBindings(meshBindings : DataBindings, sceneBindings : DataBindings, computeDepth : Boolean) : void { for (var parameter : String in _bindings) { meshBindings.addCallback(parameter, parameterChangedHandler); sceneBindings.addCallback(parameter, parameterChangedHandler); if (meshBindings.propertyExists(parameter)) setParameter(parameter, meshBindings.getProperty(parameter)); else if (sceneBindings.propertyExists(parameter)) setParameter(parameter, sceneBindings.getProperty(parameter)); } if (computeDepth) { _worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4; _localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4; sceneBindings.addCallback('worldToScreen', transformChangedHandler); meshBindings.addCallback('localToWorld', transformChangedHandler); _invalidDepth = true; } } public function apply(context : Context3DResource, previous : DrawCall) : uint { if (!_enabled) return 0; context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA) .setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants) .setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants); var numTextures : uint = _fsTextures.length; var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES; var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS; var i : uint = 0; // setup textures for (i = 0; i < numTextures; ++i) { context.setTextureAt( i, (_fsTextures[i] as ITextureResource).getNativeTexture(context) ); } while (i < maxTextures) context.setTextureAt(i++, null); // setup buffers for (i = 0; i < _numVertexComponents; ++i) { context.setVertexBufferAt( i, (_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context), _offsets[i], _formats[i] ); } while (i < maxBuffers) context.setVertexBufferAt(i++, null); // draw triangles context.drawTriangles( _indexBuffer.getIndexBuffer3D(context), _firstIndex, _numTriangles ); return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles; } public function setParameter(name : String, value : Object) : void { var binding : IBinder = _bindings[name] as IBinder; if (binding != null) binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value); } private function parameterChangedHandler(dataBindings : DataBindings, property : String, oldValue : Object, newValue : Object) : void { newValue !== null && setParameter(property, newValue); } private function transformChangedHandler(bindings : DataBindings, property : String, oldValue : Matrix4x4, newValue : Matrix4x4) : void { if (property == 'worldToScreen') _worldToScreen = newValue; else if (property == 'localToWorld') _localToWorld = newValue; _invalidDepth = true; } } }
remove call to trace() in DrawCall
remove call to trace() in DrawCall
ActionScript
mit
aerys/minko-as3
0ed5138a037b9a5ab02755bb3b7442197df1838b
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private const TOR_ADDRESS:String = "173.255.221.44"; private const TOR_PORT:int = 9001; private var output_text:TextField; // Socket to Tor relay. private var s_t:Socket; // Socket to Facilitator. private var s_f:Socket; // Socket to client. private var s_c:Socket; private var fac_address:String; private var fac_port:int; private var client_address:String; private var client_port:int; private function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String, parts:Array; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); parts = fac_spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } fac_address = parts[0]; fac_port = parseInt(parts[1]); go(TOR_ADDRESS, TOR_PORT); } /* We connect first to the Tor relay; once that happens we connect to the facilitator to get a client address; once we have the address of a waiting client then we connect to the client and BAM! we're in business. */ private function go(tor_address:String, tor_port:int):void { s_t = new Socket(); s_t.addEventListener(Event.CONNECT, tor_connected); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); puts("Tor: connecting to " + tor_address + ":" + tor_port + "."); s_t.connect(tor_address, tor_port); } private function tor_connected(e:Event):void { /* Got a connection to tor, now let's get served a client from the facilitator */ s_f = new Socket(); puts("Tor: connected."); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); if (s_t.connected) s_t.close(); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); if (s_t.connected) s_t.close(); }); puts("Facilitator: connecting to " + fac_address + ":" + fac_port + "."); s_f.connect(fac_address, fac_port); /*s_c = new Socket(); puts("Tor: connected."); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { puts("Client: closed."); if (s_t.connected) s_t.close(); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Client: I/O error: " + e.text + "."); if (s_t.connected) s_t.close(); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Client: security error: " + e.text + "."); if (s_t.connected) s_t.close(); }); puts("Client: connecting to " + client_address + ":" + client_port + "."); s_c.connect(client_address, client_port);*/ } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var client_spec:String = new String(); client_spec = s_f.readUTF(); puts("Facilitator: got \"" + client_spec + "\""); //s_c.writeBytes(bytes); /* Need to parse the bytes to get the new client. Fill out client_address and client_port */ }); s_f.writeUTFBytes("GET / HTTP/1.0"); s_f.flush(); } private function client_connected(e:Event):void { puts("Client: connected."); s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_t.readBytes(bytes, 0, e.bytesLoaded); puts("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); puts("Client: read " + bytes.length + "."); s_t.writeBytes(bytes); }); } } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private const TOR_ADDRESS:String = "173.255.221.44"; private const TOR_PORT:int = 9001; private var output_text:TextField; // Socket to Tor relay. private var s_t:Socket; // Socket to Facilitator. private var s_f:Socket; // Socket to client. private var s_c:Socket; private var fac_address:String; private var fac_port:int; private var client_address:String; private var client_port:int; private function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String, parts:Array; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); parts = fac_spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } fac_address = parts[0]; fac_port = parseInt(parts[1]); go(TOR_ADDRESS, TOR_PORT); } /* We connect first to the Tor relay; once that happens we connect to the facilitator to get a client address; once we have the address of a waiting client then we connect to the client and BAM! we're in business. */ private function go(tor_address:String, tor_port:int):void { s_t = new Socket(); s_t.addEventListener(Event.CONNECT, tor_connected); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); puts("Tor: connecting to " + tor_address + ":" + tor_port + "."); s_t.connect(tor_address, tor_port); } private function tor_connected(e:Event):void { /* Got a connection to tor, now let's get served a client from the facilitator */ s_f = new Socket(); puts("Tor: connected."); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); if (s_t.connected) s_t.close(); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); if (s_t.connected) s_t.close(); }); puts("Facilitator: connecting to " + fac_address + ":" + fac_port + "."); s_f.connect(fac_address, fac_port); /*s_c = new Socket(); puts("Tor: connected."); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { puts("Client: closed."); if (s_t.connected) s_t.close(); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Client: I/O error: " + e.text + "."); if (s_t.connected) s_t.close(); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Client: security error: " + e.text + "."); if (s_t.connected) s_t.close(); }); puts("Client: connecting to " + client_address + ":" + client_port + "."); s_c.connect(client_address, client_port);*/ } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var client_spec:String = new String(); client_spec = s_f.readUTF(); puts("Facilitator: got \"" + client_spec + "\""); //s_c.writeBytes(bytes); /* Need to parse the bytes to get the new client. Fill out client_address and client_port */ }); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); s_f.flush(); } private function client_connected(e:Event):void { puts("Client: connected."); s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_t.readBytes(bytes, 0, e.bytesLoaded); puts("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); puts("Client: read " + bytes.length + "."); s_t.writeBytes(bytes); }); } } }
Add "\r\n\r\n" to finish the GET request.
Add "\r\n\r\n" to finish the GET request.
ActionScript
mit
infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy
e1f13b21ca65210081f4e8887a7c3753f9dc32f8
activities/module-2/series-measuring/Probe.as
activities/module-2/series-measuring/Probe.as
package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.geom.Point; import org.concord.sparks.JavaScript; import org.concord.sparks.util.Display; public class Probe extends MovieClip { private var circuit:Circuit; private var connection:Object = null; private var id:String; private var _dragging:Boolean = false; private var _down:Boolean = false; public function Probe() { //trace('ENTER Probe#Probe'); super(); id = this.name; trace('Probe id=' + id); this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove); stage.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp); } public function getId() { return id; } public function getConnection():Object { return connection; } public function setConnection(connection:Object):void { this.connection = connection; } public function setCircuit(circuit:Circuit) { //trace('ENTER Probe#setCircuit'); this.circuit = circuit; } public function getTipPos():Point { return Display.localToStage(this.parent, new Point(this.x, this.y)); } public function onMouseDown(event:MouseEvent):void { _down = true; circuit.putProbeOnTop(this); } public function onMouseUp(event:MouseEvent):void { trace('ENTER Probe#onMouseUp'); this.stopDrag(); _down = false; if (_dragging) { _dragging = false; circuit.updateProbeConnection(this); } } public function onMouseMove(event:MouseEvent):void { //trace('ENTER Probe#onMouseMove'); if (! _down) { return; } if (_dragging) { circuit.updateResistorEndColors(this); } else { _dragging = true; this.startDrag(); if (connection) { disConnect(); } } } private function disConnect():void { JavaScript.instance().sendEvent('disconnect', 'probe', getId(), connection.getId()); connection = null; } } }
package { //test change// import flash.display.MovieClip; import flash.events.MouseEvent; import flash.geom.Point; import org.concord.sparks.JavaScript; import org.concord.sparks.util.Display; public class Probe extends MovieClip { private var circuit:Circuit; private var connection:Object = null; private var id:String; private var _dragging:Boolean = false; private var _down:Boolean = false; public function Probe() { //trace('ENTER Probe#Probe'); super(); id = this.name; trace('Probe id=' + id); this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown); this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp); this.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove); stage.addEventListener(MouseEvent.MOUSE_OUT, onMouseUp); } public function getId() { return id; } public function getConnection():Object { return connection; } public function setConnection(connection:Object):void { this.connection = connection; } public function setCircuit(circuit:Circuit) { //trace('ENTER Probe#setCircuit'); this.circuit = circuit; } public function getTipPos():Point { return Display.localToStage(this.parent, new Point(this.x, this.y)); } public function onMouseDown(event:MouseEvent):void { _down = true; circuit.putProbeOnTop(this); } public function onMouseUp(event:MouseEvent):void { trace('ENTER Probe#onMouseUp'); this.stopDrag(); _down = false; if (_dragging) { _dragging = false; circuit.updateProbeConnection(this); } } public function onMouseMove(event:MouseEvent):void { //trace('ENTER Probe#onMouseMove'); if (! _down) { return; } if (_dragging) { circuit.updateResistorEndColors(this); } else { _dragging = true; this.startDrag(); if (connection) { disConnect(); } } } private function disConnect():void { JavaScript.instance().sendEvent('disconnect', 'probe', getId(), connection.getId()); connection = null; } } }
test change
test change
ActionScript
apache-2.0
concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks,concord-consortium/sparks
efed6d80241205315ae3f79724d0cd027a2319c1
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.events.Event; import flash.utils.setTimeout; import FacilitatorSocket; import events.FacilitatorSocketEvent; import ProxyPair; import RTMFPProxyPair; import SQSProxyPair; import TCPProxyPair; import rtmfp.CirrusSocket; import rtmfp.events.CirrusSocketEvent; public class swfcat extends Sprite { /* Adobe's Cirrus server for RTMFP connections. The Cirrus key is defined at compile time by reading from the CIRRUS_KEY environment var. */ private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net"; private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Default Tor client to use in case of RTMFP connection */ private const DEFAULT_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; /* Poll facilitator every 10 sec */ private const DEFAULT_FAC_POLL_INTERVAL:uint = 10000; // Socket to Cirrus server private var s_c:CirrusSocket; // Socket to facilitator. private var s_f:FacilitatorSocket; // Handle local-remote traffic private var p_p:ProxyPair; private var client_id:String; private var proxy_pair_factory:Function; private var proxy_pairs:Array; private var debug_mode:Boolean; private var proxy_mode:Boolean; /* TextField for debug output. */ private var output_text:TextField; /* Badge for display */ private var badge:InternetFreedomBadge; private var fac_addr:Object; private var relay_addr:Object; public function swfcat() { proxy_mode = false; debug_mode = false; // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } public function puts(s:String):void { if (output_text != null) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } private function loaderinfo_complete(e:Event):void { var fac_spec:String; var relay_spec:String; debug_mode = (this.loaderInfo.parameters["debug"] != null) proxy_mode = (this.loaderInfo.parameters["proxy"] != null); if (proxy_mode && !debug_mode) { badge = new InternetFreedomBadge(this); badge.display(); } else { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } puts("Starting: parameters loaded."); /* TODO: use this to have multiple proxies going at once */ proxy_pairs = new Array(); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { if (proxy_mode) { establish_facilitator_connection(); } else { establish_cirrus_connection(); } } private function establish_cirrus_connection():void { s_c = new CirrusSocket(); s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void { puts("Cirrus: connected with id " + s_c.id + "."); if (proxy_mode) { start_proxy_pair(); s_c.send_hello(client_id); } else { establish_facilitator_connection(); } }); s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void { puts("Error: failed to connect to Cirrus."); }); s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void { puts("Cirrus: closed connection."); }); s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void { puts("Cirrus: received hello from peer " + e.peer); /* don't bother if we already have a proxy going */ if (p_p != null && p_p.connected) { return; } /* if we're in proxy mode, we should have already set up a proxy pair */ if (!proxy_mode) { relay_addr = DEFAULT_TOR_CLIENT_ADDR; proxy_pair_factory = rtmfp_proxy_pair_factory; start_proxy_pair(); s_c.send_hello(e.peer); } else if (!debug_mode && badge != null) { badge.total_proxy_pairs++; badge.num_proxy_pairs++; } p_p.client = {peer: e.peer, stream: e.stream}; }); s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY); } private function establish_facilitator_connection():void { s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port); s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void { puts("Facilitator: connect failed."); setTimeout(establish_facilitator_connection, DEFAULT_FAC_POLL_INTERVAL); }); if (proxy_mode) { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void { var client_addr:Object = parse_addr_spec(e.client); relay_addr = parse_addr_spec(e.relay); if (client_addr == null) { puts("Facilitator: got registration " + e.client); proxy_pair_factory = rtmfp_proxy_pair_factory; if (s_c == null || !s_c.connected) { client_id = e.client; establish_cirrus_connection(); } else { start_proxy_pair(); s_c.send_hello(e.client); } } else { proxy_pair_factory = tcp_proxy_pair_factory; start_proxy_pair(); p_p.client = client_addr; } }); s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void { puts("Facilitator: no registrations available."); setTimeout(establish_facilitator_connection, DEFAULT_FAC_POLL_INTERVAL); }); puts("Facilitator: getting registration."); s_f.get_registration(); } else { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void { puts("Facilitator: registration failed."); setTimeout(establish_facilitator_connection, DEFAULT_FAC_POLL_INTERVAL); }); puts("Facilitator: posting registration."); s_f.post_registration(s_c.id); } } private function start_proxy_pair():void { p_p = proxy_pair_factory(); p_p.addEventListener(Event.CONNECT, function (e:Event):void { puts("ProxyPair: connected!"); }); p_p.addEventListener(Event.CLOSE, function (e:Event):void { puts("ProxyPair: connection closed."); p_p = null; if (proxy_mode && !debug_mode && badge != null) { badge.num_proxy_pairs--; } establish_facilitator_connection(); }); p_p.relay = relay_addr; } private function rtmfp_proxy_pair_factory():ProxyPair { return new RTMFPProxyPair(this, s_c, s_c.local_stream_name); } // currently is the same as TCPProxyPair // could be interesting to see how this works // can't imagine it will work terribly well... private function sqs_proxy_pair_factory():ProxyPair { return new SQSProxyPair(this); } private function tcp_proxy_pair_factory():ProxyPair { return new TCPProxyPair(this); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextField; import flash.text.TextFormat; class InternetFreedomBadge { private var ui:swfcat; private var _num_proxy_pairs:uint; private var _total_proxy_pairs:uint; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function InternetFreedomBadge(ui:swfcat) { this.ui = ui; _num_proxy_pairs = 0; _total_proxy_pairs = 0; /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; /* Update the client counter on badge. */ update_client_count(); } public function display():void { ui.addChild(new BadgeImage()); /* Tried unsuccessfully to add counter to badge. */ /* For now, need two addChilds :( */ ui.addChild(tot_client_count_tf); ui.addChild(cur_client_count_tf); } public function get num_proxy_pairs():uint { return _num_proxy_pairs; } public function set num_proxy_pairs(amount:uint):void { _num_proxy_pairs = amount; update_client_count(); } public function get total_proxy_pairs():uint { return _total_proxy_pairs; } public function set total_proxy_pairs(amount:uint):void { _total_proxy_pairs = amount; /* note: doesn't update, so be sure to update this before you update num_proxy_pairs! */ } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } }
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.events.Event; import flash.utils.setTimeout; import FacilitatorSocket; import events.FacilitatorSocketEvent; import ProxyPair; import RTMFPProxyPair; import SQSProxyPair; import TCPProxyPair; import rtmfp.CirrusSocket; import rtmfp.events.CirrusSocketEvent; public class swfcat extends Sprite { /* Adobe's Cirrus server for RTMFP connections. The Cirrus key is defined at compile time by reading from the CIRRUS_KEY environment var. */ private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net"; private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Default Tor client to use in case of RTMFP connection */ private const DEFAULT_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to Cirrus server private var s_c:CirrusSocket; // Socket to facilitator. private var s_f:FacilitatorSocket; // Handle local-remote traffic private var p_p:ProxyPair; private var client_id:String; private var proxy_pair_factory:Function; private var proxy_pairs:Array; private var debug_mode:Boolean; private var proxy_mode:Boolean; /* TextField for debug output. */ private var output_text:TextField; /* Badge for display */ private var badge:InternetFreedomBadge; private var fac_addr:Object; private var relay_addr:Object; public function swfcat() { proxy_mode = false; debug_mode = false; // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } public function puts(s:String):void { if (output_text != null) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } private function loaderinfo_complete(e:Event):void { var fac_spec:String; var relay_spec:String; debug_mode = (this.loaderInfo.parameters["debug"] != null) proxy_mode = (this.loaderInfo.parameters["proxy"] != null); if (proxy_mode && !debug_mode) { badge = new InternetFreedomBadge(this); badge.display(); } else { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } puts("Starting: parameters loaded."); /* TODO: use this to have multiple proxies going at once */ proxy_pairs = new Array(); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { if (proxy_mode) { establish_facilitator_connection(); } else { establish_cirrus_connection(); } } private function establish_cirrus_connection():void { s_c = new CirrusSocket(); s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void { puts("Cirrus: connected with id " + s_c.id + "."); if (proxy_mode) { start_proxy_pair(); s_c.send_hello(client_id); } else { establish_facilitator_connection(); } }); s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void { puts("Error: failed to connect to Cirrus."); }); s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void { puts("Cirrus: closed connection."); }); s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void { puts("Cirrus: received hello from peer " + e.peer); /* don't bother if we already have a proxy going */ if (p_p != null && p_p.connected) { return; } /* if we're in proxy mode, we should have already set up a proxy pair */ if (!proxy_mode) { relay_addr = DEFAULT_TOR_CLIENT_ADDR; proxy_pair_factory = rtmfp_proxy_pair_factory; start_proxy_pair(); s_c.send_hello(e.peer); } else if (!debug_mode && badge != null) { badge.total_proxy_pairs++; badge.num_proxy_pairs++; } p_p.client = {peer: e.peer, stream: e.stream}; }); s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY); } private function establish_facilitator_connection():void { s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port); s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void { puts("Facilitator: connect failed."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); if (proxy_mode) { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void { var client_addr:Object = parse_addr_spec(e.client); relay_addr = parse_addr_spec(e.relay); if (client_addr == null) { puts("Facilitator: got registration " + e.client); proxy_pair_factory = rtmfp_proxy_pair_factory; if (s_c == null || !s_c.connected) { client_id = e.client; establish_cirrus_connection(); } else { start_proxy_pair(); s_c.send_hello(e.client); } } else { proxy_pair_factory = tcp_proxy_pair_factory; start_proxy_pair(); p_p.client = client_addr; } }); s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void { puts("Facilitator: no registrations available."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); puts("Facilitator: getting registration."); s_f.get_registration(); } else { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void { puts("Facilitator: registration failed."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); puts("Facilitator: posting registration."); s_f.post_registration(s_c.id); } } private function start_proxy_pair():void { p_p = proxy_pair_factory(); p_p.addEventListener(Event.CONNECT, function (e:Event):void { puts("ProxyPair: connected!"); }); p_p.addEventListener(Event.CLOSE, function (e:Event):void { puts("ProxyPair: connection closed."); p_p = null; if (proxy_mode && !debug_mode && badge != null) { badge.num_proxy_pairs--; } establish_facilitator_connection(); }); p_p.relay = relay_addr; } private function rtmfp_proxy_pair_factory():ProxyPair { return new RTMFPProxyPair(this, s_c, s_c.local_stream_name); } // currently is the same as TCPProxyPair // could be interesting to see how this works // can't imagine it will work terribly well... private function sqs_proxy_pair_factory():ProxyPair { return new SQSProxyPair(this); } private function tcp_proxy_pair_factory():ProxyPair { return new TCPProxyPair(this); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextField; import flash.text.TextFormat; class InternetFreedomBadge { private var ui:swfcat; private var _num_proxy_pairs:uint; private var _total_proxy_pairs:uint; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function InternetFreedomBadge(ui:swfcat) { this.ui = ui; _num_proxy_pairs = 0; _total_proxy_pairs = 0; /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; /* Update the client counter on badge. */ update_client_count(); } public function display():void { ui.addChild(new BadgeImage()); /* Tried unsuccessfully to add counter to badge. */ /* For now, need two addChilds :( */ ui.addChild(tot_client_count_tf); ui.addChild(cur_client_count_tf); } public function get num_proxy_pairs():uint { return _num_proxy_pairs; } public function set num_proxy_pairs(amount:uint):void { _num_proxy_pairs = amount; update_client_count(); } public function get total_proxy_pairs():uint { return _total_proxy_pairs; } public function set total_proxy_pairs(amount:uint):void { _total_proxy_pairs = amount; /* note: doesn't update, so be sure to update this before you update num_proxy_pairs! */ } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } }
Rename DEFAULT_FAC_POLL_INTERVAL to FACILITATOR_POLL_INTERVAL.
Rename DEFAULT_FAC_POLL_INTERVAL to FACILITATOR_POLL_INTERVAL.
ActionScript
mit
infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy
c61ff1b2470396bc616a111e6893f298e4853ec3
kdp3Lib/src/com/kaltura/kdpfl/view/controls/ScrubberMediator.as
kdp3Lib/src/com/kaltura/kdpfl/view/controls/ScrubberMediator.as
/** * ScrubberMediator * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @author Dan X Bacon baconoppenheim.com */ package com.kaltura.kdpfl.view.controls { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.vo.KalturaLiveStreamEntry; import com.kaltura.vo.KalturaPlayableEntry; import flash.events.Event; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; /** * Mediator for the scrubber component of the KDP. * @author Hila * */ public class ScrubberMediator extends Mediator { public static const NAME:String = "scrubberMediator"; protected static const STATE_READY:String = "ready"; protected static const STATE_NOT_READY:String = "notReady"; protected static const STATE_PLAYING:String = "playing"; protected static const STATE_PAUSED:String = "paused"; protected static const STATE_SEEKING:String = "seeking"; private var _state:String = STATE_NOT_READY; private var _prevState:String = STATE_NOT_READY; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _flashvars:Object; private var _isLiveRtmp:Boolean=false; //private var _loadIndicatorX : Number; public function ScrubberMediator( viewComponent:Object=null ) { super( NAME, viewComponent ); //if () scrubber.enabled = false; var configProxy : ConfigProxy = facade.retrieveProxy( ConfigProxy.NAME ) as ConfigProxy; _flashvars = configProxy.vo.flashvars; scrubber.addEventListener( KScrubber.EVENT_SEEK, onSeek, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_SEEK_START, onSeekStart, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_SEEK_END, onSeekEnd, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_DRAG, onStartDrag, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_DRAG_END, onEndDrag, false, 0, true ); } /** * Event handler for the Scubber dragging event. * @param evt * */ private function onStartDrag( evt:Event ):void { sendNotification( NotificationType.SCRUBBER_DRAG_START ); } /** * Event listener for the Scrubber_drag_stop event. * @param evt * */ private function onEndDrag( evt:Event ):void { sendNotification( NotificationType.SCRUBBER_DRAG_END); } private function onSeekStart( evt:Event ):void { //sendNotification( NotificationType.PLAYER_SEEK_START ); _prevState = _state; _state = STATE_SEEKING; //sendNotification( NotificationType.DO_PAUSE ); } /** * Handler for the <code> KScrubber.EVENT_SEEK_START</code> event. * @param evt - event of type KScrubber.EVENT_SEEK_STAR * */ private function onSeek( evt:Event ):void { var seekPosition:Number = scrubber.getPosition(); sendNotification( NotificationType.DO_SEEK, seekPosition ); } /** * Handler for the <code> KScrubber.EVENT_SEEK_END</code> event. * @param evt - event of type KScrubber.EVENT_SEEK_END * */ private function onSeekEnd( evt:Event ):void { //sendNotification( NotificationType.PLAYER_SEEK_END ); /*if( _prevState == STATE_PLAYING ) { //trace( "DO_PLAY" ); sendNotification( NotificationType.DO_PLAY ); _prevState = STATE_PLAYING; } */ } override public function handleNotification( note:INotification ):void { switch( note.getName() ) { case NotificationType.KDP_READY: _state = STATE_READY; break; case NotificationType.PLAYER_PLAYED: _state = STATE_PLAYING; break; case NotificationType.PLAYER_PAUSED: _state = STATE_PAUSED; break; case NotificationType.PLAYER_UPDATE_PLAYHEAD: var position:Number = note.getBody() as Number; scrubber.setPosition( position ); break; case NotificationType.DURATION_CHANGE: var duration:Number = note.getBody().newValue; scrubber.duration = duration; break; case NotificationType.BYTES_TOTAL_CHANGE: _bytesTotal = note.getBody().newValue ; break; case NotificationType.BYTES_DOWNLOADED_CHANGE: _bytesLoaded = note.getBody().newValue; var loadProgress:Number = _bytesLoaded/_bytesTotal; scrubber.setLoadProgress( loadProgress ); break; case NotificationType.INTELLI_SEEK: var startLoadFrom : Number = note.getBody().intelliseekTo; var percentIntelli : Number = startLoadFrom/scrubber.duration; scrubber.loadIndicatorX = percentIntelli * scrubber.width; scrubber.indicatorWidth = scrubber.width - scrubber.loadIndicatorX; break; case NotificationType.CHANGE_MEDIA: scrubber.loadIndicatorX = 0; break; case NotificationType.ENTRY_READY: var entry:object = note.getBody(); if (!entry is KalturaLiveStreamEntry) scrubber.duration = entry is KalturaPlayableEntry ? (entry as KalturaPlayableEntry).duration : 0; break; case NotificationType.POST_SEQUENCE_COMPLETE: //tell the scrubber that it should be drawn as progress complete //fix a bug where calling enableGUI reset the scrubber position to the start scrubber.progressComplete = true; break; } } override public function listNotificationInterests():Array { return [ NotificationType.KDP_READY, NotificationType.PLAYER_PLAYED, NotificationType.PLAYER_PAUSED, NotificationType.PLAYER_UPDATE_PLAYHEAD, NotificationType.DURATION_CHANGE, NotificationType.BYTES_TOTAL_CHANGE, NotificationType.BYTES_DOWNLOADED_CHANGE, NotificationType.INTELLI_SEEK, NotificationType.CHANGE_MEDIA, NotificationType.ENTRY_READY, NotificationType.POST_SEQUENCE_COMPLETE ]; } public function get scrubber():KScrubber { return( viewComponent as KScrubber ); } } }
/** * ScrubberMediator * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @author Dan X Bacon baconoppenheim.com */ package com.kaltura.kdpfl.view.controls { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.vo.KalturaLiveStreamEntry; import com.kaltura.vo.KalturaPlayableEntry; import flash.events.Event; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; /** * Mediator for the scrubber component of the KDP. * @author Hila * */ public class ScrubberMediator extends Mediator { public static const NAME:String = "scrubberMediator"; protected static const STATE_READY:String = "ready"; protected static const STATE_NOT_READY:String = "notReady"; protected static const STATE_PLAYING:String = "playing"; protected static const STATE_PAUSED:String = "paused"; protected static const STATE_SEEKING:String = "seeking"; private var _state:String = STATE_NOT_READY; private var _prevState:String = STATE_NOT_READY; private var _bytesLoaded:Number = 0; private var _bytesTotal:Number = 0; private var _flashvars:Object; private var _isLiveRtmp:Boolean=false; //private var _loadIndicatorX : Number; public function ScrubberMediator( viewComponent:Object=null ) { super( NAME, viewComponent ); //if () scrubber.enabled = false; var configProxy : ConfigProxy = facade.retrieveProxy( ConfigProxy.NAME ) as ConfigProxy; _flashvars = configProxy.vo.flashvars; scrubber.addEventListener( KScrubber.EVENT_SEEK, onSeek, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_SEEK_START, onSeekStart, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_SEEK_END, onSeekEnd, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_DRAG, onStartDrag, false, 0, true ); scrubber.addEventListener( KScrubber.EVENT_DRAG_END, onEndDrag, false, 0, true ); } /** * Event handler for the Scubber dragging event. * @param evt * */ private function onStartDrag( evt:Event ):void { sendNotification( NotificationType.SCRUBBER_DRAG_START ); } /** * Event listener for the Scrubber_drag_stop event. * @param evt * */ private function onEndDrag( evt:Event ):void { sendNotification( NotificationType.SCRUBBER_DRAG_END); } private function onSeekStart( evt:Event ):void { //sendNotification( NotificationType.PLAYER_SEEK_START ); _prevState = _state; _state = STATE_SEEKING; //sendNotification( NotificationType.DO_PAUSE ); } /** * Handler for the <code> KScrubber.EVENT_SEEK_START</code> event. * @param evt - event of type KScrubber.EVENT_SEEK_STAR * */ private function onSeek( evt:Event ):void { var seekPosition:Number = scrubber.getPosition(); sendNotification( NotificationType.DO_SEEK, seekPosition ); } /** * Handler for the <code> KScrubber.EVENT_SEEK_END</code> event. * @param evt - event of type KScrubber.EVENT_SEEK_END * */ private function onSeekEnd( evt:Event ):void { //sendNotification( NotificationType.PLAYER_SEEK_END ); /*if( _prevState == STATE_PLAYING ) { //trace( "DO_PLAY" ); sendNotification( NotificationType.DO_PLAY ); _prevState = STATE_PLAYING; } */ } override public function handleNotification( note:INotification ):void { switch( note.getName() ) { case NotificationType.KDP_READY: _state = STATE_READY; break; case NotificationType.PLAYER_PLAYED: _state = STATE_PLAYING; break; case NotificationType.PLAYER_PAUSED: _state = STATE_PAUSED; break; case NotificationType.PLAYER_UPDATE_PLAYHEAD: var position:Number = note.getBody() as Number; scrubber.setPosition( position ); break; case NotificationType.DURATION_CHANGE: var duration:Number = note.getBody().newValue; scrubber.duration = duration; break; case NotificationType.BYTES_TOTAL_CHANGE: _bytesTotal = note.getBody().newValue ; break; case NotificationType.BYTES_DOWNLOADED_CHANGE: _bytesLoaded = note.getBody().newValue; var loadProgress:Number = _bytesLoaded/_bytesTotal; scrubber.setLoadProgress( loadProgress ); break; case NotificationType.INTELLI_SEEK: var startLoadFrom : Number = note.getBody().intelliseekTo; var percentIntelli : Number = startLoadFrom/scrubber.duration; scrubber.loadIndicatorX = percentIntelli * scrubber.width; scrubber.indicatorWidth = scrubber.width - scrubber.loadIndicatorX; break; case NotificationType.CHANGE_MEDIA: scrubber.loadIndicatorX = 0; break; case NotificationType.ENTRY_READY: var entry:object = note.getBody(); if (!(entry is KalturaLiveStreamEntry)) scrubber.duration = entry is KalturaPlayableEntry ? (entry as KalturaPlayableEntry).duration : 0; break; case NotificationType.POST_SEQUENCE_COMPLETE: //tell the scrubber that it should be drawn as progress complete //fix a bug where calling enableGUI reset the scrubber position to the start scrubber.progressComplete = true; break; } } override public function listNotificationInterests():Array { return [ NotificationType.KDP_READY, NotificationType.PLAYER_PLAYED, NotificationType.PLAYER_PAUSED, NotificationType.PLAYER_UPDATE_PLAYHEAD, NotificationType.DURATION_CHANGE, NotificationType.BYTES_TOTAL_CHANGE, NotificationType.BYTES_DOWNLOADED_CHANGE, NotificationType.INTELLI_SEEK, NotificationType.CHANGE_MEDIA, NotificationType.ENTRY_READY, NotificationType.POST_SEQUENCE_COMPLETE ]; } public function get scrubber():KScrubber { return( viewComponent as KScrubber ); } } }
fix scrubber initial duration
qnd: fix scrubber initial duration git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@92658 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
50574375e3fadf69427c29467fbed4d881a3f6f3
MicrophoneMain.as
MicrophoneMain.as
package { import flash.display.Sprite; import flash.events.Event; import flash.events.SampleDataEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; import flash.system.Security; /** * Audio main. */ public class MicrophoneMain extends Sprite { private var ns:String; private var debug:Boolean; private var mic:Microphone; private var frameBuffer:Array; /** * Constructor */ public function MicrophoneMain() { if (!ExternalInterface.available) { throw new Error("ExternalInterface not available"); } ns = loaderInfo.parameters["namespace"] || getQualifiedClassName(this); debug = false; Security.allowDomain("*"); Security.allowInsecureDomain("*"); frameBuffer = []; /** * Javascript can call these */ ExternalInterface.addCallback("__initialize", initialize); ExternalInterface.addCallback("__enable", enable); ExternalInterface.addCallback("__disable", disable); ExternalInterface.addCallback("__receiveFrames", receiveFrames); ExternalInterface.addCallback("__setDebug", setDebug); ExternalInterface.addCallback("__test", test); invoke("__onFlashInitialized"); } private function initialize():void { if (Microphone.names.length == 0) { invoke("__onLog", "No microphones detected."); return; } mic = Microphone.getMicrophone(); mic.gain = 100; mic.rate = 44; } private function enable():void { mic.addEventListener(SampleDataEvent.SAMPLE_DATA, handleSampleData); } private function disable():void { mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, handleSampleData); var frame:ByteArray = frameBuffer.shift(); while (frame) { frame.clear(); frame = frameBuffer.shift(); } } private function encodePCM(data:ByteArray):String { var samples:ByteArray = new ByteArray(); data.position = 0; while (data.bytesAvailable) { var val:int = (1 + data.readFloat()) * 27647; if (val == 0 || val == 92 || val == 8232 || val == 8233) { val += 2; } samples.writeUTFBytes(String.fromCharCode(val)); } return String(samples); } private function receiveFrames():String { var samples:Array = []; var frame:ByteArray = frameBuffer.shift(); while (frame) { samples.push(encodePCM(frame)); frame.clear(); frame = frameBuffer.shift(); } return samples.join(""); } private function handleSampleData(event:SampleDataEvent):void { var frame:ByteArray = new ByteArray(); frame.writeBytes(event.data, 0, event.data.length); frameBuffer.push(frame); invoke("__onQueuedSamples", frameBuffer.length); } private function setDebug(val:Boolean):void { invoke("__onLog", "setDebug"); ExternalInterface.marshallExceptions = val; debug = val; } /** * Conveniently invoke a function in Javascript. * * @param method String The method to call. */ private function invoke(method:String, ...params):void { params = params || []; ExternalInterface.call.apply(ExternalInterface, [ns + "." + method].concat(params)); } } }
package { import flash.display.Sprite; import flash.events.Event; import flash.events.SampleDataEvent; import flash.external.ExternalInterface; import flash.media.Microphone; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.getQualifiedClassName; import flash.system.Security; /** * Audio main. */ public class MicrophoneMain extends Sprite { private var ns:String; private var debug:Boolean; private var mic:Microphone; private var frameBuffer:Array; /** * Constructor */ public function MicrophoneMain() { if (!ExternalInterface.available) { throw new Error("ExternalInterface not available"); } ns = loaderInfo.parameters["namespace"] || getQualifiedClassName(this); debug = false; Security.allowDomain("*"); Security.allowInsecureDomain("*"); frameBuffer = []; /** * Javascript can call these */ ExternalInterface.addCallback("__initialize", initialize); ExternalInterface.addCallback("__enable", enable); ExternalInterface.addCallback("__disable", disable); ExternalInterface.addCallback("__receiveFrames", receiveFrames); ExternalInterface.addCallback("__setDebug", setDebug); invoke("__onFlashInitialized"); } private function initialize():void { if (Microphone.names.length == 0) { invoke("__onLog", "No microphones detected."); return; } mic = Microphone.getMicrophone(); mic.gain = 100; mic.rate = 44; } private function enable():void { mic.addEventListener(SampleDataEvent.SAMPLE_DATA, handleSampleData); } private function disable():void { mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, handleSampleData); var frame:ByteArray = frameBuffer.shift(); while (frame) { frame.clear(); frame = frameBuffer.shift(); } } private function encodePCM(data:ByteArray):String { var samples:ByteArray = new ByteArray(); data.position = 0; while (data.bytesAvailable) { var val:int = (1 + data.readFloat()) * 27647; if (val == 0 || val == 92 || val == 8232 || val == 8233) { val += 2; } samples.writeUTFBytes(String.fromCharCode(val)); } return String(samples); } private function receiveFrames():String { var samples:Array = []; var frame:ByteArray = frameBuffer.shift(); while (frame) { samples.push(encodePCM(frame)); frame.clear(); frame = frameBuffer.shift(); } return samples.join(""); } private function handleSampleData(event:SampleDataEvent):void { var frame:ByteArray = new ByteArray(); frame.writeBytes(event.data, 0, event.data.length); frameBuffer.push(frame); invoke("__onQueuedSamples", frameBuffer.length); } private function setDebug(val:Boolean):void { invoke("__onLog", "setDebug"); ExternalInterface.marshallExceptions = val; debug = val; } /** * Conveniently invoke a function in Javascript. * * @param method String The method to call. */ private function invoke(method:String, ...params):void { params = params || []; ExternalInterface.call.apply(ExternalInterface, [ns + "." + method].concat(params)); } } }
Remove test external interface decl
Remove test external interface decl
ActionScript
bsd-3-clause
luciferous/Microphone
777694b653eed1118dd658b3aa2c92ff85fad465
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
package aerys.minko.scene.controller.debug { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.primitive.LineGeometry; import aerys.minko.render.geometry.stream.iterator.TriangleIterator; import aerys.minko.render.geometry.stream.iterator.TriangleReference; import aerys.minko.render.material.line.LineMaterial; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; public final class WireframeDebugController extends AbstractController { private static var _wireframeMaterial : LineMaterial; private var _targetToWireframe : Dictionary = new Dictionary(); private var _geometryToMesh : Dictionary = new Dictionary(); private var _visible : Boolean = true; public function get material() : LineMaterial { return _wireframeMaterial || (_wireframeMaterial = new LineMaterial({diffuseColor : 0xffffffff, lineThickness : 1.})); } public function set visible(value : Boolean) : void { _visible = value; for each (var wireframe : Mesh in _targetToWireframe) wireframe.visible = value; } public function get visible() : Boolean { return _visible; } public function WireframeDebugController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.scene) addedHandler(target, target.parent); else target.added.add(addedHandler); target.removed.add(removedHandler); } private function addedHandler(target : Mesh, ancestor : Group) : void { if (!target.scene || target.geometry == null) return ; var triangles : TriangleIterator = new TriangleIterator( target.geometry.getVertexStream(), target.geometry.indexStream ); var linesGeom : LineGeometry = new LineGeometry(); for each (var triangle : TriangleReference in triangles) { linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z) .lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z) .lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z) .lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z); } var lines : Mesh = new Mesh(linesGeom, this.material); lines.visible = _visible; _targetToWireframe[target] = lines; target.localToWorldTransformChanged.add(updateTransform); updateTransform(target, target.getLocalToWorldTransform()); target.scene.addChild(lines); } private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void { var lineMesh : Mesh = _targetToWireframe[child]; if (lineMesh == null) child.localToWorldTransformChanged.remove(updateTransform); else lineMesh.transform.copyFrom(childLocalToWorld); } private function removeWireframes(target : Mesh) : void { if (_targetToWireframe[target]) _targetToWireframe[target].parent = null; _targetToWireframe[target] = null; } private function targetRemovedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.added.hasCallback(addedHandler)) target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.localToWorldTransformChanged.hasCallback(updateTransform)) target.localToWorldTransformChanged.remove(updateTransform); removeWireframes(target); } private function removedHandler(target : Mesh, ancestor : Group) : void { removeWireframes(target); } override public function clone():AbstractController { return null; } } }
package aerys.minko.scene.controller.debug { import aerys.minko.render.geometry.Geometry; import aerys.minko.render.geometry.primitive.LineGeometry; import aerys.minko.render.geometry.stream.iterator.TriangleIterator; import aerys.minko.render.geometry.stream.iterator.TriangleReference; import aerys.minko.render.material.line.LineMaterial; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; public final class WireframeDebugController extends AbstractController { private static var _wireframeMaterial : LineMaterial; private var _targetToWireframe : Dictionary = new Dictionary(); private var _geometryToMesh : Dictionary = new Dictionary(); private var _visible : Boolean = true; public function get material() : LineMaterial { return _wireframeMaterial || (_wireframeMaterial = new LineMaterial({diffuseColor : 0x509dc7ff, lineThickness : 1.})); } public function set visible(value : Boolean) : void { _visible = value; for each (var wireframe : Mesh in _targetToWireframe) wireframe.visible = value; } public function get visible() : Boolean { return _visible; } public function WireframeDebugController() { super(Mesh); initialize(); } private function initialize() : void { targetAdded.add(targetAddedHandler); targetRemoved.add(targetRemovedHandler); } private function targetAddedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.scene) addedHandler(target, target.parent); else target.added.add(addedHandler); target.removed.add(removedHandler); } private function addedHandler(target : Mesh, ancestor : Group) : void { if (!target.scene || target.geometry == null) return ; var triangles : TriangleIterator = new TriangleIterator( target.geometry.getVertexStream(), target.geometry.indexStream ); var linesGeom : LineGeometry = new LineGeometry(); for each (var triangle : TriangleReference in triangles) { linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z) .lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z) .lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z) .lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z); } var lines : Mesh = new Mesh(linesGeom, this.material); lines.visible = _visible; _targetToWireframe[target] = lines; target.localToWorldTransformChanged.add(updateTransform); updateTransform(target, target.getLocalToWorldTransform()); target.scene.addChild(lines); } private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void { var lineMesh : Mesh = _targetToWireframe[child]; if (lineMesh == null) child.localToWorldTransformChanged.remove(updateTransform); else lineMesh.transform.copyFrom(childLocalToWorld); } private function removeWireframes(target : Mesh) : void { if (_targetToWireframe[target]) _targetToWireframe[target].parent = null; _targetToWireframe[target] = null; } private function targetRemovedHandler(ctrl : WireframeDebugController, target : Mesh) : void { if (target.added.hasCallback(addedHandler)) target.added.remove(addedHandler); target.removed.remove(removedHandler); if (target.localToWorldTransformChanged.hasCallback(updateTransform)) target.localToWorldTransformChanged.remove(updateTransform); removeWireframes(target); } private function removedHandler(target : Mesh, ancestor : Group) : void { removeWireframes(target); } override public function clone():AbstractController { return null; } } }
Change color of wireframe debug controller
Change color of wireframe debug controller
ActionScript
mit
aerys/minko-as3
c260132ab91a5bcd4ccb740921c6ba98074e4fe8
as3/com/netease/protobuf/ReadUtils.as
as3/com/netease/protobuf/ReadUtils.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // Copyright (c) 2012 , Yang Bo. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.errors.* import flash.utils.* /** * @private */ public final class ReadUtils { public static function skip(input:IDataInput, wireType:uint):void { switch (wireType) { case WireType.VARINT: while (input.readUnsignedByte() > 0x80) {} break case WireType.FIXED_64_BIT: input.readInt() input.readInt() break case WireType.LENGTH_DELIMITED: for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) { input.readByte() } break case WireType.FIXED_32_BIT: input.readInt() break default: throw new IOError("Invalid wire type: " + wireType) } } public static function read$TYPE_DOUBLE(input:IDataInput):Number { return input.readDouble() } public static function read$TYPE_FLOAT(input:IDataInput):Number { return input.readFloat() } public static function read$TYPE_INT64(input:IDataInput):Int64 { const result:Int64 = new Int64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_UINT64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_INT32(input:IDataInput):int { return int(read$TYPE_UINT32(input)) } public static function read$TYPE_FIXED64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 result.low = input.readUnsignedInt() result.high = input.readUnsignedInt() return result } public static function read$TYPE_FIXED32(input:IDataInput):uint { return input.readUnsignedInt() } public static function read$TYPE_BOOL(input:IDataInput):Boolean { return read$TYPE_UINT32(input) != 0 } public static function read$TYPE_STRING(input:IDataInput):String { const length:uint = read$TYPE_UINT32(input) return input.readUTFBytes(length) } public static function read$TYPE_BYTES(input:IDataInput):ByteArray { const result:ByteArray = new ByteArray const length:uint = read$TYPE_UINT32(input) if (length > 0) { input.readBytes(result, 0, length) } return result } public static function read$TYPE_UINT32(input:IDataInput):uint { var result:uint = 0 for (var i:uint = 0;; i += 7) { const b:uint = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result |= ((b & 0x7f) << i) } else { result |= (b << i) break } } else { while (input.readUnsignedByte() >= 0x80) {} break } } return result } public static function read$TYPE_ENUM(input:IDataInput):int { return read$TYPE_INT32(input) } public static function read$TYPE_SFIXED32(input:IDataInput):int { return input.readInt() } public static function read$TYPE_SFIXED64(input:IDataInput):Int64 { const result:Int64 = new Int64 result.low = input.readUnsignedInt() result.high = input.readInt() return result } public static function read$TYPE_SINT32(input:IDataInput):int { return ZigZag.decode32(read$TYPE_UINT32(input)) } public static function read$TYPE_SINT64(input:IDataInput):Int64 { const result:Int64 = read$TYPE_INT64(input) const low:uint = result.low const high:uint = result.high result.low = ZigZag.decode64low(low, high) result.high = ZigZag.decode64high(low, high) return result } public static function read$TYPE_MESSAGE(input:IDataInput, message:Message):Message { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length message.used_by_generated_code::readFromSlice(input, bytesAfterSlice) if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid nested message") } return message } public static function readPackedRepeated(input:IDataInput, readFuntion:Function, value:Array):void { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length while (input.bytesAvailable > bytesAfterSlice) { value.push(readFuntion(input)) } if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid packed repeated data") } } } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , NetEase.com,Inc. All rights reserved. // Copyright (c) 2012 , Yang Bo. All rights reserved. // // Author: Yang Bo ([email protected]) // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.errors.* import flash.utils.* /** * @private */ public final class ReadUtils { public static function skip(input:IDataInput, wireType:uint):void { switch (wireType) { case WireType.VARINT: while (input.readUnsignedByte() >= 0x80) {} break case WireType.FIXED_64_BIT: input.readInt() input.readInt() break case WireType.LENGTH_DELIMITED: for (var i:uint = read$TYPE_UINT32(input); i != 0; i--) { input.readByte() } break case WireType.FIXED_32_BIT: input.readInt() break default: throw new IOError("Invalid wire type: " + wireType) } } public static function read$TYPE_DOUBLE(input:IDataInput):Number { return input.readDouble() } public static function read$TYPE_FLOAT(input:IDataInput):Number { return input.readFloat() } public static function read$TYPE_INT64(input:IDataInput):Int64 { const result:Int64 = new Int64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_UINT64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 var b:uint var i:uint = 0 for (;; i += 7) { b = input.readUnsignedByte() if (i == 28) { break } else { if (b >= 0x80) { result.low |= ((b & 0x7f) << i) } else { result.low |= (b << i) return result } } } if (b >= 0x80) { b &= 0x7f result.low |= (b << i) result.high = b >>> 4 } else { result.low |= (b << i) result.high = b >>> 4 return result } for (i = 3;; i += 7) { b = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result.high |= ((b & 0x7f) << i) } else { result.high |= (b << i) break } } } return result } public static function read$TYPE_INT32(input:IDataInput):int { return int(read$TYPE_UINT32(input)) } public static function read$TYPE_FIXED64(input:IDataInput):UInt64 { const result:UInt64 = new UInt64 result.low = input.readUnsignedInt() result.high = input.readUnsignedInt() return result } public static function read$TYPE_FIXED32(input:IDataInput):uint { return input.readUnsignedInt() } public static function read$TYPE_BOOL(input:IDataInput):Boolean { return read$TYPE_UINT32(input) != 0 } public static function read$TYPE_STRING(input:IDataInput):String { const length:uint = read$TYPE_UINT32(input) return input.readUTFBytes(length) } public static function read$TYPE_BYTES(input:IDataInput):ByteArray { const result:ByteArray = new ByteArray const length:uint = read$TYPE_UINT32(input) if (length > 0) { input.readBytes(result, 0, length) } return result } public static function read$TYPE_UINT32(input:IDataInput):uint { var result:uint = 0 for (var i:uint = 0;; i += 7) { const b:uint = input.readUnsignedByte() if (i < 32) { if (b >= 0x80) { result |= ((b & 0x7f) << i) } else { result |= (b << i) break } } else { while (input.readUnsignedByte() >= 0x80) {} break } } return result } public static function read$TYPE_ENUM(input:IDataInput):int { return read$TYPE_INT32(input) } public static function read$TYPE_SFIXED32(input:IDataInput):int { return input.readInt() } public static function read$TYPE_SFIXED64(input:IDataInput):Int64 { const result:Int64 = new Int64 result.low = input.readUnsignedInt() result.high = input.readInt() return result } public static function read$TYPE_SINT32(input:IDataInput):int { return ZigZag.decode32(read$TYPE_UINT32(input)) } public static function read$TYPE_SINT64(input:IDataInput):Int64 { const result:Int64 = read$TYPE_INT64(input) const low:uint = result.low const high:uint = result.high result.low = ZigZag.decode64low(low, high) result.high = ZigZag.decode64high(low, high) return result } public static function read$TYPE_MESSAGE(input:IDataInput, message:Message):Message { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length message.used_by_generated_code::readFromSlice(input, bytesAfterSlice) if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid nested message") } return message } public static function readPackedRepeated(input:IDataInput, readFuntion:Function, value:Array):void { const length:uint = read$TYPE_UINT32(input) if (input.bytesAvailable < length) { throw new IOError("Invalid message length: " + length) } const bytesAfterSlice:uint = input.bytesAvailable - length while (input.bytesAvailable > bytesAfterSlice) { value.push(readFuntion(input)) } if (input.bytesAvailable != bytesAfterSlice) { throw new IOError("Invalid packed repeated data") } } } }
Fix #35
Fix #35
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
bdda60fe7b2fd8e64721f63251c14ba8671f51de
as3/xobjas3/src/com/rpath/xobj/FilterTerm.as
as3/xobjas3/src/com/rpath/xobj/FilterTerm.as
/* # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program 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 MIT License for full details. # */ package com.rpath.xobj { [RemoteClass] [Bindable] public class FilterTerm { public function FilterTerm(field:String, value:String, operator:String = EQUAL) { super(); this.field = field; this.operator = operator; this.value = value; } /** * The field/property to filter on (LHS) */ public var field:String; /** * The logical operator to apply (see static consts below) */ public var operator:String; /** * The value to test the field against (RHS) */ public var value:String; public static const EQUAL:String = "EQUAL"; public static const NOT_EQUAL:String = "NOT_EQUAL"; public static const IS_NULL:String = "IS_NULL"; public static const IS_NOT_NULL:String = "IS_NOT_NULL"; public static const LESS_THAN:String = "LESS_THAN"; public static const LESS_THAN_OR_EQUAL:String = "LESS_THAN_OR_EQUAL"; public static const GREATER_THAN:String = "GREATER_THAN"; public static const GREATER_THAN_OR_EQUAL:String = "GREATER_THAN_OR_EQUAL"; public static const LIKE:String = "LIKE"; public static const NOT_LIKE:String = "NOT_LIKE"; public static const IN:String = "IN"; public static const NOT_IN:String = "NOT_IN"; public static const MATCHING:String = "MATCHING"; public static const NOT_MATCHING:String = "NOT_MATCHING"; public static const YES:String = "YES"; public static const NO:String = "NO"; } }
/* # Copyright (c) 2008-2010 rPath, Inc. # # This program is distributed under the terms of the MIT License as found # in a file called LICENSE. If it is not present, the license # is always available at http://www.opensource.org/licenses/mit-license.php. # # This program 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 MIT License for full details. # */ package com.rpath.xobj { [RemoteClass] [Bindable] public class FilterTerm { public function FilterTerm(field:String, value:String, operator:String = EQUAL) { super(); this.field = field; this.operator = operator; this.value = value; } /** * The field/property to filter on (LHS) */ public var field:String; /** * The logical operator to apply (see static consts below) */ public var operator:String; /** * The value to test the field against (RHS) */ public var value:String; public static const EQUAL:String = "EQUAL"; public static const NOT_EQUAL:String = "NOT_EQUAL"; public static const IS_NULL:String = "IS_NULL"; public static const IS_NOT_NULL:String = "IS_NOT_NULL"; public static const LESS_THAN:String = "LESS_THAN"; public static const LESS_THAN_OR_EQUAL:String = "LESS_THAN_OR_EQUAL"; public static const GREATER_THAN:String = "GREATER_THAN"; public static const GREATER_THAN_OR_EQUAL:String = "GREATER_THAN_OR_EQUAL"; public static const LIKE:String = "LIKE"; public static const NOT_LIKE:String = "NOT_LIKE"; public static const IN:String = "IN"; public static const NOT_IN:String = "NOT_IN"; /* NOT YET IMPLEMENTED public static const MATCHING:String = "MATCHING"; public static const NOT_MATCHING:String = "NOT_MATCHING"; */ public static const YES:String = "YES"; public static const NO:String = "NO"; } }
Remove MATCHING operator for now per RBL-8583
Remove MATCHING operator for now per RBL-8583
ActionScript
apache-2.0
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
8eb2120f5dc4ea7a3bdc2b2638d77ff953ce20e9
src/com/benoitfreslon/layoutmanager/LayoutLoader.as
src/com/benoitfreslon/layoutmanager/LayoutLoader.as
package com.benoitfreslon.layoutmanager { import flash.display.MovieClip; import flash.events.Event; import flash.system.Capabilities; import flash.utils.getDefinitionByName; import starling.display.Button; import starling.display.ButtonExtended; import starling.display.DisplayObject; import starling.display.DisplayObjectContainer; import starling.display.Image; import starling.display.Quad; import starling.display.Sprite; import starling.text.TextField; import starling.textures.Texture; import starling.utils.AssetManager; /** * Loader of Layout * @version 1.04 * @author Benoît Freslon */ public class LayoutLoader { private var _movieclip : MovieClip; private var _displayObject : DisplayObjectContainer; private var _rootObject : DisplayObjectContainer; private var _assetManager : AssetManager; static public var debug : Boolean = false; private var onLoad : Function = function() : void { }; /** * Loader of Layout class. */ public function LayoutLoader() { super(); debug = Capabilities.isDebugger } /** * Load a layout from a MovieClip added in ActionScript. * Embed a SWC file with all your layouts in your ActionScript 3.0 project and use this lib to load and display your layouts. * * @param displayObject The starling.display.DisplayObject where the layout should be displayed * @param LayoutClass The layout class Embed in the SWC file. * @param assetManager The AssetManager instance where all assets are loaded. * @param callBack The callback function when the layout is loaded and displayed. */ public function loadLayout( rootObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void { if ( debug ) trace( "LayoutLoader: loadLayout" , rootObject , LayoutClass , assetManager , callBack ); _rootObject = rootObject; _displayObject = rootObject; _assetManager = assetManager; _movieclip = new LayoutClass(); _movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded ); if ( onLoad != null ) onLoad = callBack } public function loadLayoutIn( rootObject : DisplayObjectContainer , displayObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void { if ( debug ) trace( "LayoutLoader: loadLayoutIn" , rootObject , displayObject , LayoutClass , assetManager , callBack ); _rootObject = rootObject _displayObject = displayObject; _assetManager = assetManager; _movieclip = new LayoutClass(); _movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded ); if ( onLoad != null ) onLoad = callBack } private function layoutLoaded( e : Event ) : void { if ( debug ) trace( "LayoutLoader: layoutLoaded" ); _movieclip.removeEventListener( Event.ENTER_FRAME , layoutLoaded ); parseMovieClip( _movieclip , _rootObject , _displayObject ); loaded(); } private function parseMovieClip( mc : MovieClip , root : DisplayObjectContainer , container : DisplayObjectContainer ) : void { var child : BFObject; var n : int = mc.numChildren; for ( var i : uint = 0 ; i < n ; ++i ) { child = mc.getChildAt( i ) as BFObject; if ( child ) { if ( child.mainClass ) { var a : Array = [ ButtonExtended ]; var objectClass : Class; if (debug) trace(child.className); if ( child.className ) { objectClass = getDefinitionByName( child.className ) as Class; } else { objectClass = getDefinitionByName( child.mainClass ) as Class; } var obj : DisplayObject; if ( child.mainClass == "starling.display.Image" ) { obj = addImage( objectClass , child as BFImage ); } else if ( child.mainClass == "starling.display.ButtonExtended" ) { obj = addButton( objectClass , child as BFButton ); } else if ( child.mainClass == "starling.text.TextField" ) { obj = addTextField( objectClass , child as BFTextField ); } else if ( child.mainClass == "starling.display.Sprite" ) { obj = addSprite( objectClass , child as BFSprite ); } else { throw new Error( "No mainClass defined in '" + child + "'" ); } if ( child.hasOwnProperty( "params" ) ) { for ( var metatags : String in child.params ) { if ( obj.hasOwnProperty( metatags ) ) obj[ metatags ] = child.params[ metatags ]; } } obj.name = child.name; obj.x = int( child.x ); obj.y = int( child.y ); //obj.scaleX = child.scaleX; //obj.scaleY = child.scaleY; if ( child.flipX ) { obj.scaleX = -1; } if ( child.flipY ) { obj.scaleY = -1; } obj.alpha = child.alpha; obj.rotation = child.rotation; obj.visible = child.isVisible; container.addChild( obj ); if ( obj.hasOwnProperty( "tag" ) ) { obj[ "tag" ] = child.tag; } if ( obj.hasOwnProperty( "userData" ) ) { obj[ "userData" ] = child.userData; } if ( _rootObject.hasOwnProperty( child.name ) ) { _rootObject[ child.name ] = obj as objectClass; } else if ( child.name.split( "__id" ).length == 1 && child.name.split( "instance" ).length == 1 ) { throw new Error( "No public property '" + child.name + "' declared in " + _rootObject ); } } else { //trace( new Error( "No className defined " + child ) ); } } } } private function loaded() : void { _assetManager = null; _displayObject = null; _movieclip = null; _rootObject = null; onLoad(); } private function addImage( objectClass : Class , child : BFImage ) : Image { var tex : Texture = getTexture( child , child.texture , child.width , child.height ) var img : Image = new objectClass( tex ) as Image; img.pivotX = int( img.width * child.pivotX ); img.pivotY = int( img.height * child.pivotY ); return img; } private function addSprite( objectClass : Class , child : BFSprite ) : Sprite { var s : Sprite = new objectClass() as Sprite; parseMovieClip( child as MovieClip , s as DisplayObjectContainer , s as DisplayObjectContainer ); return s; } private function addTextField( objectClass : Class , child : BFTextField ) : TextField { var t : TextField = new objectClass( child.width , child.height , "" ) as TextField; t.autoSize = child.autoSize; t.fontName = child.fontName; t.fontSize = child.fontSize; t.color = child.color; t.hAlign = child.hAlign; t.vAlign = child.vAlign; t.bold = child.bold; t.italic = child.italic; t.border = child.border; t.underline = child.underline; t.pivotX = int( t.width * child.pivotX ); t.pivotY = int( t.height * child.pivotY ); var text : String = child.text; text = text.replace( "\\r" , "\r" ); text = text.replace( "\\n" , "\n" ); text = text.replace( "\\t" , "\t" ); t.text = text; t.width = child.width; t.height = child.height; return t; } // TODO Parse BFButton and addChild objects inside Button private function addButton( objectClass : Class , child : BFButton ) : Button { var bt : Button = new objectClass( getTexture( child , child.upState , child.width , child.height ) ) as Button; bt.fontBold = child.bold; bt.fontColor = child.color; bt.fontName = child.fontName; bt.fontSize = child.fontSize; bt.alphaWhenDisabled = child.alphaWhenDisabled; bt.scaleWhenDown = child.scaleWhenDown; bt.text = child.text; bt.pivotX = int( bt.width * child.pivotX ); bt.pivotY = int( bt.height * child.pivotY ); if ( child.downState ) bt.downState = _assetManager.getTexture( child.downState ); if ( bt.hasOwnProperty( "overState" ) && child.overState ) bt[ "overState" ] = _assetManager.getTexture( child.overState ); if ( bt.hasOwnProperty( "onTouch" ) && _rootObject.hasOwnProperty( child.onTouch ) ) { bt[ "onTouch" ] = _rootObject[ child.onTouch ]; } else if ( bt.hasOwnProperty( "onTouch" ) && child.onTouch != "" && !_rootObject.hasOwnProperty( child.onTouch ) ) { throw new Error( "The public method '" + child.onTouch + "' is not defined in " + _rootObject ) ; } return bt; } private function getTexture( child : BFObject , textureName : String , w : Number , h : Number ) : Texture { if ( textureName == "" ) { //trace( new Error( "No texture defined in '" + child + " - name: "+child.name+"' in "+_displayObject+". Default texture used." ) ); return Texture.empty( w , h ); } else { var tex : Texture = _assetManager.getTexture( textureName ); if ( tex == null ) { trace( new Error( "Texture '" + textureName + "' defined in '" + child + " - name: " + child.name + "' in " + _displayObject + " doesn't exist. Default texture used." )); return Texture.empty( w , h ); } return tex; } } } }
package com.benoitfreslon.layoutmanager { import flash.display.MovieClip; import flash.events.Event; import flash.system.Capabilities; import flash.utils.getDefinitionByName; import starling.display.Button; import starling.display.ButtonExtended; import starling.display.DisplayObject; import starling.display.DisplayObjectContainer; import starling.display.Image; import starling.display.Quad; import starling.display.Sprite; import starling.text.TextField; import starling.textures.Texture; import starling.utils.AssetManager; /** * Loader of Layout * @version 1.04 * @author Benoît Freslon */ public class LayoutLoader { private var _movieclip : MovieClip; private var _displayObject : DisplayObjectContainer; private var _rootObject : DisplayObjectContainer; private var _assetManager : AssetManager; static public var debug : Boolean = false; private var onLoad : Function = function() : void { }; /** * Loader of Layout class. */ public function LayoutLoader() { super(); debug = Capabilities.isDebugger } /** * Load a layout from a MovieClip added in ActionScript. * Embed a SWC file with all your layouts in your ActionScript 3.0 project and use this lib to load and display your layouts. * * @param displayObject The starling.display.DisplayObject where the layout should be displayed * @param LayoutClass The layout class Embed in the SWC file. * @param assetManager The AssetManager instance where all assets are loaded. * @param callBack The callback function when the layout is loaded and displayed. */ public function loadLayout( rootObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void { if ( debug ) trace( "LayoutLoader: loadLayout" , rootObject , LayoutClass , assetManager , callBack ); _rootObject = rootObject; _displayObject = rootObject; _assetManager = assetManager; _movieclip = new LayoutClass(); _movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded ); if ( onLoad != null ) onLoad = callBack } public function loadLayoutIn( rootObject : DisplayObjectContainer , displayObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void { if ( debug ) trace( "LayoutLoader: loadLayoutIn" , rootObject , displayObject , LayoutClass , assetManager , callBack ); _rootObject = rootObject _displayObject = displayObject; _assetManager = assetManager; _movieclip = new LayoutClass(); _movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded ); if ( onLoad != null ) onLoad = callBack } private function layoutLoaded( e : Event ) : void { if ( debug ) trace( "LayoutLoader: layoutLoaded" ); _movieclip.removeEventListener( Event.ENTER_FRAME , layoutLoaded ); parseMovieClip( _movieclip , _rootObject , _displayObject ); loaded(); } private function parseMovieClip( mc : MovieClip , root : DisplayObjectContainer , container : DisplayObjectContainer ) : void { var child : BFObject; var n : int = mc.numChildren; for ( var i : uint = 0 ; i < n ; ++i ) { child = mc.getChildAt( i ) as BFObject; if ( child ) { if ( child.mainClass ) { var a : Array = [ ButtonExtended ]; var objectClass : Class; if (debug) trace("LayoutLoader: child.className",child.className); if ( child.className ) { objectClass = getDefinitionByName( child.className ) as Class; } else { objectClass = getDefinitionByName( child.mainClass ) as Class; } var obj : DisplayObject; if ( child.mainClass == "starling.display.Image" ) { obj = addImage( objectClass , child as BFImage ); } else if ( child.mainClass == "starling.display.ButtonExtended" ) { obj = addButton( objectClass , child as BFButton ); } else if ( child.mainClass == "starling.text.TextField" ) { obj = addTextField( objectClass , child as BFTextField ); } else if ( child.mainClass == "starling.display.Sprite" ) { obj = addSprite( objectClass , child as BFSprite ); } else { throw new Error( "No mainClass defined in '" + child + "'" ); } if ( child.hasOwnProperty( "params" ) ) { for ( var metatags : String in child.params ) { if ( obj.hasOwnProperty( metatags ) ) obj[ metatags ] = child.params[ metatags ]; } } obj.name = child.name; obj.x = int( child.x ); obj.y = int( child.y ); //obj.scaleX = child.scaleX; //obj.scaleY = child.scaleY; if ( child.flipX ) { obj.scaleX = -1; } if ( child.flipY ) { obj.scaleY = -1; } obj.alpha = child.alpha; obj.rotation = child.rotation; obj.visible = child.isVisible; container.addChild( obj ); if ( obj.hasOwnProperty( "tag" ) ) { obj[ "tag" ] = child.tag; } if ( obj.hasOwnProperty( "userData" ) ) { obj[ "userData" ] = child.userData; } if ( _rootObject.hasOwnProperty( child.name ) ) { _rootObject[ child.name ] = obj as objectClass; } else if ( child.name.split( "__id" ).length == 1 && child.name.split( "instance" ).length == 1 ) { throw new Error( "No public property '" + child.name + "' declared in " + _rootObject ); } } else { //trace( new Error( "No className defined " + child ) ); } } } } private function loaded() : void { _assetManager = null; _displayObject = null; _movieclip = null; _rootObject = null; onLoad(); } private function addImage( objectClass : Class , child : BFImage ) : Image { var tex : Texture = getTexture( child , child.texture , child.width , child.height ) var img : Image = new objectClass( tex ) as Image; img.pivotX = int( img.width * child.pivotX ); img.pivotY = int( img.height * child.pivotY ); return img; } private function addSprite( objectClass : Class , child : BFSprite ) : Sprite { var s : Sprite = new objectClass() as Sprite; parseMovieClip( child as MovieClip , s as DisplayObjectContainer , s as DisplayObjectContainer ); return s; } private function addTextField( objectClass : Class , child : BFTextField ) : TextField { var t : TextField = new objectClass( child.width , child.height , "" ) as TextField; t.autoSize = child.autoSize; t.fontName = child.fontName; t.fontSize = child.fontSize; t.color = child.color; t.hAlign = child.hAlign; t.vAlign = child.vAlign; t.bold = child.bold; t.italic = child.italic; t.border = child.border; t.underline = child.underline; t.pivotX = int( t.width * child.pivotX ); t.pivotY = int( t.height * child.pivotY ); var text : String = child.text; text = text.replace( "\\r" , "\r" ); text = text.replace( "\\n" , "\n" ); text = text.replace( "\\t" , "\t" ); t.text = text; t.width = child.width; t.height = child.height; return t; } // TODO Parse BFButton and addChild objects inside Button private function addButton( objectClass : Class , child : BFButton ) : Button { var bt : Button = new objectClass( getTexture( child , child.upState , child.width , child.height ) ) as Button; bt.fontBold = child.bold; bt.fontColor = child.color; bt.fontName = child.fontName; bt.fontSize = child.fontSize; bt.alphaWhenDisabled = child.alphaWhenDisabled; bt.scaleWhenDown = child.scaleWhenDown; bt.text = child.text; bt.pivotX = int( bt.width * child.pivotX ); bt.pivotY = int( bt.height * child.pivotY ); if ( child.downState ) bt.downState = _assetManager.getTexture( child.downState ); if ( bt.hasOwnProperty( "overState" ) && child.overState ) bt[ "overState" ] = _assetManager.getTexture( child.overState ); if ( bt.hasOwnProperty( "onTouch" ) && _rootObject.hasOwnProperty( child.onTouch ) ) { bt[ "onTouch" ] = _rootObject[ child.onTouch ]; } else if ( bt.hasOwnProperty( "onTouch" ) && child.onTouch != "" && !_rootObject.hasOwnProperty( child.onTouch ) ) { throw new Error( "The public method '" + child.onTouch + "' is not defined in " + _rootObject ) ; } return bt; } private function getTexture( child : BFObject , textureName : String , w : Number , h : Number ) : Texture { if ( textureName == "" ) { //trace( new Error( "No texture defined in '" + child + " - name: "+child.name+"' in "+_displayObject+". Default texture used." ) ); return Texture.empty( w , h ); } else { var tex : Texture = _assetManager.getTexture( textureName ); if ( tex == null ) { trace( new Error( "Texture '" + textureName + "' defined in '" + child + " - name: " + child.name + "' in " + _displayObject + " doesn't exist. Default texture used." )); return Texture.empty( w , h ); } return tex; } } } }
Debug message
Debug message
ActionScript
mit
BenoitFreslon/benoitfreslon-layoutmanager
239060e6e2928aaf471b1820f2a715ba3a0891cf
tests/misc/flashtest.as
tests/misc/flashtest.as
package{ import flash.display.Sprite; import flash.net.registerClassAlias; import flash.text.TextField; import flash.utils.ByteArray; import flash.utils.Dictionary; [SWF(width="450", height="400")] public class flashtest extends Sprite { private var tf:TextField; public function flashtest() { tf = new TextField(); tf.width = tf.height = 450; tf.wordWrap = true; addChild(tf); dumpValues(); readValues(); } private function dumpValues():void { tf.text = ""; var b:ByteArray = new ByteArray(); var a:Dictionary = new Dictionary(); a["x"] = a; tf.appendText(a.toString() + "\n"); tf.appendText(a["x"].toString() + "\n"); b.writeObject(a); dumpByteArray(b); } private function readValues():void { /* var data:Array = [ 0x11, 0x07, 0x00, 0x0a, 0x0b, 0x01, 0x07, 0x62, 0x61, 0x72, 0x04, 0x01, 0x01, 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x0a, 0x0b, 0x01, 0x07, 0x62, 0x61, 0x72, 0x04, 0x02, 0x01, 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x06, 0x07, 0x71, 0x75, 0x78, 0x0a, 0x00 ]; */ var data:Array = [ 0x11, 0x03, 0x00, 0x06, 0x03, 0x78, 0x00 ]; var b:ByteArray = createByteArray(data); var o:* = b.readObject(); tf.appendText(o + "\n"); tf.appendText(o.x + "\n"); } private function testExternalizable():void { tf.text = ""; registerClassAlias("Foo", Foo); var b:ByteArray = new ByteArray(); var f:Foo = new Foo("asd"); var g:Foo = new Foo("bar"); var a:Array = [f, f, g]; b.writeObject(a); dumpByteArray(b); b.position = 0; var a2:Array = b.readObject(); tf.appendText((a[0] as Foo).foo); tf.appendText((a[1] as Foo).foo); tf.appendText((a[2] as Foo).foo); } private function dumpByteArray(b:ByteArray):void { b.position = 0; tf.appendText(b.bytesAvailable + "\n"); tf.appendText("\tv8 data {\n\t\t"); var cnt:int = 0; while(b.bytesAvailable) { var c:String = b.readUnsignedByte().toString(16); if(c.length < 2) c = "0" + c; tf.appendText("0x" + c); if (b.bytesAvailable == 0) break; if (++cnt == 12) { cnt = 0; tf.appendText(",\n\t\t"); } else { tf.appendText(", "); } } tf.appendText("\n\t};\n"); } private function createByteArray(data:Array):ByteArray { var b:ByteArray = new ByteArray(); for(var i:int = 0; i < data.length; ++i) b.writeByte(data[i]); b.position = 0; return b; } } } import flash.utils.IDataInput; import flash.utils.IDataOutput; import flash.utils.IExternalizable; class Foo implements IExternalizable { public var foo:String; public function Foo(s:String = "default") { foo = s; } public function writeExternal(output:IDataOutput):void { output.writeUTF(foo); } public function readExternal(input:IDataInput):void { foo = input.readUTF(); } }
package{ import flash.display.Sprite; import flash.net.registerClassAlias; import flash.text.TextField; import flash.utils.ByteArray; import flash.utils.Dictionary; [SWF(width="450", height="400")] public class flashtest extends Sprite { private var tf:TextField; public function flashtest() { tf = new TextField(); tf.width = tf.height = 450; tf.wordWrap = true; addChild(tf); dumpValues(); readValues(); } private function dumpValues():void { tf.text = ""; var b:ByteArray = new ByteArray(); var a:Array = []; a["x"] = "x"; b.writeObject(a); b.writeObject(a); dumpByteArray(b); } private function log(o:*):void { tf.appendText(o + "\n"); } private function readValues():void { /* var data:Array = [ 0x11, 0x07, 0x00, 0x0a, 0x0b, 0x01, 0x07, 0x62, 0x61, 0x72, 0x04, 0x01, 0x01, 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x0a, 0x0b, 0x01, 0x07, 0x62, 0x61, 0x72, 0x04, 0x02, 0x01, 0x06, 0x07, 0x66, 0x6f, 0x6f, 0x06, 0x07, 0x71, 0x75, 0x78, 0x0a, 0x00 ]; */ var data:Array = [ 0x09, 0x05, 0x01, 0x09, 0x01, 0x03, 0x78, 0x06, 0x00, 0x01, 0x09, 0x01, 0x00, 0x06, 0x00, 0x01, ]; var b:ByteArray = createByteArray(data); var o:* = b.readObject(); log(o); log(o.length); log(o[0].x); log(o[1].x); } private function testExternalizable():void { tf.text = ""; registerClassAlias("Foo", Foo); var b:ByteArray = new ByteArray(); var f:Foo = new Foo("asd"); var g:Foo = new Foo("bar"); var a:Array = [f, f, g]; b.writeObject(a); dumpByteArray(b); b.position = 0; var a2:Array = b.readObject(); tf.appendText((a[0] as Foo).foo); tf.appendText((a[1] as Foo).foo); tf.appendText((a[2] as Foo).foo); } private function dumpByteArray(b:ByteArray):void { b.position = 0; tf.appendText(b.bytesAvailable + "\n"); tf.appendText("\tv8 data {\n\t\t"); var cnt:int = 0; while(b.bytesAvailable) { var c:String = b.readUnsignedByte().toString(16); if(c.length < 2) c = "0" + c; tf.appendText("0x" + c); if (b.bytesAvailable == 0) break; if (++cnt == 12) { cnt = 0; tf.appendText(",\n\t\t"); } else { tf.appendText(", "); } } tf.appendText("\n\t};\n"); } private function createByteArray(data:Array):ByteArray { var b:ByteArray = new ByteArray(); for(var i:int = 0; i < data.length; ++i) b.writeByte(data[i]); b.position = 0; return b; } } } import flash.utils.IDataInput; import flash.utils.IDataOutput; import flash.utils.IExternalizable; class Foo implements IExternalizable { public var foo:String; public function Foo(s:String = "default") { foo = s; } public function writeExternal(output:IDataOutput):void { output.writeUTF(foo); } public function readExternal(input:IDataInput):void { foo = input.readUTF(); } }
Add utility function in Flash test.
Add utility function in Flash test.
ActionScript
mit
adir-/amf-cpp,Ventero/amf-cpp
98623ac977482d62438a9e9358b8c3a4947a78fc
krew-framework/krewfw/builtin_actor/system/KrewStateMachine.as
krew-framework/krewfw/builtin_actor/system/KrewStateMachine.as
package krewfw.builtin_actor.system { import flash.utils.Dictionary; import krewfw.core.KrewActor; /** * Hierarchical Finite State Machine for krewFramework. * * [Note] 後から動的に登録 State を変えるような使い方は想定していない。 * addState はあるが removeState のインタフェースは用意していない。 * * また、現状 KrewStateMachine に addState を行った後の state に * sub state を足すような書き方にも対応していない。 * KrewStateMachine のコンストラクタで一度に定義してしまうことを推奨する。 */ //------------------------------------------------------------ public class KrewStateMachine extends KrewActor { /** If trace log is annoying you, set it false. */ public static var VERBOSE:Boolean = true; // key : state id // value: KrewState instance private var _states:Dictionary = new Dictionary(); // States with constructor argument order. Used for default 'next' settings. private var _rootStateList:Vector.<KrewState> = new Vector.<KrewState>(); private var _currentState:KrewState; private var _listenMap:Dictionary = new Dictionary(); //------------------------------------------------------------ /** * Usage: * <pre> * var fsm:KrewStateMachine = new KrewStateMachine([ * { * id: "state_1", // First element will be an initial state. * enter: onEnterFunc, * next: "state_2" // Default next state is next element of this Array. * }, * * new YourCustomState(), // Instead of Object, KrewState instance is OK. * * { * id: "state_2", * children: [ // State can contain sub States. * { id: "state_2_a" }, * { id: "state_2_b" }, * { * id : "state_2_c", * listen: {event: "event_1", to: "state_4"}, * guard : guardFunc * }, * { * id: "state_2_d", * listen: [ // Array is also OK. * {event: "event_2", to: "state_1"}, * {event: "event_3", to: "state_2"} * ] * } * ] * }, * { * id: "state_3", * listen: {event: "event_1", to: "state_4"} * }, * ... * ]); * </pre> * * @param stateDefList Array of KrewState instances or definition objects. * @param funcOwner If you speciify functions with name string, pass function-owner object. */ public function KrewStateMachine(stateDefList:Array=null, funcOwner:Object=null) { displayable = false; _initStates(stateDefList, funcOwner); } private function _initStates(stateDefList:Array, funcOwner:Object=null):void { // guard if (stateDefList == null) { return; } if (!(stateDefList is Array)) { throw new Error("[KrewFSM] Constructor argument must be Array."); } if (stateDefList.length == 0) { return; } // do init addInitializer(function():void { for each (var stateDef:* in stateDefList) { addState(stateDef, funcOwner); } _setDefaultNextStates(_rootStateList); _setInitialState(stateDefList); }); } private function _setInitialState(stateDefList:Array):void { var firstDef:* = stateDefList[0]; var initStateId:String; if (firstDef is KrewState) { initStateId = firstDef.stateId; } else if (firstDef is Object) { initStateId = firstDef.id; } else { throw new Error("[KrewFSM] Invalid first stateDef."); } changeState(initStateId); } /** * next が指定されていない state について、コンストラクタで渡した定義で * 上から下になぞるように next を設定していく。 * この関数は再帰で、ツリーの末端の子 state を返す */ private function _setDefaultNextStates(stateList:Vector.<KrewState>):KrewState { if (stateList.length == 0) { return null; } for (var i:int = 0; i < stateList.length; ++i) { var state:KrewState = stateList[i]; if (state.nextStateId == null) { if (state.hasChildren()) { state.nextStateId = state.childStates[0].stateId; } else if (i + 1 <= stateList.length - 1) { state.nextStateId = stateList[i + 1].stateId; } } if (state.hasChildren()) { var edgeState:KrewState = _setDefaultNextStates(state.childStates); if (edgeState.nextStateId == null) { if (i + 1 <= stateList.length - 1) { edgeState.nextStateId = stateList[i + 1].stateId; } else { return edgeState; } } } } var edgeState:KrewState = krew.last(stateList); if (!edgeState.hasParent()) { return null; } return edgeState; } protected override function onDispose():void { for each (var state:KrewState in _states) { state.eachChild(function(childState:KrewState):void { childState.dispose(); }); } _states = null; _rootStateList = null; _currentState = null; _listenMap = null; } //------------------------------------------------------------ // public //------------------------------------------------------------ /** * @see KrewState.addState */ public function addState(stateDef:*, funcOwner:Object=null):void { var state:KrewState = KrewState.makeState(stateDef, funcOwner); _registerStateTree(state); _rootStateList.push(state); } public function changeState(stateId:String):void { if (!_states[stateId]) { throw new Error("[KrewFSM] stateId not registered: " + stateId); } var oldStateId:String = "null"; var oldState:KrewState = _currentState; var newState:KrewState = _states[stateId]; // Good bye old state if (_currentState != null) { oldStateId = _currentState.stateId; oldState.exit(); oldState.end(newState); } // Hello new state _currentState = newState; newState.begin(oldState); newState.enter(); _log("[Info] [KrewFSM] SWITCHED: " + newState.stateId + " <- " + oldStateId); } /** * If given state is current state OR parent of current state, return true. * For example, when current state is "A-sub", and it is child state of "A", * both isState("A-sub") and isState("A") returns true. * * 現在の state が指定したものか、指定したものの子 state なら true を返す。 * 例えば現在の state "A-sub" が "A" の子 state であるとき、isState("A-sub") でも * isState("A") でも true が返る。 */ public function isState(stateName:String):Boolean { if (_currentState.stateId == stateName) { return true; } var stateIter:KrewState = _currentState; while (stateIter.hasParent()) { stateIter = stateIter.parentState; if (stateIter.stateId == stateName) { return true; } } return false; } public function getState(stateId:String):KrewState { if (!_states[stateId]) { throw new Error("[KrewFSM] stateId not registered: " + stateId); } return _states[stateId]; } public function get currentState():KrewState { return _currentState; } //------------------------------------------------------------ // called by KrewState //------------------------------------------------------------ public function listenToStateEvent(event:String):void { if (_listenMap[event]) { return; } // already listening by other state listen(event, function(args:Object):void { _onEvent(args, event); }) _listenMap[event] = true; } public function stopListeningToStateEvent(event:String):void { if (!_listenMap[event]) { return; } // already stopped by other state stopListening(event); _listenMap[event] = false; } //------------------------------------------------------------ // called by krewFramework //------------------------------------------------------------ public override function onUpdate(passedTime:Number):void { if (_currentState == null) { return; } _currentState.eachParent(function(state:KrewState):void { if (state.onUpdateHandler == null) { return; } state.onUpdateHandler(state, passedTime); }); } //------------------------------------------------------------ // private //------------------------------------------------------------ private function _onEvent(args:Object, event:String):void { _currentState.onEvent(args, event); } /** * State を、子を含めて全て Dictionary に保持 * (State は Composite Pattern で sub state を子に持てる) */ private function _registerStateTree(state:KrewState):void { state.eachChild(function(aState:KrewState):void { _registerState(aState); }); } // State 1 個ぶんを Dictionary に保持 private function _registerState(state:KrewState):void { if (_states[state.stateId]) { throw new Error("[KrewFSM] stateId already registered: " + state.stateId); } _states[state.stateId] = state; state.stateMachine = this; } //------------------------------------------------------------ // debug method //------------------------------------------------------------ private function _log(text:String):void { if (!VERBOSE) { return; } krew.fwlog(text); } public function dumpDictionary():void { krew.log(krew.str.repeat("-", 50)); krew.log(" KrewStateMachine state dictionary dump"); krew.log(krew.str.repeat("-", 50)); for each(var state:KrewState in _states) { krew.log(" - " + state.stateId); } krew.log(krew.str.repeat("^", 50)); } public function dumpDictionaryVerbose():void { krew.log(krew.str.repeat("-", 50)); krew.log(" KrewStateMachine state dictionary dump -v"); krew.log(krew.str.repeat("-", 50)); for each(var state:KrewState in _states) { state.dump(); } } public function dumpState(stateId:String):void { _states[stateId].dump(); } public function dumpStateTree():void { krew.log(krew.str.repeat("-", 50)); krew.log(" KrewStateMachine state tree dump"); krew.log(krew.str.repeat("-", 50)); for each(var state:KrewState in _rootStateList) { state.dumpTree(); } krew.log(krew.str.repeat("^", 50)); } } }
package krewfw.builtin_actor.system { import flash.utils.Dictionary; import krewfw.core.KrewActor; /** * Hierarchical Finite State Machine for krewFramework. * * [Note] 後から動的に登録 State を変えるような使い方は想定していない。 * addState はあるが removeState のインタフェースは用意していない。 * * また、現状 KrewStateMachine に addState を行った後の state に * sub state を足すような書き方にも対応していない。 * KrewStateMachine のコンストラクタで一度に定義してしまうことを推奨する。 */ //------------------------------------------------------------ public class KrewStateMachine extends KrewActor { /** If trace log is annoying you, set it false. */ public static var VERBOSE:Boolean = true; // key : state id // value: KrewState instance private var _states:Dictionary = new Dictionary(); // States with constructor argument order. Used for default 'next' settings. private var _rootStateList:Vector.<KrewState> = new Vector.<KrewState>(); private var _currentState:KrewState; private var _listenMap:Dictionary = new Dictionary(); //------------------------------------------------------------ /** * Usage: * <pre> * var fsm:KrewStateMachine = new KrewStateMachine([ * { * id: "state_1", // First element will be an initial state. * enter: onEnterFunc, * next: "state_2" // Default next state is next element of this Array. * }, * * new YourCustomState(), // Instead of Object, KrewState instance is OK. * * { * id: "state_2", * children: [ // State can contain sub States. * { id: "state_2_a" }, * { id: "state_2_b" }, * { * id : "state_2_c", * listen: {event: "event_1", to: "state_4"}, * guard : guardFunc * }, * { * id: "state_2_d", * listen: [ // Array is also OK. * {event: "event_2", to: "state_1"}, * {event: "event_3", to: "state_2"} * ] * } * ] * }, * { * id: "state_3", * listen: {event: "event_1", to: "state_4"} * }, * ... * ]); * </pre> * * @param stateDefList Array of KrewState instances or definition objects. * @param funcOwner If you speciify functions with name string, pass function-owner object. */ public function KrewStateMachine(stateDefList:Array=null, funcOwner:Object=null) { displayable = false; _initStates(stateDefList, funcOwner); } private function _initStates(stateDefList:Array, funcOwner:Object=null):void { // guard if (stateDefList == null) { return; } if (!(stateDefList is Array)) { throw new Error("[KrewFSM] Constructor argument must be Array."); } if (stateDefList.length == 0) { return; } // do init addInitializer(function():void { for each (var stateDef:* in stateDefList) { addState(stateDef, funcOwner); } _setDefaultNextStates(_rootStateList); _setInitialState(stateDefList); }); } private function _setInitialState(stateDefList:Array):void { var firstDef:* = stateDefList[0]; var initStateId:String; if (firstDef is KrewState) { initStateId = firstDef.stateId; } else if (firstDef is Object) { initStateId = firstDef.id; } else { throw new Error("[KrewFSM] Invalid first stateDef."); } changeState(initStateId); } /** * next が指定されていない state について、コンストラクタで渡した定義で * 上から下になぞるように next を設定していく。 * この関数は再帰で、ツリーの末端の子 state を返す */ private function _setDefaultNextStates(stateList:Vector.<KrewState>):KrewState { if (stateList.length == 0) { return null; } for (var i:int = 0; i < stateList.length; ++i) { var state:KrewState = stateList[i]; if (state.nextStateId == null) { if (state.hasChildren()) { state.nextStateId = state.childStates[0].stateId; } else if (i + 1 <= stateList.length - 1) { state.nextStateId = stateList[i + 1].stateId; } } if (state.hasChildren()) { var edgeState:KrewState = _setDefaultNextStates(state.childStates); if (edgeState.nextStateId == null) { if (i + 1 <= stateList.length - 1) { edgeState.nextStateId = stateList[i + 1].stateId; } else { return edgeState; } } } } var edgeState:KrewState = krew.last(stateList); if (!edgeState.hasParent()) { return null; } return edgeState; } protected override function onDispose():void { for each (var state:KrewState in _states) { state.eachChild(function(childState:KrewState):void { childState.dispose(); }); } _states = null; _rootStateList = null; _currentState = null; _listenMap = null; } //------------------------------------------------------------ // public //------------------------------------------------------------ /** * @see KrewState.addState */ public function addState(stateDef:*, funcOwner:Object=null):void { var state:KrewState = KrewState.makeState(stateDef, funcOwner); _registerStateTree(state); _rootStateList.push(state); } public function changeState(stateId:String):void { if (!_states[stateId]) { throw new Error("[KrewFSM] stateId not registered: " + stateId); } var oldStateId:String = "null"; var oldState:KrewState = _currentState; var newState:KrewState = _states[stateId]; // Good bye old state if (_currentState != null) { oldStateId = _currentState.stateId; oldState.exit(); oldState.end(newState); } _log("[Info] [KrewFSM] SWITCHED: " + newState.stateId + " <- " + oldStateId); // Hello new state _currentState = newState; newState.begin(oldState); newState.enter(); } /** * If given state is current state OR parent of current state, return true. * For example, when current state is "A-sub", and it is child state of "A", * both isState("A-sub") and isState("A") returns true. * * 現在の state が指定したものか、指定したものの子 state なら true を返す。 * 例えば現在の state "A-sub" が "A" の子 state であるとき、isState("A-sub") でも * isState("A") でも true が返る。 */ public function isState(stateName:String):Boolean { if (_currentState.stateId == stateName) { return true; } var stateIter:KrewState = _currentState; while (stateIter.hasParent()) { stateIter = stateIter.parentState; if (stateIter.stateId == stateName) { return true; } } return false; } public function getState(stateId:String):KrewState { if (!_states[stateId]) { throw new Error("[KrewFSM] stateId not registered: " + stateId); } return _states[stateId]; } public function get currentState():KrewState { return _currentState; } //------------------------------------------------------------ // called by KrewState //------------------------------------------------------------ public function listenToStateEvent(event:String):void { if (_listenMap[event]) { return; } // already listening by other state listen(event, function(args:Object):void { _onEvent(args, event); }) _listenMap[event] = true; } public function stopListeningToStateEvent(event:String):void { if (!_listenMap[event]) { return; } // already stopped by other state stopListening(event); _listenMap[event] = false; } //------------------------------------------------------------ // called by krewFramework //------------------------------------------------------------ public override function onUpdate(passedTime:Number):void { if (_currentState == null) { return; } _currentState.eachParent(function(state:KrewState):void { if (state.onUpdateHandler == null) { return; } state.onUpdateHandler(state, passedTime); }); } //------------------------------------------------------------ // private //------------------------------------------------------------ private function _onEvent(args:Object, event:String):void { _currentState.onEvent(args, event); } /** * State を、子を含めて全て Dictionary に保持 * (State は Composite Pattern で sub state を子に持てる) */ private function _registerStateTree(state:KrewState):void { state.eachChild(function(aState:KrewState):void { _registerState(aState); }); } // State 1 個ぶんを Dictionary に保持 private function _registerState(state:KrewState):void { if (_states[state.stateId]) { throw new Error("[KrewFSM] stateId already registered: " + state.stateId); } _states[state.stateId] = state; state.stateMachine = this; } //------------------------------------------------------------ // debug method //------------------------------------------------------------ private function _log(text:String):void { if (!VERBOSE) { return; } krew.fwlog(text); } public function dumpDictionary():void { krew.log(krew.str.repeat("-", 50)); krew.log(" KrewStateMachine state dictionary dump"); krew.log(krew.str.repeat("-", 50)); for each(var state:KrewState in _states) { krew.log(" - " + state.stateId); } krew.log(krew.str.repeat("^", 50)); } public function dumpDictionaryVerbose():void { krew.log(krew.str.repeat("-", 50)); krew.log(" KrewStateMachine state dictionary dump -v"); krew.log(krew.str.repeat("-", 50)); for each(var state:KrewState in _states) { state.dump(); } } public function dumpState(stateId:String):void { _states[stateId].dump(); } public function dumpStateTree():void { krew.log(krew.str.repeat("-", 50)); krew.log(" KrewStateMachine state tree dump"); krew.log(krew.str.repeat("-", 50)); for each(var state:KrewState in _rootStateList) { state.dumpTree(); } krew.log(krew.str.repeat("^", 50)); } } }
Modify log position of KrewStateMachine
Modify log position of KrewStateMachine
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
d4228c5e7b8da2340522ef2e269bc733907a5d51
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
dolly-framework/src/test/actionscript/dolly/CloningOfCompositeCloneableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClass.array = [1, 2, 3, 4, 5]; compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]); compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } [Test] public function cloningOfArray():void { const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass); assertNotNull(clone.array); assertThat(clone.array, arrayWithSize(5)); assertThat(clone.array, compositeCloneableClass.array); assertFalse(clone.array == compositeCloneableClass.array); assertThat(clone.array, everyItem(isA(Number))); assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5))); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCloneableClass; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertFalse; import org.flexunit.asserts.assertNotNull; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class CloningOfCompositeCloneableClassTest { private var compositeCloneableClass:CompositeCloneableClass; private var compositeCloneableClassType:Type; [Before] public function before():void { compositeCloneableClass = new CompositeCloneableClass(); compositeCloneableClass.array = [1, 2, 3, 4, 5]; compositeCloneableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]); compositeCloneableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]); compositeCloneableClassType = Type.forInstance(compositeCloneableClass); } [After] public function after():void { compositeCloneableClass = null; compositeCloneableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Cloner.findAllWritableFieldsForType(compositeCloneableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } [Test] public function cloningOfArray():void { const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass); assertNotNull(clone.array); assertThat(clone.array, arrayWithSize(5)); assertThat(clone.array, compositeCloneableClass.array); assertFalse(clone.array == compositeCloneableClass.array); assertThat(clone.array, everyItem(isA(Number))); assertThat(clone.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5))); } [Test] public function cloningOfArrayList():void { const clone:CompositeCloneableClass = Cloner.clone(compositeCloneableClass); const arrayList:ArrayList = clone.arrayList; assertNotNull(arrayList); assertFalse(clone.arrayList == compositeCloneableClass.arrayList); assertEquals(arrayList.length, 5); assertEquals(arrayList.getItemAt(0), 1); assertEquals(arrayList.getItemAt(1), 2); assertEquals(arrayList.getItemAt(2), 3); assertEquals(arrayList.getItemAt(3), 4); assertEquals(arrayList.getItemAt(4), 5); } } }
Test for cloning of ArrayList in CompositeCloneableClass.
Test for cloning of ArrayList in CompositeCloneableClass.
ActionScript
mit
Yarovoy/dolly
2001ad4bf340cb43a0c081945addaf0f899e3b51
as3/com/netease/protobuf/WriteUtils.as
as3/com/netease/protobuf/WriteUtils.as
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved. // // [email protected] // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.utils.* public final class WriteUtils { public static function writeTag(output:IDataOutput, wireType:uint, number:uint):void { const varint:VarintWriter = new VarintWriter; varint.write(wireType, 3); varint.write(number, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_DOUBLE(output:IDataOutput, value:Number):void { output.writeDouble(value) } public static function write_TYPE_FLOAT(output:IDataOutput, value:Number):void { output.writeFloat(value) } public static function write_TYPE_INT64(output:IDataOutput, value:Int64):void { const varint:VarintWriter = new VarintWriter; varint.write(value.low, 32); varint.write(value.high, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_UINT64(output:IDataOutput, value:UInt64):void { const varint:VarintWriter = new VarintWriter; varint.write(value.low, 32); varint.write(value.high, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_INT32(output:IDataOutput, value:int):void { write_TYPE_UINT32(output, value) } public static function write_TYPE_FIXED64(output:IDataOutput, value:Int64):void { output.endian = Endian.LITTLE_ENDIAN output.writeUnsignedInt(value.low) output.writeInt(value.high) } public static function write_TYPE_FIXED32(output:IDataOutput, value:int):void { output.endian = Endian.LITTLE_ENDIAN output.writeInt(value) } public static function write_TYPE_BOOL(output:IDataOutput, value:Boolean):void { output.writeByte(value ? 1 : 0) } public static function write_TYPE_STRING(output:IDataOutput, value:String):void { var plb:PostposeLengthBuffer = output as PostposeLengthBuffer if (plb == null) { plb = new PostposeLengthBuffer } const i:uint = plb.beginBlock() plb.writeUTF(value) plb.endBlock(i) if (plb != output) { plb.toNormal(output) } } public static function write_TYPE_BYTES(output:IDataOutput, value:ByteArray):void { write_TYPE_UINT32(output, value.length) output.writeBytes(value) } public static function write_TYPE_UINT32(output:IDataOutput, value:uint):void { const varint:VarintWriter = new VarintWriter; varint.write(value, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_ENUM(output:IDataOutput, value:int):void { write_TYPE_INT32(output, value) } public static function write_TYPE_SFIXED32(output:IDataOutput, value:int):void { write_TYPE_FIXED32(output, (value >>> 31) ^ (value << 1)) } public static function write_TYPE_SFIXED64(output:IDataOutput, value:Int64):void { output.endian = Endian.LITTLE_ENDIAN output.writeUnsignedInt((value.high >>> 31) ^ (value.low << 1)) output.writeUnsignedInt((value.low >>> 31) ^ (value.high << 1)) } public static function write_TYPE_SINT32(output:IDataOutput, value:int):void { write_TYPE_UINT32(output, (value >>> 31) ^ (value << 1)) } public static function write_TYPE_SINT64(output:IDataOutput, value:Int64):void { const varint:VarintWriter = new VarintWriter; varint.write((value.high >>> 31) ^ (value.low << 1), 32); varint.write((value.low >>> 31) ^ (value.high << 1), 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_MESSAGE(output:IDataOutput, value:IExternalizable):void { var plb:PostposeLengthBuffer = output as PostposeLengthBuffer if (plb == null) { plb = new PostposeLengthBuffer } const i:uint = plb.beginBlock() value.writeExternal(plb) plb.endBlock(i) if (plb != output) { plb.toNormal(output) } } public static function writePackedRepeated(output:IDataOutput, writeFunction:Function, value:Array):void { var plb:PostposeLengthBuffer = output as PostposeLengthBuffer if (plb == null) { plb = new PostposeLengthBuffer } const i:uint = plb.beginBlock() for each (var element:* in value) { writeFunction(plb, element) } plb.endBlock(i) if (plb != output) { plb.toNormal(output) } } } }
// vim: tabstop=4 shiftwidth=4 // Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved. // // [email protected] // // Use, modification and distribution are subject to the "New BSD License" // as listed at <url: http://www.opensource.org/licenses/bsd-license.php >. package com.netease.protobuf { import flash.utils.* public final class WriteUtils { public static function writeTag(output:IDataOutput, wireType:uint, number:uint):void { const varint:VarintWriter = new VarintWriter; varint.write(wireType, 3); varint.write(number, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_DOUBLE(output:IDataOutput, value:Number):void { output.writeDouble(value) } public static function write_TYPE_FLOAT(output:IDataOutput, value:Number):void { output.writeFloat(value) } public static function write_TYPE_INT64(output:IDataOutput, value:Int64):void { const varint:VarintWriter = new VarintWriter; varint.write(value.low, 32); varint.write(value.high, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_UINT64(output:IDataOutput, value:UInt64):void { const varint:VarintWriter = new VarintWriter; varint.write(value.low, 32); varint.write(value.high, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_INT32(output:IDataOutput, value:int):void { write_TYPE_UINT32(output, value) } public static function write_TYPE_FIXED64(output:IDataOutput, value:Int64):void { output.endian = Endian.LITTLE_ENDIAN output.writeUnsignedInt(value.low) output.writeInt(value.high) } public static function write_TYPE_FIXED32(output:IDataOutput, value:int):void { output.endian = Endian.LITTLE_ENDIAN output.writeInt(value) } public static function write_TYPE_BOOL(output:IDataOutput, value:Boolean):void { output.writeByte(value ? 1 : 0) } public static function write_TYPE_STRING(output:IDataOutput, value:String):void { var plb:PostposeLengthBuffer = output as PostposeLengthBuffer if (plb == null) { plb = new PostposeLengthBuffer } const i:uint = plb.beginBlock() plb.writeUTFBytes(value) plb.endBlock(i) if (plb != output) { plb.toNormal(output) } } public static function write_TYPE_BYTES(output:IDataOutput, value:ByteArray):void { write_TYPE_UINT32(output, value.length) output.writeBytes(value) } public static function write_TYPE_UINT32(output:IDataOutput, value:uint):void { const varint:VarintWriter = new VarintWriter; varint.write(value, 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_ENUM(output:IDataOutput, value:int):void { write_TYPE_INT32(output, value) } public static function write_TYPE_SFIXED32(output:IDataOutput, value:int):void { write_TYPE_FIXED32(output, (value >>> 31) ^ (value << 1)) } public static function write_TYPE_SFIXED64(output:IDataOutput, value:Int64):void { output.endian = Endian.LITTLE_ENDIAN output.writeUnsignedInt((value.high >>> 31) ^ (value.low << 1)) output.writeUnsignedInt((value.low >>> 31) ^ (value.high << 1)) } public static function write_TYPE_SINT32(output:IDataOutput, value:int):void { write_TYPE_UINT32(output, (value >>> 31) ^ (value << 1)) } public static function write_TYPE_SINT64(output:IDataOutput, value:Int64):void { const varint:VarintWriter = new VarintWriter; varint.write((value.high >>> 31) ^ (value.low << 1), 32); varint.write((value.low >>> 31) ^ (value.high << 1), 32); varint.end() output.writeBytes(varint) } public static function write_TYPE_MESSAGE(output:IDataOutput, value:IExternalizable):void { var plb:PostposeLengthBuffer = output as PostposeLengthBuffer if (plb == null) { plb = new PostposeLengthBuffer } const i:uint = plb.beginBlock() value.writeExternal(plb) plb.endBlock(i) if (plb != output) { plb.toNormal(output) } } public static function writePackedRepeated(output:IDataOutput, writeFunction:Function, value:Array):void { var plb:PostposeLengthBuffer = output as PostposeLengthBuffer if (plb == null) { plb = new PostposeLengthBuffer } const i:uint = plb.beginBlock() for each (var element:* in value) { writeFunction(plb, element) } plb.endBlock(i) if (plb != output) { plb.toNormal(output) } } } }
修复发送字符串时多发了前缀的 bug
修复发送字符串时多发了前缀的 bug
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
2c9ef93544d141de6404b312897dc79f1ee286bc
Bin/Data/Scripts/Editor/EditorGizmo.as
Bin/Data/Scripts/Editor/EditorGizmo.as
// Urho3D editor node transform gizmo handling Node@ gizmoNode; StaticModel@ gizmo; const float axisMaxD = 0.1; const float axisMaxT = 1.0; const float rotSensitivity = 50.0; EditMode lastGizmoMode; // For undo bool previousGizmoDrag; bool needGizmoUndo; Array<Transform> oldGizmoTransforms; class GizmoAxis { Ray axisRay; bool selected; bool lastSelected; float t; float d; float lastT; float lastD; GizmoAxis() { selected = false; lastSelected = false; t = 0.0; d = 0.0; lastT = 0.0; lastD = 0.0; } void Update(Ray cameraRay, float scale, bool drag) { // Do not select when UI has modal element if (ui.HasModalElement()) { selected = false; return; } Vector3 closest = cameraRay.ClosestPoint(axisRay); Vector3 projected = axisRay.Project(closest); d = axisRay.Distance(closest); t = (projected - axisRay.origin).DotProduct(axisRay.direction); // Determine the sign of d from a plane that goes through the camera position to the axis Plane axisPlane(cameraNode.position, axisRay.origin, axisRay.origin + axisRay.direction); if (axisPlane.Distance(closest) < 0.0) d = -d; // Update selected status only when not dragging if (!drag) { selected = Abs(d) < axisMaxD * scale && t >= -axisMaxD * scale && t <= axisMaxT * scale; lastT = t; lastD = d; } } void Moved() { lastT = t; lastD = d; } } GizmoAxis gizmoAxisX; GizmoAxis gizmoAxisY; GizmoAxis gizmoAxisZ; void CreateGizmo() { gizmoNode = Node(); gizmo = gizmoNode.CreateComponent("StaticModel"); gizmo.model = cache.GetResource("Model", "Models/Axes.mdl"); gizmo.materials[0] = cache.GetResource("Material", "Materials/RedUnlit.xml"); gizmo.materials[1] = cache.GetResource("Material", "Materials/GreenUnlit.xml"); gizmo.materials[2] = cache.GetResource("Material", "Materials/BlueUnlit.xml"); gizmo.enabled = false; gizmo.viewMask = 0x80000000; // Editor raycasts use viewmask 0x7fffffff gizmo.occludee = false; gizmoAxisX.lastSelected = false; gizmoAxisY.lastSelected = false; gizmoAxisZ.lastSelected = false; lastGizmoMode = EDIT_MOVE; } void HideGizmo() { if (gizmo !is null) gizmo.enabled = false; } void ShowGizmo() { if (gizmo !is null) { gizmo.enabled = true; // Because setting enabled = false detaches the gizmo from octree, // and it is a manually added drawable, must readd to octree when showing if (editorScene.octree !is null) editorScene.octree.AddManualDrawable(gizmo); } } void UpdateGizmo() { UseGizmo(); PositionGizmo(); ResizeGizmo(); } void PositionGizmo() { if (gizmo is null) return; if (editNodes.empty) { HideGizmo(); return; } Vector3 center(0, 0, 0); for (uint i = 0; i < editNodes.length; ++i) center += editNodes[i].worldPosition; center /= editNodes.length; gizmoNode.position = center; if (axisMode == AXIS_WORLD || editNodes.length > 1) gizmoNode.rotation = Quaternion(); else gizmoNode.rotation = editNodes[0].worldRotation; if (editMode != lastGizmoMode) { switch (editMode) { case EDIT_MOVE: gizmo.model = cache.GetResource("Model", "Models/Axes.mdl"); break; case EDIT_ROTATE: gizmo.model = cache.GetResource("Model", "Models/RotateAxes.mdl"); break; case EDIT_SCALE: gizmo.model = cache.GetResource("Model", "Models/ScaleAxes.mdl"); break; } lastGizmoMode = editMode; } if (editMode != EDIT_SELECT && !gizmo.enabled) ShowGizmo(); else if (editMode == EDIT_SELECT && gizmo.enabled) HideGizmo(); } void ResizeGizmo() { if (gizmo is null || !gizmo.enabled) return; float c = 0.1; if (camera.orthographic) gizmoNode.scale = Vector3(c, c, c); else { /// \todo if matrix classes were exposed to script could simply use the camera's inverse world transform float z = (cameraNode.worldRotation.Inverse() * (gizmoNode.worldPosition - cameraNode.worldPosition)).z; gizmoNode.scale = Vector3(c * z, c * z, c * z); } } void CalculateGizmoAxes() { gizmoAxisX.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(1, 0, 0)); gizmoAxisY.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 1, 0)); gizmoAxisZ.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 0, 1)); } void GizmoMoved() { gizmoAxisX.Moved(); gizmoAxisY.Moved(); gizmoAxisZ.Moved(); } void UseGizmo() { if (gizmo is null || !gizmo.enabled || editMode == EDIT_SELECT) { StoreGizmoEditActions(); previousGizmoDrag = false; return; } IntVector2 pos = ui.cursorPosition; if (ui.GetElementAt(pos) !is null) return; Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height); float scale = gizmoNode.scale.x; // Recalculate axes only when not left-dragging bool drag = input.mouseButtonDown[MOUSEB_LEFT]; if (!drag) CalculateGizmoAxes(); gizmoAxisX.Update(cameraRay, scale, drag); gizmoAxisY.Update(cameraRay, scale, drag); gizmoAxisZ.Update(cameraRay, scale, drag); if (gizmoAxisX.selected != gizmoAxisX.lastSelected) { gizmo.materials[0] = cache.GetResource("Material", gizmoAxisX.selected ? "Materials/BrightRedUnlit.xml" : "Materials/RedUnlit.xml"); gizmoAxisX.lastSelected = gizmoAxisX.selected; } if (gizmoAxisY.selected != gizmoAxisY.lastSelected) { gizmo.materials[1] = cache.GetResource("Material", gizmoAxisY.selected ? "Materials/BrightGreenUnlit.xml" : "Materials/GreenUnlit.xml"); gizmoAxisY.lastSelected = gizmoAxisY.selected; } if (gizmoAxisZ.selected != gizmoAxisZ.lastSelected) { gizmo.materials[2] = cache.GetResource("Material", gizmoAxisZ.selected ? "Materials/BrightBlueUnlit.xml" : "Materials/BlueUnlit.xml"); gizmoAxisZ.lastSelected = gizmoAxisZ.selected; }; if (drag) { // Store initial transforms for undo when gizmo drag started if (!previousGizmoDrag) { oldGizmoTransforms.Resize(editNodes.length); for (uint i = 0; i < editNodes.length; ++i) oldGizmoTransforms[i].Define(editNodes[i]); } bool moved = false; if (editMode == EDIT_MOVE) { Vector3 adjust(0, 0, 0); if (gizmoAxisX.selected) adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT); if (gizmoAxisY.selected) adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT); if (gizmoAxisZ.selected) adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT); moved = MoveNodes(adjust); } else if (editMode == EDIT_ROTATE) { Vector3 adjust(0, 0, 0); if (gizmoAxisX.selected) adjust.x = (gizmoAxisX.d - gizmoAxisX.lastD) * rotSensitivity / scale; if (gizmoAxisY.selected) adjust.y = -(gizmoAxisY.d - gizmoAxisY.lastD) * rotSensitivity / scale; if (gizmoAxisZ.selected) adjust.z = (gizmoAxisZ.d - gizmoAxisZ.lastD) * rotSensitivity / scale; moved = RotateNodes(adjust); } else if (editMode == EDIT_SCALE) { Vector3 adjust(0, 0, 0); if (gizmoAxisX.selected) adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT); if (gizmoAxisY.selected) adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT); if (gizmoAxisZ.selected) adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT); // Special handling for uniform scale: use the unmodified X-axis movement only if (editMode == EDIT_SCALE && gizmoAxisX.selected && gizmoAxisY.selected && gizmoAxisZ.selected) { float x = gizmoAxisX.t - gizmoAxisX.lastT; adjust = Vector3(x, x, x); } moved = ScaleNodes(adjust); } if (moved) { GizmoMoved(); UpdateNodeAttributes(); needGizmoUndo = true; } } else { if (previousGizmoDrag) StoreGizmoEditActions(); } previousGizmoDrag = drag; } bool IsGizmoSelected() { return gizmo !is null && gizmo.enabled && (gizmoAxisX.selected || gizmoAxisY.selected || gizmoAxisZ.selected); } bool MoveNodes(Vector3 adjust) { bool moved = false; if (adjust.length > M_EPSILON) { for (uint i = 0; i < editNodes.length; ++i) { if (moveSnap) { float moveStepScaled = moveStep * snapScale; adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled; adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled; adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled; } Node@ node = editNodes[i]; Vector3 nodeAdjust = adjust; if (axisMode == AXIS_LOCAL && editNodes.length == 1) nodeAdjust = node.worldRotation * nodeAdjust; Vector3 worldPos = node.worldPosition; Vector3 oldPos = node.position; worldPos += nodeAdjust; if (node.parent is null) node.position = worldPos; else node.position = node.parent.WorldToLocal(worldPos); if (node.position != oldPos) moved = true; } } return moved; } bool RotateNodes(Vector3 adjust) { bool moved = false; if (rotateSnap) { float rotateStepScaled = rotateStep * snapScale; adjust.x = Floor(adjust.x / rotateStepScaled + 0.5) * rotateStepScaled; adjust.y = Floor(adjust.y / rotateStepScaled + 0.5) * rotateStepScaled; adjust.z = Floor(adjust.z / rotateStepScaled + 0.5) * rotateStepScaled; } if (adjust.length > M_EPSILON) { moved = true; for (uint i = 0; i < editNodes.length; ++i) { Node@ node = editNodes[i]; Quaternion rotQuat(adjust); if (axisMode == AXIS_LOCAL && editNodes.length == 1) node.rotation = node.rotation * rotQuat; else { Vector3 offset = node.worldPosition - gizmoAxisX.axisRay.origin; if (node.parent !is null && node.parent.worldRotation != Quaternion(1, 0, 0, 0)) rotQuat = node.parent.worldRotation.Inverse() * rotQuat * node.parent.worldRotation; node.rotation = rotQuat * node.rotation; Vector3 newPosition = gizmoAxisX.axisRay.origin + rotQuat * offset; if (node.parent !is null) newPosition = node.parent.WorldToLocal(newPosition); node.position = newPosition; } } } return moved; } bool ScaleNodes(Vector3 adjust) { bool moved = false; if (adjust.length > M_EPSILON) { for (uint i = 0; i < editNodes.length; ++i) { Node@ node = editNodes[i]; Vector3 scale = node.scale; Vector3 oldScale = scale; if (!scaleSnap) scale += adjust; else { float scaleStepScaled = scaleStep * snapScale; if (adjust.x != 0) { scale.x += adjust.x * scaleStepScaled; scale.x = Floor(scale.x / scaleStepScaled + 0.5) * scaleStepScaled; } if (adjust.y != 0) { scale.y += adjust.y * scaleStepScaled; scale.y = Floor(scale.y / scaleStepScaled + 0.5) * scaleStepScaled; } if (adjust.z != 0) { scale.z += adjust.z * scaleStepScaled; scale.z = Floor(scale.z / scaleStepScaled + 0.5) * scaleStepScaled; } } if (scale != oldScale) moved = true; node.scale = scale; } } return moved; } void StoreGizmoEditActions() { if (needGizmoUndo && editNodes.length > 0 && oldGizmoTransforms.length == editNodes.length) { EditActionGroup group; for (uint i = 0; i < editNodes.length; ++i) { EditNodeTransformAction action; action.Define(editNodes[i], oldGizmoTransforms[i]); group.actions.Push(action); } SaveEditActionGroup(group); SetSceneModified(); } needGizmoUndo = false; }
// Urho3D editor node transform gizmo handling Node@ gizmoNode; StaticModel@ gizmo; const float axisMaxD = 0.1; const float axisMaxT = 1.0; const float rotSensitivity = 50.0; EditMode lastGizmoMode; // For undo bool previousGizmoDrag; bool needGizmoUndo; Array<Transform> oldGizmoTransforms; class GizmoAxis { Ray axisRay; bool selected; bool lastSelected; float t; float d; float lastT; float lastD; GizmoAxis() { selected = false; lastSelected = false; t = 0.0; d = 0.0; lastT = 0.0; lastD = 0.0; } void Update(Ray cameraRay, float scale, bool drag) { // Do not select when UI has modal element if (ui.HasModalElement()) { selected = false; return; } Vector3 closest = cameraRay.ClosestPoint(axisRay); Vector3 projected = axisRay.Project(closest); d = axisRay.Distance(closest); t = (projected - axisRay.origin).DotProduct(axisRay.direction); // Determine the sign of d from a plane that goes through the camera position to the axis Plane axisPlane(cameraNode.position, axisRay.origin, axisRay.origin + axisRay.direction); if (axisPlane.Distance(closest) < 0.0) d = -d; // Update selected status only when not dragging if (!drag) { selected = Abs(d) < axisMaxD * scale && t >= -axisMaxD * scale && t <= axisMaxT * scale; lastT = t; lastD = d; } } void Moved() { lastT = t; lastD = d; } } GizmoAxis gizmoAxisX; GizmoAxis gizmoAxisY; GizmoAxis gizmoAxisZ; void CreateGizmo() { gizmoNode = Node(); gizmo = gizmoNode.CreateComponent("StaticModel"); gizmo.model = cache.GetResource("Model", "Models/Axes.mdl"); gizmo.materials[0] = cache.GetResource("Material", "Materials/RedUnlit.xml"); gizmo.materials[1] = cache.GetResource("Material", "Materials/GreenUnlit.xml"); gizmo.materials[2] = cache.GetResource("Material", "Materials/BlueUnlit.xml"); gizmo.enabled = false; gizmo.viewMask = 0x80000000; // Editor raycasts use viewmask 0x7fffffff gizmo.occludee = false; gizmoAxisX.lastSelected = false; gizmoAxisY.lastSelected = false; gizmoAxisZ.lastSelected = false; lastGizmoMode = EDIT_MOVE; } void HideGizmo() { if (gizmo !is null) gizmo.enabled = false; } void ShowGizmo() { if (gizmo !is null) { gizmo.enabled = true; // Because setting enabled = false detaches the gizmo from octree, // and it is a manually added drawable, must readd to octree when showing if (editorScene.octree !is null) editorScene.octree.AddManualDrawable(gizmo); } } void UpdateGizmo() { UseGizmo(); PositionGizmo(); ResizeGizmo(); } void PositionGizmo() { if (gizmo is null) return; if (editNodes.empty) { HideGizmo(); return; } Vector3 center(0, 0, 0); for (uint i = 0; i < editNodes.length; ++i) center += editNodes[i].worldPosition; center /= editNodes.length; gizmoNode.position = center; if (axisMode == AXIS_WORLD || editNodes.length > 1) gizmoNode.rotation = Quaternion(); else gizmoNode.rotation = editNodes[0].worldRotation; if (editMode != lastGizmoMode) { switch (editMode) { case EDIT_MOVE: gizmo.model = cache.GetResource("Model", "Models/Axes.mdl"); break; case EDIT_ROTATE: gizmo.model = cache.GetResource("Model", "Models/RotateAxes.mdl"); break; case EDIT_SCALE: gizmo.model = cache.GetResource("Model", "Models/ScaleAxes.mdl"); break; } lastGizmoMode = editMode; } if ((editMode != EDIT_SELECT && !orbiting) && !gizmo.enabled) ShowGizmo(); else if ((editMode == EDIT_SELECT || orbiting) && gizmo.enabled) HideGizmo(); } void ResizeGizmo() { if (gizmo is null || !gizmo.enabled) return; float c = 0.1; if (camera.orthographic) gizmoNode.scale = Vector3(c, c, c); else { /// \todo if matrix classes were exposed to script could simply use the camera's inverse world transform float z = (cameraNode.worldRotation.Inverse() * (gizmoNode.worldPosition - cameraNode.worldPosition)).z; gizmoNode.scale = Vector3(c * z, c * z, c * z); } } void CalculateGizmoAxes() { gizmoAxisX.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(1, 0, 0)); gizmoAxisY.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 1, 0)); gizmoAxisZ.axisRay = Ray(gizmoNode.position, gizmoNode.rotation * Vector3(0, 0, 1)); } void GizmoMoved() { gizmoAxisX.Moved(); gizmoAxisY.Moved(); gizmoAxisZ.Moved(); } void UseGizmo() { if (gizmo is null || !gizmo.enabled || editMode == EDIT_SELECT) { StoreGizmoEditActions(); previousGizmoDrag = false; return; } IntVector2 pos = ui.cursorPosition; if (ui.GetElementAt(pos) !is null) return; Ray cameraRay = camera.GetScreenRay(float(pos.x) / graphics.width, float(pos.y) / graphics.height); float scale = gizmoNode.scale.x; // Recalculate axes only when not left-dragging bool drag = input.mouseButtonDown[MOUSEB_LEFT]; if (!drag) CalculateGizmoAxes(); gizmoAxisX.Update(cameraRay, scale, drag); gizmoAxisY.Update(cameraRay, scale, drag); gizmoAxisZ.Update(cameraRay, scale, drag); if (gizmoAxisX.selected != gizmoAxisX.lastSelected) { gizmo.materials[0] = cache.GetResource("Material", gizmoAxisX.selected ? "Materials/BrightRedUnlit.xml" : "Materials/RedUnlit.xml"); gizmoAxisX.lastSelected = gizmoAxisX.selected; } if (gizmoAxisY.selected != gizmoAxisY.lastSelected) { gizmo.materials[1] = cache.GetResource("Material", gizmoAxisY.selected ? "Materials/BrightGreenUnlit.xml" : "Materials/GreenUnlit.xml"); gizmoAxisY.lastSelected = gizmoAxisY.selected; } if (gizmoAxisZ.selected != gizmoAxisZ.lastSelected) { gizmo.materials[2] = cache.GetResource("Material", gizmoAxisZ.selected ? "Materials/BrightBlueUnlit.xml" : "Materials/BlueUnlit.xml"); gizmoAxisZ.lastSelected = gizmoAxisZ.selected; }; if (drag) { // Store initial transforms for undo when gizmo drag started if (!previousGizmoDrag) { oldGizmoTransforms.Resize(editNodes.length); for (uint i = 0; i < editNodes.length; ++i) oldGizmoTransforms[i].Define(editNodes[i]); } bool moved = false; if (editMode == EDIT_MOVE) { Vector3 adjust(0, 0, 0); if (gizmoAxisX.selected) adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT); if (gizmoAxisY.selected) adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT); if (gizmoAxisZ.selected) adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT); moved = MoveNodes(adjust); } else if (editMode == EDIT_ROTATE) { Vector3 adjust(0, 0, 0); if (gizmoAxisX.selected) adjust.x = (gizmoAxisX.d - gizmoAxisX.lastD) * rotSensitivity / scale; if (gizmoAxisY.selected) adjust.y = -(gizmoAxisY.d - gizmoAxisY.lastD) * rotSensitivity / scale; if (gizmoAxisZ.selected) adjust.z = (gizmoAxisZ.d - gizmoAxisZ.lastD) * rotSensitivity / scale; moved = RotateNodes(adjust); } else if (editMode == EDIT_SCALE) { Vector3 adjust(0, 0, 0); if (gizmoAxisX.selected) adjust += Vector3(1, 0, 0) * (gizmoAxisX.t - gizmoAxisX.lastT); if (gizmoAxisY.selected) adjust += Vector3(0, 1, 0) * (gizmoAxisY.t - gizmoAxisY.lastT); if (gizmoAxisZ.selected) adjust += Vector3(0, 0, 1) * (gizmoAxisZ.t - gizmoAxisZ.lastT); // Special handling for uniform scale: use the unmodified X-axis movement only if (editMode == EDIT_SCALE && gizmoAxisX.selected && gizmoAxisY.selected && gizmoAxisZ.selected) { float x = gizmoAxisX.t - gizmoAxisX.lastT; adjust = Vector3(x, x, x); } moved = ScaleNodes(adjust); } if (moved) { GizmoMoved(); UpdateNodeAttributes(); needGizmoUndo = true; } } else { if (previousGizmoDrag) StoreGizmoEditActions(); } previousGizmoDrag = drag; } bool IsGizmoSelected() { return gizmo !is null && gizmo.enabled && (gizmoAxisX.selected || gizmoAxisY.selected || gizmoAxisZ.selected); } bool MoveNodes(Vector3 adjust) { bool moved = false; if (adjust.length > M_EPSILON) { for (uint i = 0; i < editNodes.length; ++i) { if (moveSnap) { float moveStepScaled = moveStep * snapScale; adjust.x = Floor(adjust.x / moveStepScaled + 0.5) * moveStepScaled; adjust.y = Floor(adjust.y / moveStepScaled + 0.5) * moveStepScaled; adjust.z = Floor(adjust.z / moveStepScaled + 0.5) * moveStepScaled; } Node@ node = editNodes[i]; Vector3 nodeAdjust = adjust; if (axisMode == AXIS_LOCAL && editNodes.length == 1) nodeAdjust = node.worldRotation * nodeAdjust; Vector3 worldPos = node.worldPosition; Vector3 oldPos = node.position; worldPos += nodeAdjust; if (node.parent is null) node.position = worldPos; else node.position = node.parent.WorldToLocal(worldPos); if (node.position != oldPos) moved = true; } } return moved; } bool RotateNodes(Vector3 adjust) { bool moved = false; if (rotateSnap) { float rotateStepScaled = rotateStep * snapScale; adjust.x = Floor(adjust.x / rotateStepScaled + 0.5) * rotateStepScaled; adjust.y = Floor(adjust.y / rotateStepScaled + 0.5) * rotateStepScaled; adjust.z = Floor(adjust.z / rotateStepScaled + 0.5) * rotateStepScaled; } if (adjust.length > M_EPSILON) { moved = true; for (uint i = 0; i < editNodes.length; ++i) { Node@ node = editNodes[i]; Quaternion rotQuat(adjust); if (axisMode == AXIS_LOCAL && editNodes.length == 1) node.rotation = node.rotation * rotQuat; else { Vector3 offset = node.worldPosition - gizmoAxisX.axisRay.origin; if (node.parent !is null && node.parent.worldRotation != Quaternion(1, 0, 0, 0)) rotQuat = node.parent.worldRotation.Inverse() * rotQuat * node.parent.worldRotation; node.rotation = rotQuat * node.rotation; Vector3 newPosition = gizmoAxisX.axisRay.origin + rotQuat * offset; if (node.parent !is null) newPosition = node.parent.WorldToLocal(newPosition); node.position = newPosition; } } } return moved; } bool ScaleNodes(Vector3 adjust) { bool moved = false; if (adjust.length > M_EPSILON) { for (uint i = 0; i < editNodes.length; ++i) { Node@ node = editNodes[i]; Vector3 scale = node.scale; Vector3 oldScale = scale; if (!scaleSnap) scale += adjust; else { float scaleStepScaled = scaleStep * snapScale; if (adjust.x != 0) { scale.x += adjust.x * scaleStepScaled; scale.x = Floor(scale.x / scaleStepScaled + 0.5) * scaleStepScaled; } if (adjust.y != 0) { scale.y += adjust.y * scaleStepScaled; scale.y = Floor(scale.y / scaleStepScaled + 0.5) * scaleStepScaled; } if (adjust.z != 0) { scale.z += adjust.z * scaleStepScaled; scale.z = Floor(scale.z / scaleStepScaled + 0.5) * scaleStepScaled; } } if (scale != oldScale) moved = true; node.scale = scale; } } return moved; } void StoreGizmoEditActions() { if (needGizmoUndo && editNodes.length > 0 && oldGizmoTransforms.length == editNodes.length) { EditActionGroup group; for (uint i = 0; i < editNodes.length; ++i) { EditNodeTransformAction action; action.Define(editNodes[i], oldGizmoTransforms[i]); group.actions.Push(action); } SaveEditActionGroup(group); SetSceneModified(); } needGizmoUndo = false; }
Hide also the gizmo when orbiting.
Hide also the gizmo when orbiting.
ActionScript
mit
fire/Urho3D-1,cosmy1/Urho3D,victorholt/Urho3D,victorholt/Urho3D,codemon66/Urho3D,eugeneko/Urho3D,luveti/Urho3D,299299/Urho3D,victorholt/Urho3D,MonkeyFirst/Urho3D,abdllhbyrktr/Urho3D,weitjong/Urho3D,codemon66/Urho3D,victorholt/Urho3D,carnalis/Urho3D,c4augustus/Urho3D,codedash64/Urho3D,kostik1337/Urho3D,orefkov/Urho3D,eugeneko/Urho3D,SuperWangKai/Urho3D,codedash64/Urho3D,henu/Urho3D,helingping/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,rokups/Urho3D,weitjong/Urho3D,bacsmar/Urho3D,rokups/Urho3D,helingping/Urho3D,henu/Urho3D,c4augustus/Urho3D,abdllhbyrktr/Urho3D,xiliu98/Urho3D,urho3d/Urho3D,SirNate0/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,codemon66/Urho3D,xiliu98/Urho3D,luveti/Urho3D,carnalis/Urho3D,helingping/Urho3D,victorholt/Urho3D,codemon66/Urho3D,urho3d/Urho3D,eugeneko/Urho3D,MeshGeometry/Urho3D,abdllhbyrktr/Urho3D,c4augustus/Urho3D,rokups/Urho3D,codemon66/Urho3D,urho3d/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,299299/Urho3D,abdllhbyrktr/Urho3D,helingping/Urho3D,MeshGeometry/Urho3D,MeshGeometry/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,c4augustus/Urho3D,SuperWangKai/Urho3D,orefkov/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,PredatorMF/Urho3D,henu/Urho3D,weitjong/Urho3D,orefkov/Urho3D,cosmy1/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,rokups/Urho3D,codedash64/Urho3D,fire/Urho3D-1,PredatorMF/Urho3D,iainmerrick/Urho3D,bacsmar/Urho3D,helingping/Urho3D,rokups/Urho3D,luveti/Urho3D,MonkeyFirst/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,299299/Urho3D,MonkeyFirst/Urho3D,SirNate0/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,c4augustus/Urho3D,rokups/Urho3D,urho3d/Urho3D,eugeneko/Urho3D,weitjong/Urho3D,xiliu98/Urho3D,kostik1337/Urho3D,luveti/Urho3D,luveti/Urho3D,SirNate0/Urho3D,codedash64/Urho3D,iainmerrick/Urho3D,299299/Urho3D,weitjong/Urho3D,SirNate0/Urho3D,henu/Urho3D,abdllhbyrktr/Urho3D,SuperWangKai/Urho3D,fire/Urho3D-1,SuperWangKai/Urho3D,orefkov/Urho3D,MeshGeometry/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,tommy3/Urho3D,cosmy1/Urho3D,iainmerrick/Urho3D,tommy3/Urho3D,299299/Urho3D,cosmy1/Urho3D,xiliu98/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,henu/Urho3D,iainmerrick/Urho3D
5e8995d2beb4f9ad5aa6e9dc7f9fc4dfcd5b332e
bin/Data/Scripts/Main.as
bin/Data/Scripts/Main.as
Scene@ newScene_; Scene@ scene_; Camera@ camera_; Timer timer_; void Start() { StartScene("Scenes/Level1.xml"); SubscribeToEvent("LevelComplete", "HandleLevelComplete"); } void Stop() { } void HandleLevelComplete(StringHash type, VariantMap& data) { log.Debug("Level Complete. I should be loading "+data["NextLevel"].GetString()); float timeTaken = timer_.GetMSec(false); log.Debug("You took " + timeTaken / 1000.f + " seconds to solve the level"); StartScene(data["NextLevel"].GetString()); } void StartScene(String scene) { newScene_ = Scene(); newScene_.LoadAsyncXML(cache.GetFile(scene)); SubscribeToEvent("AsyncLoadFinished", "HandleAsyncLoadFinished"); } void HandleAsyncLoadFinished(StringHash type, VariantMap& data) { UnsubscribeFromEvent("AsyncLoadFinished"); newScene_ = data["Scene"].GetPtr(); SubscribeToEvent("Update", "HandleDelayedStart"); } void HandleDelayedStart(StringHash type, VariantMap& data) { UnsubscribeFromEvent("Update"); Node@ cameraNode = newScene_.GetChild("Camera", true); Camera@ newCamera = cameraNode.CreateComponent("Camera"); Viewport@ viewport = Viewport(newScene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; scene_ = newScene_; camera_ = newCamera; newScene_ = null; timer_.Reset(); }
#include "Scripts/PlayerPower.as" Scene@ newScene_; Scene@ scene_; Camera@ camera_; Timer timer_; void Start() { StartScene("Scenes/Level1.xml"); SubscribeToEvent("LevelComplete", "HandleLevelComplete"); } void Stop() { } void HandleLevelComplete(StringHash type, VariantMap& data) { log.Debug("Level Complete. I should be loading "+data["NextLevel"].GetString()); float timeTaken = timer_.GetMSec(false); log.Debug("You took " + timeTaken / 1000.f + " seconds to solve the level"); Node@[] playerNode = scene_.GetChildrenWithTag("player", true); PlayerPower@ playerPower = cast<PlayerPower>(playerNode[0].GetScriptObject("PlayerPower")); float power = playerPower.Power; log.Debug("You had " + power + " power remaining"); StartScene(data["NextLevel"].GetString()); } void StartScene(String scene) { newScene_ = Scene(); newScene_.LoadAsyncXML(cache.GetFile(scene)); SubscribeToEvent("AsyncLoadFinished", "HandleAsyncLoadFinished"); } void HandleAsyncLoadFinished(StringHash type, VariantMap& data) { UnsubscribeFromEvent("AsyncLoadFinished"); newScene_ = data["Scene"].GetPtr(); SubscribeToEvent("Update", "HandleDelayedStart"); } void HandleDelayedStart(StringHash type, VariantMap& data) { UnsubscribeFromEvent("Update"); Node@ cameraNode = newScene_.GetChild("Camera", true); Camera@ newCamera = cameraNode.CreateComponent("Camera"); Viewport@ viewport = Viewport(newScene_, cameraNode.GetComponent("Camera")); renderer.viewports[0] = viewport; scene_ = newScene_; camera_ = newCamera; newScene_ = null; timer_.Reset(); }
Determine player power at the end of each level.
Determine player power at the end of each level.
ActionScript
mit
leyarotheconquerer/on-off
2e4077626154aed5665277cee1b009066c49b481
src/org/mangui/flowplayer/HLSStreamProvider.as
src/org/mangui/flowplayer/HLSStreamProvider.as
/* 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/. */ package org.mangui.flowplayer { import org.mangui.hls.event.HLSEvent; import org.mangui.hls.utils.Params2Settings; import flash.display.DisplayObject; import flash.net.NetConnection; import flash.net.NetStream; import flash.utils.Dictionary; import flash.media.Video; import org.mangui.hls.HLS; import org.mangui.hls.constant.HLSPlayStates; import org.flowplayer.model.Plugin; import org.flowplayer.model.PluginModel; import org.flowplayer.view.Flowplayer; import org.flowplayer.controller.StreamProvider; import org.flowplayer.controller.TimeProvider; import org.flowplayer.controller.VolumeController; import org.flowplayer.model.Clip; import org.flowplayer.model.ClipType; import org.flowplayer.model.ClipEvent; import org.flowplayer.model.ClipEventType; import org.flowplayer.model.Playlist; import org.flowplayer.view.StageVideoWrapper; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class HLSStreamProvider implements StreamProvider,Plugin { private var _volumecontroller : VolumeController; private var _playlist : Playlist; private var _timeProvider : TimeProvider; private var _model : PluginModel; private var _player : Flowplayer; private var _clip : Clip; private var _video : Video; /** reference to the framework. **/ private var _hls : HLS; // event values private var _position : Number = 0; private var _duration : Number = 0; private var _bufferedTime : Number = 0; private var _videoWidth : int = -1; private var _videoHeight : int = -1; private var _isManifestLoaded : Boolean = false; private var _pauseAfterStart : Boolean; private var _seekable : Boolean = false; public function getDefaultConfig() : Object { return null; } public function onConfig(model : PluginModel) : void { CONFIG::LOGGING { Log.info("onConfig()"); } _model = model; } public function onLoad(player : Flowplayer) : void { CONFIG::LOGGING { Log.info("onLoad()"); } _player = player; _hls = new HLS(); _hls.stage = player.screen.getDisplayObject().stage; _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.ID3_UPDATED, _ID3Handler); var cfg : Object = _model.config; for (var object : String in cfg) { var subidx : int = object.indexOf("hls_"); if (subidx != -1) { Params2Settings.set(object.substr(4), cfg[object]); } } _model.dispatchOnLoad(); } private function _completeHandler(event : HLSEvent) : void { // dispatch a before event because the finish has default behavior that can be prevented by listeners _clip.dispatchBeforeEvent(new ClipEvent(ClipEventType.FINISH)); }; private function _errorHandler(event : HLSEvent) : void { }; private function _ID3Handler(event : HLSEvent) : void { _clip.dispatch(ClipEventType.NETSTREAM_EVENT, "onID3", event.ID3Data); }; private function _manifestHandler(event : HLSEvent) : void { _duration = event.levels[_hls.startlevel].duration; _isManifestLoaded = true; _clip.duration = _duration; _clip.stopLiveOnPause = false; _clip.dispatch(ClipEventType.METADATA); _seekable = true; // if (_hls.type == HLSTypes.LIVE) { // _seekable = false; // } else { // _seekable = true; // } _hls.stream.play(); _clip.dispatch(ClipEventType.SEEK); if (_pauseAfterStart) { pause(new ClipEvent(ClipEventType.PAUSE)); } }; private function _mediaTimeHandler(event : HLSEvent) : void { _position = Math.max(0, event.mediatime.position); _duration = event.mediatime.duration; _clip.duration = _duration; _bufferedTime = event.mediatime.buffer + event.mediatime.position; var videoWidth : int = _video.videoWidth; var videoHeight : int = _video.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { CONFIG::LOGGING { Log.info("video size changed to " + videoWidth + "/" + videoHeight); } _videoWidth = videoWidth; _videoHeight = videoHeight; _clip.originalWidth = videoWidth; _clip.originalHeight = videoHeight; _clip.dispatch(ClipEventType.START); _clip.dispatch(ClipEventType.METADATA_CHANGED); } } }; private function _stateHandler(event : HLSEvent) : void { // CONFIG::LOGGING { // Log.txt("state:"+ event.state); // } switch(event.state) { case HLSPlayStates.IDLE: case HLSPlayStates.PLAYING: case HLSPlayStates.PAUSED: _clip.dispatch(ClipEventType.BUFFER_FULL); break; case HLSPlayStates.PLAYING_BUFFERING: case HLSPlayStates.PAUSED_BUFFERING: _clip.dispatch(ClipEventType.BUFFER_EMPTY); break; default: break; } }; /** * Starts loading the specified clip. Once video data is available the provider * must set it to the clip using <code>clip.setContent()</code>. Typically the video * object passed to the clip is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">flash.media.Video</a>. * * @param event the event that this provider should dispatch once loading has successfully started, * once dispatched the player will call <code>getVideo()</code> * @param clip the clip to load * @param pauseAfterStart if <code>true</code> the playback is paused on first frame and * buffering is continued * @see Clip#setContent() * @see #getVideo() */ public function load(event : ClipEvent, clip : Clip, pauseAfterStart : Boolean = true) : void { _clip = clip; CONFIG::LOGGING { Log.info("load()" + clip.completeUrl); } _hls.load(clip.completeUrl); _pauseAfterStart = pauseAfterStart; clip.type = ClipType.VIDEO; clip.dispatch(ClipEventType.BEGIN); clip.setNetStream(_hls.stream); return; } /** * Gets the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">Video</a> object. * A stream will be attached to the returned video object using <code>attachStream()</code>. * @param clip the clip for which the Video object is queried for * @see #attachStream() */ public function getVideo(clip : Clip) : DisplayObject { CONFIG::LOGGING { Log.debug("getVideo()"); } if (_video == null) { if (clip.useStageVideo) { CONFIG::LOGGING { Log.debug("useStageVideo"); } _video = new StageVideoWrapper(clip); } else { _video = new Video(); _video.smoothing = clip.smoothing; } } return _video; } /** * Attaches a stream to the specified display object. * @param video the video object that was originally retrieved using <code>getVideo()</code>. * @see #getVideo() */ public function attachStream(video : DisplayObject) : void { CONFIG::LOGGING { Log.debug("attachStream()"); } Video(video).attachNetStream(_hls.stream); return; } /** * Pauses playback. * @param event the event that this provider should dispatch once loading has been successfully paused */ public function pause(event : ClipEvent) : void { CONFIG::LOGGING { Log.info("pause()"); } _hls.stream.pause(); if (event) { _clip.dispatch(ClipEventType.PAUSE); } return; } /** * Resumes playback. * @param event the event that this provider should dispatch once loading has been successfully resumed */ public function resume(event : ClipEvent) : void { CONFIG::LOGGING { Log.info("resume()"); } _hls.stream.resume(); _clip.dispatch(ClipEventType.RESUME); return; } /** * Stops and rewinds to the beginning of current clip. * @param event the event that this provider should dispatch once loading has been successfully stopped */ public function stop(event : ClipEvent, closeStream : Boolean = false) : void { CONFIG::LOGGING { Log.info("stop()"); } _hls.stream.close(); return; } /** * Seeks to the specified point in the timeline. * @param event the event that this provider should dispatch once the seek is in target * @param seconds the target point in the timeline */ public function seek(event : ClipEvent, seconds : Number) : void { CONFIG::LOGGING { Log.info("seek()"); } _hls.stream.seek(seconds); _position = seconds; _bufferedTime = seconds; _clip.dispatch(ClipEventType.SEEK, seconds); return; } /** * File size in bytes. */ public function get fileSize() : Number { return 0; } /** * Current playhead time in seconds. */ public function get time() : Number { return _position; } /** * The point in timeline where the buffered data region begins, in seconds. */ public function get bufferStart() : Number { return 0; } /** * The point in timeline where the buffered data region ends, in seconds. */ public function get bufferEnd() : Number { return _bufferedTime; } /** * Does this provider support random seeking to unbuffered areas in the timeline? */ public function get allowRandomSeek() : Boolean { // CONFIG::LOGGING { // Log.info("allowRandomSeek()"); // } return _seekable; } /** * Volume controller used to control the video volume. */ public function set volumeController(controller : VolumeController) : void { _volumecontroller = controller; _volumecontroller.netStream = _hls.stream; return; } /** * Is this provider in the process of stopping the stream? * When stopped the provider should not dispatch any events resulting from events that * might get triggered by the underlying streaming implementation. */ public function get stopping() : Boolean { CONFIG::LOGGING { Log.info("stopping()"); } return false; } /** * The playlist instance. */ public function set playlist(playlist : Playlist) : void { // CONFIG::LOGGING { // Log.debug("set playlist()"); // } _playlist = playlist; return; } public function get playlist() : Playlist { CONFIG::LOGGING { Log.debug("get playlist()"); } return _playlist; } /** * Adds a callback public function to the NetConnection instance. This public function will fire ClipEvents whenever * the callback is invoked in the connection. * @param name * @param listener * @return * @see ClipEventType#CONNECTION_EVENT */ public function addConnectionCallback(name : String, listener : Function) : void { CONFIG::LOGGING { Log.debug("addConnectionCallback()"); } return; } /** * Adds a callback public function to the NetStream object. This public function will fire a ClipEvent of type StreamEvent whenever * the callback has been invoked on the stream. The invokations typically come from a server-side app running * on RTMP server. * @param name * @param listener * @return * @see ClipEventType.NETSTREAM_EVENT */ public function addStreamCallback(name : String, listener : Function) : void { CONFIG::LOGGING { Log.debug("addStreamCallback()"); } return; } /** * Get the current stream callbacks. * @return a dictionary of callbacks, keyed using callback names and values being the callback functions */ public function get streamCallbacks() : Dictionary { CONFIG::LOGGING { Log.debug("get streamCallbacks()"); } return null; } /** * Gets the underlying NetStream object. * @return the netStream currently in use, or null if this provider has not started streaming yet */ public function get netStream() : NetStream { CONFIG::LOGGING { Log.debug("get netStream()"); } return _hls.stream; } /** * Gets the underlying netConnection object. * @return the netConnection currently in use, or null if this provider has not started streaming yet */ public function get netConnection() : NetConnection { CONFIG::LOGGING { Log.debug("get netConnection()"); } return null; } /** * Sets a time provider to be used by this StreamProvider. Normally the playhead time is queried from * the NetStream.time property. * * @param timeProvider */ public function set timeProvider(timeProvider : TimeProvider) : void { CONFIG::LOGGING { Log.debug("set timeProvider()"); } _timeProvider = timeProvider; return; } /** * Gets the type of StreamProvider either http, rtmp, psuedo. */ public function get type() : String { return "httpstreaming"; } /** * Switch the stream in realtime with / without dynamic stream switching support * * @param event ClipEvent the clip event * @param clip Clip the clip to switch to * @param netStreamPlayOptions Object the NetStreamPlayOptions object to enable dynamic stream switching */ public function switchStream(event : ClipEvent, clip : Clip, netStreamPlayOptions : Object = null) : void { CONFIG::LOGGING { Log.info("switchStream()"); } return; } } }
/* 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/. */ package org.mangui.flowplayer { import org.mangui.hls.event.HLSEvent; import org.mangui.hls.utils.Params2Settings; import flash.display.DisplayObject; import flash.net.NetConnection; import flash.net.NetStream; import flash.utils.Dictionary; import flash.media.Video; import org.mangui.hls.HLS; import org.mangui.hls.constant.HLSPlayStates; import org.flowplayer.model.Plugin; import org.flowplayer.model.PluginModel; import org.flowplayer.view.Flowplayer; import org.flowplayer.controller.StreamProvider; import org.flowplayer.controller.TimeProvider; import org.flowplayer.controller.VolumeController; import org.flowplayer.model.Clip; import org.flowplayer.model.ClipType; import org.flowplayer.model.ClipEvent; import org.flowplayer.model.ClipEventType; import org.flowplayer.model.Playlist; import org.flowplayer.view.StageVideoWrapper; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class HLSStreamProvider implements StreamProvider,Plugin { private var _volumecontroller : VolumeController; private var _playlist : Playlist; private var _timeProvider : TimeProvider; private var _model : PluginModel; private var _player : Flowplayer; private var _clip : Clip; private var _video : Video; /** reference to the framework. **/ private var _hls : HLS; // event values private var _position : Number = 0; private var _duration : Number = 0; private var _bufferedTime : Number = 0; private var _videoWidth : int = -1; private var _videoHeight : int = -1; private var _isManifestLoaded : Boolean = false; private var _pauseAfterStart : Boolean; private var _seekable : Boolean = false; public function getDefaultConfig() : Object { return null; } public function onConfig(model : PluginModel) : void { CONFIG::LOGGING { Log.info("onConfig()"); } _model = model; } public function onLoad(player : Flowplayer) : void { CONFIG::LOGGING { Log.info("onLoad()"); } _player = player; _hls = new HLS(); _hls.stage = player.screen.getDisplayObject().stage; _hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler); _hls.addEventListener(HLSEvent.ERROR, _errorHandler); _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler); _hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler); _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.ID3_UPDATED, _ID3Handler); var cfg : Object = _model.config; for (var object : String in cfg) { var subidx : int = object.indexOf("hls_"); if (subidx != -1) { Params2Settings.set(object.substr(4), cfg[object]); } } _model.dispatchOnLoad(); } private function _completeHandler(event : HLSEvent) : void { // dispatch a before event because the finish has default behavior that can be prevented by listeners _clip.dispatchBeforeEvent(new ClipEvent(ClipEventType.FINISH)); }; private function _errorHandler(event : HLSEvent) : void { }; private function _ID3Handler(event : HLSEvent) : void { _clip.dispatch(ClipEventType.NETSTREAM_EVENT, "onID3", event.ID3Data); }; private function _manifestHandler(event : HLSEvent) : void { _duration = event.levels[_hls.startlevel].duration; _isManifestLoaded = true; _clip.duration = _duration; _clip.stopLiveOnPause = false; _clip.dispatch(ClipEventType.METADATA); _seekable = true; // if (_hls.type == HLSTypes.LIVE) { // _seekable = false; // } else { // _seekable = true; // } _hls.stream.play(); _clip.dispatch(ClipEventType.SEEK,0); if (_pauseAfterStart) { pause(new ClipEvent(ClipEventType.PAUSE)); } }; private function _mediaTimeHandler(event : HLSEvent) : void { _position = Math.max(0, event.mediatime.position); _duration = event.mediatime.duration; _clip.duration = _duration; _bufferedTime = event.mediatime.buffer + event.mediatime.position; var videoWidth : int = _video.videoWidth; var videoHeight : int = _video.videoHeight; if (videoWidth && videoHeight) { var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight; if (changed) { CONFIG::LOGGING { Log.info("video size changed to " + videoWidth + "/" + videoHeight); } _videoWidth = videoWidth; _videoHeight = videoHeight; _clip.originalWidth = videoWidth; _clip.originalHeight = videoHeight; _clip.dispatch(ClipEventType.START); _clip.dispatch(ClipEventType.METADATA_CHANGED); } } }; private function _stateHandler(event : HLSEvent) : void { // CONFIG::LOGGING { // Log.txt("state:"+ event.state); // } switch(event.state) { case HLSPlayStates.IDLE: case HLSPlayStates.PLAYING: case HLSPlayStates.PAUSED: _clip.dispatch(ClipEventType.BUFFER_FULL); break; case HLSPlayStates.PLAYING_BUFFERING: case HLSPlayStates.PAUSED_BUFFERING: _clip.dispatch(ClipEventType.BUFFER_EMPTY); break; default: break; } }; /** * Starts loading the specified clip. Once video data is available the provider * must set it to the clip using <code>clip.setContent()</code>. Typically the video * object passed to the clip is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">flash.media.Video</a>. * * @param event the event that this provider should dispatch once loading has successfully started, * once dispatched the player will call <code>getVideo()</code> * @param clip the clip to load * @param pauseAfterStart if <code>true</code> the playback is paused on first frame and * buffering is continued * @see Clip#setContent() * @see #getVideo() */ public function load(event : ClipEvent, clip : Clip, pauseAfterStart : Boolean = true) : void { _clip = clip; CONFIG::LOGGING { Log.info("load()" + clip.completeUrl); } _hls.load(clip.completeUrl); _pauseAfterStart = pauseAfterStart; clip.type = ClipType.VIDEO; clip.dispatch(ClipEventType.BEGIN); clip.setNetStream(_hls.stream); return; } /** * Gets the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">Video</a> object. * A stream will be attached to the returned video object using <code>attachStream()</code>. * @param clip the clip for which the Video object is queried for * @see #attachStream() */ public function getVideo(clip : Clip) : DisplayObject { CONFIG::LOGGING { Log.debug("getVideo()"); } if (_video == null) { if (clip.useStageVideo) { CONFIG::LOGGING { Log.debug("useStageVideo"); } _video = new StageVideoWrapper(clip); } else { _video = new Video(); _video.smoothing = clip.smoothing; } } return _video; } /** * Attaches a stream to the specified display object. * @param video the video object that was originally retrieved using <code>getVideo()</code>. * @see #getVideo() */ public function attachStream(video : DisplayObject) : void { CONFIG::LOGGING { Log.debug("attachStream()"); } Video(video).attachNetStream(_hls.stream); return; } /** * Pauses playback. * @param event the event that this provider should dispatch once loading has been successfully paused */ public function pause(event : ClipEvent) : void { CONFIG::LOGGING { Log.info("pause()"); } _hls.stream.pause(); if (event) { _clip.dispatch(ClipEventType.PAUSE); } return; } /** * Resumes playback. * @param event the event that this provider should dispatch once loading has been successfully resumed */ public function resume(event : ClipEvent) : void { CONFIG::LOGGING { Log.info("resume()"); } _hls.stream.resume(); _clip.dispatch(ClipEventType.RESUME); return; } /** * Stops and rewinds to the beginning of current clip. * @param event the event that this provider should dispatch once loading has been successfully stopped */ public function stop(event : ClipEvent, closeStream : Boolean = false) : void { CONFIG::LOGGING { Log.info("stop()"); } _hls.stream.close(); return; } /** * Seeks to the specified point in the timeline. * @param event the event that this provider should dispatch once the seek is in target * @param seconds the target point in the timeline */ public function seek(event : ClipEvent, seconds : Number) : void { CONFIG::LOGGING { Log.info("seek()"); } _hls.stream.seek(seconds); _position = seconds; _bufferedTime = seconds; _clip.dispatch(ClipEventType.SEEK, seconds); return; } /** * File size in bytes. */ public function get fileSize() : Number { return 0; } /** * Current playhead time in seconds. */ public function get time() : Number { return _position; } /** * The point in timeline where the buffered data region begins, in seconds. */ public function get bufferStart() : Number { return 0; } /** * The point in timeline where the buffered data region ends, in seconds. */ public function get bufferEnd() : Number { return _bufferedTime; } /** * Does this provider support random seeking to unbuffered areas in the timeline? */ public function get allowRandomSeek() : Boolean { // CONFIG::LOGGING { // Log.info("allowRandomSeek()"); // } return _seekable; } /** * Volume controller used to control the video volume. */ public function set volumeController(controller : VolumeController) : void { _volumecontroller = controller; _volumecontroller.netStream = _hls.stream; return; } /** * Is this provider in the process of stopping the stream? * When stopped the provider should not dispatch any events resulting from events that * might get triggered by the underlying streaming implementation. */ public function get stopping() : Boolean { CONFIG::LOGGING { Log.info("stopping()"); } return false; } /** * The playlist instance. */ public function set playlist(playlist : Playlist) : void { // CONFIG::LOGGING { // Log.debug("set playlist()"); // } _playlist = playlist; return; } public function get playlist() : Playlist { CONFIG::LOGGING { Log.debug("get playlist()"); } return _playlist; } /** * Adds a callback public function to the NetConnection instance. This public function will fire ClipEvents whenever * the callback is invoked in the connection. * @param name * @param listener * @return * @see ClipEventType#CONNECTION_EVENT */ public function addConnectionCallback(name : String, listener : Function) : void { CONFIG::LOGGING { Log.debug("addConnectionCallback()"); } return; } /** * Adds a callback public function to the NetStream object. This public function will fire a ClipEvent of type StreamEvent whenever * the callback has been invoked on the stream. The invokations typically come from a server-side app running * on RTMP server. * @param name * @param listener * @return * @see ClipEventType.NETSTREAM_EVENT */ public function addStreamCallback(name : String, listener : Function) : void { CONFIG::LOGGING { Log.debug("addStreamCallback()"); } return; } /** * Get the current stream callbacks. * @return a dictionary of callbacks, keyed using callback names and values being the callback functions */ public function get streamCallbacks() : Dictionary { CONFIG::LOGGING { Log.debug("get streamCallbacks()"); } return null; } /** * Gets the underlying NetStream object. * @return the netStream currently in use, or null if this provider has not started streaming yet */ public function get netStream() : NetStream { CONFIG::LOGGING { Log.debug("get netStream()"); } return _hls.stream; } /** * Gets the underlying netConnection object. * @return the netConnection currently in use, or null if this provider has not started streaming yet */ public function get netConnection() : NetConnection { CONFIG::LOGGING { Log.debug("get netConnection()"); } return null; } /** * Sets a time provider to be used by this StreamProvider. Normally the playhead time is queried from * the NetStream.time property. * * @param timeProvider */ public function set timeProvider(timeProvider : TimeProvider) : void { CONFIG::LOGGING { Log.debug("set timeProvider()"); } _timeProvider = timeProvider; return; } /** * Gets the type of StreamProvider either http, rtmp, psuedo. */ public function get type() : String { return "httpstreaming"; } /** * Switch the stream in realtime with / without dynamic stream switching support * * @param event ClipEvent the clip event * @param clip Clip the clip to switch to * @param netStreamPlayOptions Object the NetStreamPlayOptions object to enable dynamic stream switching */ public function switchStream(event : ClipEvent, clip : Clip, netStreamPlayOptions : Object = null) : void { CONFIG::LOGGING { Log.info("switchStream()"); } return; } } }
fix seek bar not being updated when replaying a video
flashlsFlowPlayer.swf: fix seek bar not being updated when replaying a video
ActionScript
mpl-2.0
stevemayhew/flashls,stevemayhew/flashls,stevemayhew/flashls,stevemayhew/flashls
5d5ad0b0a276116f4d5ecf97ab1e65448749b429
src/aerys/minko/scene/controller/mesh/skinning/SkinningController.as
src/aerys/minko/scene/controller/mesh/skinning/SkinningController.as
package aerys.minko.scene.controller.mesh.skinning { import aerys.minko.Minko; import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.EnterFrameController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.log.DebugLevel; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.geom.Matrix3D; import flash.utils.Dictionary; public final class SkinningController extends EnterFrameController implements IRebindableController { public static const MAX_NUM_INFLUENCES : uint = 8; public static const MAX_NUM_JOINTS : uint = 51; private var _skinningHelper : AbstractSkinningHelper; private var _isDirty : Boolean; private var _method : uint; private var _bindShapeMatrix : Matrix3D; private var _skeletonRoot : Group; private var _joints : Vector.<Group>; private var _invBindMatrices : Vector.<Matrix3D>; private var _numVisibleTargets : uint; public function get skinningMethod() : uint { return _method; } public function get bindShape() : Matrix4x4 { var bindShape : Matrix4x4 = new Matrix4x4(); bindShape.minko_math::_matrix = _bindShapeMatrix; return bindShape; } public function get skeletonRoot() : Group { return _skeletonRoot; } public function get joints() : Vector.<Group> { return _joints; } public function get invBindMatrices() : Vector.<Matrix4x4> { var numMatrices : uint = _invBindMatrices.length; var invBindMatrices : Vector.<Matrix4x4> = new Vector.<Matrix4x4>(numMatrices); for (var matrixId : uint = 0; matrixId < numMatrices; ++matrixId) { invBindMatrices[matrixId] = new Matrix4x4(); invBindMatrices[matrixId].minko_math::_matrix = _invBindMatrices[matrixId]; } return invBindMatrices; } public function SkinningController(method : uint, skeletonRoot : Group, joints : Vector.<Group>, bindShape : Matrix4x4, invBindMatrices : Vector.<Matrix4x4>) { super(Mesh); if (!skeletonRoot) throw new Error('skeletonRoot cannot be null'); _method = method; _skeletonRoot = skeletonRoot; _bindShapeMatrix = bindShape.minko_math::_matrix; _isDirty = false; initialize(joints, invBindMatrices); } private function initialize(joints : Vector.<Group>, invBindMatrices : Vector.<Matrix4x4>) : void { var numJoints : uint = joints.length; _joints = joints.slice(); _invBindMatrices = new Vector.<Matrix3D>(numJoints, true); for (var jointId : uint = 0; jointId < numJoints; ++jointId) _invBindMatrices[jointId] = invBindMatrices[jointId].minko_math::_matrix; } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene) == 1) subscribeToJoints(); var mesh : Mesh = target as Mesh; mesh.bindings.addCallback('inFrustum', meshVisibilityChangedHandler); if (!_skinningHelper) { var numInfluences : uint = AbstractSkinningHelper.getNumInfluences( mesh.geometry.format ); if (_joints.length > MAX_NUM_JOINTS || numInfluences > MAX_NUM_INFLUENCES) { _method = SkinningMethod.SOFTWARE_MATRIX; Minko.log( DebugLevel.SKINNING, 'Too many influences/joints: switching to SkinningMethod.SOFTWARE.' ); } if (skinningMethod != SkinningMethod.SOFTWARE_MATRIX) { try { _skinningHelper = new HardwareSkinningHelper( _method, _bindShapeMatrix, _invBindMatrices ); } catch (e : Error) { Minko.log( DebugLevel.SKINNING, 'Falling back to software skinning: ' + e.message, this ); _method = SkinningMethod.SOFTWARE_MATRIX; } } _skinningHelper ||= new SoftwareSkinningHelper( _method, _bindShapeMatrix, _invBindMatrices ); } _skinningHelper.addMesh(mesh); _isDirty = true; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetRemovedFromScene(target, scene); if (numTargets == 0) unsubscribeFromJoints(); var mesh : Mesh = target as Mesh; mesh.bindings.removeCallback('inFrustum', meshVisibilityChangedHandler); _skinningHelper.removeMesh(mesh); } private function jointLocalToWorldChangedHandler(node : Group, emitter : Matrix4x4) : void { _isDirty = true; } public function rebindDependencies(nodeMap : Dictionary, controllerMap : Dictionary) : void { var numJoints : uint = _joints.length; if (numTargets != 0) unsubscribeFromJoints(); if (_joints.indexOf(_skeletonRoot) == -1 && nodeMap[_skeletonRoot]) _skeletonRoot = nodeMap[_skeletonRoot]; for (var jointId : uint = 0; jointId < numJoints; ++jointId) if (nodeMap[_joints[jointId]]) _joints[jointId] = nodeMap[_joints[jointId]]; if (numTargets != 0) subscribeToJoints(); _isDirty = true; } private function subscribeToJoints() : void { var numJoints : uint = _joints.length; for (var jointId : uint = 0; jointId < numJoints; ++jointId) _joints[jointId].localToWorldTransformChanged.add(jointLocalToWorldChangedHandler); if (_joints.indexOf(_skeletonRoot) == -1) _skeletonRoot.localToWorldTransformChanged.add(jointLocalToWorldChangedHandler); } private function unsubscribeFromJoints() : void { var numJoints : uint = _joints.length; for (var jointId : uint = 0; jointId < numJoints; ++jointId) _joints[jointId].localToWorldTransformChanged.remove(jointLocalToWorldChangedHandler); if (_joints.indexOf(_skeletonRoot) == -1) _skeletonRoot.localToWorldTransformChanged.remove(jointLocalToWorldChangedHandler); } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_isDirty && _skinningHelper.numMeshes != 0) { _skinningHelper.update(_skeletonRoot, _joints); _isDirty = false; } } override public function clone() : AbstractController { return new SkinningController(_method, _skeletonRoot, _joints, bindShape, invBindMatrices); } private function meshVisibilityChangedHandler(bindings : DataBindings, property : String, oldValue : Boolean, newValue : Boolean) : void { if (newValue) _skinningHelper.addMesh(bindings.owner as Mesh); else _skinningHelper.removeMesh(bindings.owner as Mesh); } } }
package aerys.minko.scene.controller.mesh.skinning { import aerys.minko.Minko; import aerys.minko.ns.minko_math; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.EnterFrameController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Mesh; import aerys.minko.scene.node.Scene; import aerys.minko.type.animation.SkinningMethod; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.log.DebugLevel; import aerys.minko.type.math.Matrix4x4; import flash.display.BitmapData; import flash.geom.Matrix3D; import flash.utils.Dictionary; public final class SkinningController extends EnterFrameController implements IRebindableController { public static const MAX_NUM_INFLUENCES : uint = 8; public static const MAX_NUM_JOINTS : uint = 51; private var _skinningHelper : AbstractSkinningHelper; private var _isDirty : Boolean; private var _method : uint; private var _bindShapeMatrix : Matrix3D; private var _skeletonRoot : Group; private var _joints : Vector.<Group>; private var _invBindMatrices : Vector.<Matrix3D>; private var _numVisibleTargets : uint; public function get skinningMethod() : uint { return _method; } public function get bindShape() : Matrix4x4 { var bindShape : Matrix4x4 = new Matrix4x4(); bindShape.minko_math::_matrix = _bindShapeMatrix; return bindShape; } public function get skeletonRoot() : Group { return _skeletonRoot; } public function get joints() : Vector.<Group> { return _joints; } public function get invBindMatrices() : Vector.<Matrix4x4> { var numMatrices : uint = _invBindMatrices.length; var invBindMatrices : Vector.<Matrix4x4> = new Vector.<Matrix4x4>(numMatrices); for (var matrixId : uint = 0; matrixId < numMatrices; ++matrixId) { invBindMatrices[matrixId] = new Matrix4x4(); invBindMatrices[matrixId].minko_math::_matrix = _invBindMatrices[matrixId]; } return invBindMatrices; } public function SkinningController(method : uint, skeletonRoot : Group, joints : Vector.<Group>, bindShape : Matrix4x4, invBindMatrices : Vector.<Matrix4x4>) { super(Mesh); if (!skeletonRoot) throw new Error('skeletonRoot cannot be null'); _method = method; _skeletonRoot = skeletonRoot; _bindShapeMatrix = bindShape.minko_math::_matrix; _isDirty = false; initialize(joints, invBindMatrices); } private function initialize(joints : Vector.<Group>, invBindMatrices : Vector.<Matrix4x4>) : void { var numJoints : uint = joints.length; _joints = joints.slice(); _invBindMatrices = new Vector.<Matrix3D>(numJoints, true); for (var jointId : uint = 0; jointId < numJoints; ++jointId) _invBindMatrices[jointId] = invBindMatrices[jointId].minko_math::_matrix; } override protected function targetAddedToScene(target : ISceneNode, scene : Scene) : void { super.targetAddedToScene(target, scene); if (getNumTargetsInScene(scene) == 1) subscribeToJoints(); var mesh : Mesh = target as Mesh; mesh.bindings.addCallback('insideFrustum', meshVisibilityChangedHandler); if (!_skinningHelper) { var numInfluences : uint = AbstractSkinningHelper.getNumInfluences( mesh.geometry.format ); if (_joints.length > MAX_NUM_JOINTS || numInfluences > MAX_NUM_INFLUENCES) { _method = SkinningMethod.SOFTWARE_MATRIX; Minko.log( DebugLevel.SKINNING, 'Too many influences/joints: switching to SkinningMethod.SOFTWARE.' ); } if (skinningMethod != SkinningMethod.SOFTWARE_MATRIX) { try { _skinningHelper = new HardwareSkinningHelper( _method, _bindShapeMatrix, _invBindMatrices ); } catch (e : Error) { Minko.log( DebugLevel.SKINNING, 'Falling back to software skinning: ' + e.message, this ); _method = SkinningMethod.SOFTWARE_MATRIX; } } _skinningHelper ||= new SoftwareSkinningHelper( _method, _bindShapeMatrix, _invBindMatrices ); } _skinningHelper.addMesh(mesh); _isDirty = true; } override protected function targetRemovedFromScene(target : ISceneNode, scene : Scene) : void { super.targetRemovedFromScene(target, scene); if (getNumTargetsInScene(scene) == 0) unsubscribeFromJoints(); var mesh : Mesh = target as Mesh; mesh.bindings.removeCallback('insideFrustum', meshVisibilityChangedHandler); _skinningHelper.removeMesh(mesh); } private function jointLocalToWorldChangedHandler(node : Group, emitter : Matrix4x4) : void { _isDirty = true; } public function rebindDependencies(nodeMap : Dictionary, controllerMap : Dictionary) : void { var numJoints : uint = _joints.length; if (numTargets != 0) unsubscribeFromJoints(); if (_joints.indexOf(_skeletonRoot) == -1 && nodeMap[_skeletonRoot]) _skeletonRoot = nodeMap[_skeletonRoot]; for (var jointId : uint = 0; jointId < numJoints; ++jointId) if (nodeMap[_joints[jointId]]) _joints[jointId] = nodeMap[_joints[jointId]]; if (numTargets != 0) subscribeToJoints(); _isDirty = true; } private function subscribeToJoints() : void { var numJoints : uint = _joints.length; for (var jointId : uint = 0; jointId < numJoints; ++jointId) _joints[jointId].localToWorldTransformChanged.add(jointLocalToWorldChangedHandler); if (_joints.indexOf(_skeletonRoot) == -1) _skeletonRoot.localToWorldTransformChanged.add(jointLocalToWorldChangedHandler); } private function unsubscribeFromJoints() : void { var numJoints : uint = _joints.length; for (var jointId : uint = 0; jointId < numJoints; ++jointId) _joints[jointId].localToWorldTransformChanged.remove(jointLocalToWorldChangedHandler); if (_joints.indexOf(_skeletonRoot) == -1) _skeletonRoot.localToWorldTransformChanged.remove(jointLocalToWorldChangedHandler); } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { if (_isDirty && _skinningHelper.numMeshes != 0) { _skinningHelper.update(_skeletonRoot, _joints); _isDirty = false; } } override public function clone() : AbstractController { return new SkinningController(_method, _skeletonRoot, _joints, bindShape, invBindMatrices); } private function meshVisibilityChangedHandler(bindings : DataBindings, property : String, oldValue : Boolean, newValue : Boolean) : void { if (newValue) _skinningHelper.addMesh(bindings.owner as Mesh); else _skinningHelper.removeMesh(bindings.owner as Mesh); } } }
fix broken reference to the 'inFrustum' mesh binding
fix broken reference to the 'inFrustum' mesh binding
ActionScript
mit
aerys/minko-as3
18d3a383ddef834da0c92da7694d9a9e4b6d2f7f
src/org/mangui/hls/HLSSettings.as
src/org/mangui/hls/HLSSettings.as
/* 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/. */ package org.mangui.hls { import org.mangui.hls.constant.HLSSeekMode; import org.mangui.hls.constant.HLSMaxLevelCappingMode; public final class HLSSettings extends Object { /** * Limit levels usable in auto-quality by the stage dimensions (width and height). * true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight). * Max level will be set depending on the maxLevelCappingMode option. * false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelToStage : Boolean = false; /** * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode * HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled) * HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled) * * Default is HLSMaxLevelCappingMode.DOWNSCALE */ public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE; // // // // // // ///////////////////////////////// // // org.mangui.hls.stream.HLSNetStream // // // // // // // ///////////////////////////////// /** * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling. * * Default is -1 = auto */ public static var minBufferLength : Number = -1; /** * Defines maximum buffer length in seconds. * (0 means infinite buffering) * * Default is 120. */ public static var maxBufferLength : Number = 120; /** * Defines maximum back buffer length in seconds. * (0 means infinite back buffering) * * Default is 30. */ public static var maxBackBufferLength : Number = 30; /** * Defines low buffer length in seconds. * When crossing down this threshold, HLS will switch to buffering state. * * Default is 3. */ public static var lowBufferLength : Number = 3; /** * Defines seek mode to one form available in HLSSeekMode class: * HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position * HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position) * * Default is HLSSeekMode.KEYFRAME_SEEK. */ public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK; /** max nb of retries for Key Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var keyLoadMaxRetry : int = -1; /** keyLoadMaxRetryTimeout * Maximum key retry timeout (in milliseconds) in case I/O errors are met. * Every fail on key request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var keyLoadMaxRetryTimeout : Number = 64000; /** max nb of retries for Fragment Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var fragmentLoadMaxRetry : int = 4000; /** fragmentLoadMaxRetryTimeout * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached. * * Default is 4000. */ public static var fragmentLoadMaxRetryTimeout : Number = 64000; /** fragmentLoadSkipAfterMaxRetry * control behaviour in case fragment load still fails after max retry timeout * if set to true, fragment will be skipped and next one will be loaded. * If set to false, an I/O Error will be raised. * * Default is true. */ public static var fragmentLoadSkipAfterMaxRetry : Boolean = true; /** * If set to true, live playlist will be flushed from URL cache before reloading * (this is to workaround some cache issues with some combination of Flash Player / IE version) * * Default is false */ public static var flushLiveURLCache : Boolean = false; /** max nb of retries for Manifest Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var manifestLoadMaxRetry : int = -1; /** manifestLoadMaxRetryTimeout * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var manifestLoadMaxRetryTimeout : Number = 64000; /** * If greater than 0, specifies the preferred bitrate. * If -1, and startFromLevel is not specified, automatic start level selection will be used. * This parameter, if set, will take priority over startFromLevel. */ public static var startFromBitrate : Number = -1; /** start level : * from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate) */ public static var startFromLevel : Number = -1; /** seek level : * from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, keep previous level matching previous download bandwidth */ public static var seekFromLevel : Number = -1; /** use hardware video decoder : * it will set NetStream.useHardwareDecoder * refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder */ public static var useHardwareVideoDecoder : Boolean = false; /** * Defines whether INFO level log messages will will appear in the console * Default is true. */ public static var logInfo : Boolean = true; /** * Defines whether DEBUG level log messages will will appear in the console * Default is false. */ public static var logDebug : Boolean = false; /** * Defines whether DEBUG2 level log messages will will appear in the console * Default is false. */ public static var logDebug2 : Boolean = false; /** * Defines whether WARN level log messages will will appear in the console * Default is true. */ public static var logWarn : Boolean = true; /** * Defines whether ERROR level log messages will will appear in the console * Default is true. */ public static var logError : Boolean = true; } }
/* 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/. */ package org.mangui.hls { import org.mangui.hls.constant.HLSSeekMode; import org.mangui.hls.constant.HLSMaxLevelCappingMode; public final class HLSSettings extends Object { /** * Limit levels usable in auto-quality by the stage dimensions (width and height). * true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight). * Max level will be set depending on the maxLevelCappingMode option. * false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. * * Note: this setting is ignored in manual mode so all the levels could be selected manually. * * Default is false */ public static var capLevelToStage : Boolean = false; /** * Defines the max level capping mode to the one available in HLSMaxLevelCappingMode * HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled) * HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled) * * Default is HLSMaxLevelCappingMode.DOWNSCALE */ public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE; // // // // // // ///////////////////////////////// // // org.mangui.hls.stream.HLSNetStream // // // // // // // ///////////////////////////////// /** * Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling. * * Default is -1 = auto */ public static var minBufferLength : Number = -1; /** * Defines maximum buffer length in seconds. * (0 means infinite buffering) * * Default is 120. */ public static var maxBufferLength : Number = 120; /** * Defines maximum back buffer length in seconds. * (0 means infinite back buffering) * * Default is 30. */ public static var maxBackBufferLength : Number = 30; /** * Defines low buffer length in seconds. * When crossing down this threshold, HLS will switch to buffering state. * * Default is 3. */ public static var lowBufferLength : Number = 3; /** * Defines seek mode to one form available in HLSSeekMode class: * HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position * HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position) * * Default is HLSSeekMode.KEYFRAME_SEEK. */ public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK; /** max nb of retries for Key Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var keyLoadMaxRetry : int = 3; /** keyLoadMaxRetryTimeout * Maximum key retry timeout (in milliseconds) in case I/O errors are met. * Every fail on key request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var keyLoadMaxRetryTimeout : Number = 64000; /** max nb of retries for Fragment Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var fragmentLoadMaxRetry : int = 3; /** fragmentLoadMaxRetryTimeout * Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached. * * Default is 4000. */ public static var fragmentLoadMaxRetryTimeout : Number = 64000; /** fragmentLoadSkipAfterMaxRetry * control behaviour in case fragment load still fails after max retry timeout * if set to true, fragment will be skipped and next one will be loaded. * If set to false, an I/O Error will be raised. * * Default is true. */ public static var fragmentLoadSkipAfterMaxRetry : Boolean = true; /** * If set to true, live playlist will be flushed from URL cache before reloading * (this is to workaround some cache issues with some combination of Flash Player / IE version) * * Default is false */ public static var flushLiveURLCache : Boolean = false; /** max nb of retries for Manifest Loading in case I/O errors are met, * 0, means no retry, error will be triggered automatically * -1 means infinite retry */ public static var manifestLoadMaxRetry : int = -1; /** manifestLoadMaxRetryTimeout * Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met. * Every fail on fragment request, player will exponentially increase the timeout to try again. * It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached. * * Default is 64000. */ public static var manifestLoadMaxRetryTimeout : Number = 64000; /** * If greater than 0, specifies the preferred bitrate. * If -1, and startFromLevel is not specified, automatic start level selection will be used. * This parameter, if set, will take priority over startFromLevel. */ public static var startFromBitrate : Number = -1; /** start level : * from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment) * -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate) */ public static var startFromLevel : Number = -1; /** seek level : * from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first. * -1 : automatic start level selection, keep previous level matching previous download bandwidth */ public static var seekFromLevel : Number = -1; /** use hardware video decoder : * it will set NetStream.useHardwareDecoder * refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder */ public static var useHardwareVideoDecoder : Boolean = false; /** * Defines whether INFO level log messages will will appear in the console * Default is true. */ public static var logInfo : Boolean = true; /** * Defines whether DEBUG level log messages will will appear in the console * Default is false. */ public static var logDebug : Boolean = false; /** * Defines whether DEBUG2 level log messages will will appear in the console * Default is false. */ public static var logDebug2 : Boolean = false; /** * Defines whether WARN level log messages will will appear in the console * Default is true. */ public static var logWarn : Boolean = true; /** * Defines whether ERROR level log messages will will appear in the console * Default is true. */ public static var logError : Boolean = true; } }
set fragment/key max retry to 3 related to #262
set fragment/key max retry to 3 related to #262
ActionScript
mpl-2.0
Corey600/flashls,fixedmachine/flashls,suuhas/flashls,jlacivita/flashls,clappr/flashls,aevange/flashls,NicolasSiver/flashls,clappr/flashls,suuhas/flashls,thdtjsdn/flashls,vidible/vdb-flashls,Corey600/flashls,neilrackett/flashls,loungelogic/flashls,NicolasSiver/flashls,Boxie5/flashls,JulianPena/flashls,neilrackett/flashls,dighan/flashls,JulianPena/flashls,fixedmachine/flashls,Peer5/flashls,aevange/flashls,Peer5/flashls,dighan/flashls,aevange/flashls,aevange/flashls,vidible/vdb-flashls,codex-corp/flashls,mangui/flashls,hola/flashls,codex-corp/flashls,mangui/flashls,Boxie5/flashls,hola/flashls,loungelogic/flashls,tedconf/flashls,Peer5/flashls,Peer5/flashls,thdtjsdn/flashls,suuhas/flashls,suuhas/flashls,tedconf/flashls,jlacivita/flashls
27b867cd16c75d3bb3d56bcd170fcafb5bc7e4b4
plugins/nielsenVideoCensusPlugin/src/nielsenVideoCensusPluginCode.as
plugins/nielsenVideoCensusPlugin/src/nielsenVideoCensusPluginCode.as
package { import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.plugin.IPlugin; import com.kaltura.kdpfl.plugin.IPluginFactory; import com.kaltura.kdpfl.plugin.component.NielsenVideoCensusMediator; import com.yahoo.astra.fl.controls.AbstractButtonRow; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.utils.Dictionary; import flash.utils.Timer; import org.puremvc.as3.interfaces.IFacade; public dynamic class nielsenVideoCensusPluginCode extends Sprite implements IPlugin { private var _nielsenMediator:NielsenVideoCensusMediator; private var _customEvents : Array; public function set customEvents(val:String):void{ _customEvents = val.split(","); } public var requestMethod : String = "queryString"; //ads (st,a for ads or st,c for content streams) public var c3 : String; //cookie check (cc=1) public var cc : String; //Show name (encoded) public var cg : String; public var clientId: String; public var videoCensusId:String; //video title (encoded dav0-encoded title) public var tl : String; public var lp : String; public var ls : String; public var serverUrl:String; private var _facade:IFacade; private var _eventData:Object; private var _paramsMap:Object = {videoCensusId:"C6", clientId:"CI", cg:"CG", tl:"TL", lp:"LP", ls:"LS", cc:"CC", rnd:"RND", c3:"C3"}; public function nielsenVideoCensusPluginCode() { super(); } public function initializePlugin(facade:IFacade):void { _facade = facade; _nielsenMediator = new NielsenVideoCensusMediator(_customEvents); _nielsenMediator.eventDispatcher.addEventListener(NielsenVideoCensusMediator.DISPATCH_BEACON, onBeacon); //_nielsenMediator.eventDispatcher.addEventListener(NielsenVideoCensusMediator.AD_START, onAdStart); facade.registerMediator(_nielsenMediator); } /** * Do nothing. * No implementation required for this interface method on this plugin. * @param styleName * @param setSkinSize */ public function setSkin(styleName:String, setSkinSize:Boolean = false):void {} private var loader : URLLoader; private function onAdStart(e:Event):void{ onBeacon(); } private function onCuePoints(e:Event):void{_eventData = _nielsenMediator.eventData;} private function createQueryString(url:String, key:String, val:String):String{ url = url.concat(key,"=",val,"&"); return url; } public function onBeacon(e:Event=null):void{ var url : String = (serverUrl)?serverUrl+"cgi-bin/m":"http://secure-us.imrworldwide.com/cgi-bin/m"; var vars : URLVariables = new URLVariables(); loader = new URLLoader(); url += "?"; for(var s:String in this) if(s.indexOf("c") == 0 && s.length == 2){ url = createQueryString(url,s,this[s]); } //CC - Cookie check. Hard coded to cc=1 url=createQueryString(url,_paramsMap.cc,"1"); //TL -Video title. Should be prefixed by “dav0-“. Percent (%) encode the TL value after the “dav0-“ previx. //Encoding prevents restricted charactrs from impacting any processing scripts if(tl)url=createQueryString(url,_paramsMap.tl,"dav0-"+tl); //CG - Show name or category name TV networks required to use program name here //The entire cg value should be percent (%) encoded if(cg)url=createQueryString(url,_paramsMap.cg,cg); //CI -Client ID provider by Nielsen if(clientId)url=createQueryString(url,_paramsMap.clientId,clientId); //C6 -Video Census ID if(videoCensusId)url=createQueryString(url,_paramsMap.videoCensusId,videoCensusId); //RND - Random number. Must be dynamic per event. Do not use scientific notation url=createQueryString(url,_paramsMap.rnd,getRndNumber()); //LP - Long play indicator //Four sub parameters: //1. Short form/long form override. The publisher can explicitly state the this is a short form or long form clip. If set to SF then parameters 2 and 4 will be ignored. //2. Current segment/chapter number. Set to 0 if not known //3. Length in seconds of this segment/chapter. Set to 0 if not known //4. Anticipated total number of segments/chapters for this episode. Set to 0 if not known // NOTE: total length can only be determined. unable to determine length of segments with current KDP3 libraries if(lp)url=createQueryString(url,_paramsMap.lp,getLongPlayIndicator()); if(c3)url=createQueryString(url,_paramsMap.c3,c3); //LS -Live stream indicator. One parameter: //1. Set to Y if this is a live stream //2. Set to N if this is a standard video on demand stream if(ls)url=createQueryString(url,_paramsMap.ls,getLiveStreamIndicator()); //C3 - Ad indicator. If this parameter is omitted then the stream will be assumed to be content. //url = createQueryString(url,_paramsMap.c3,getAdIndicator()); loader.addEventListener(Event.COMPLETE, onComplete); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError); var request : URLRequest = new URLRequest(url); request.data = vars; if(requestMethod == "post") request.method = URLRequestMethod.POST; loader.load(request); } private function getRndNumber():String{ return String(Math.random()).split(".")[1]; } //C3 - Ad indicator. If this parameter is omitted then the stream will be assumed to be content. private function getAdIndicator():String{ return "";//("st,c":"st,a"); } //LS -Live stream indicator. One parameter: //1. Set to Y if this is a live stream //2. Set to N if this is a standard video on demand stream private function getLiveStreamIndicator():String{ return (_facade.retrieveProxy("mediaProxy")["vo"]["isLive"])?"Y":"N"; } //LP - Long play indicator //Four sub parameters: //1. LF & SF Short form/long form override. The publisher can explicitly state this is a short form or long form clip. If set to SF then parameters 2 and 4 will be ignored. //2. LF Current segment/chapter number. Set to 0 if not known //3. LF & SF Length in seconds of this segment/chapter. Set to 0 if not known //4. LF Anticipated total number of segments/chapters for this episode. Set to 0 if not known //lp=LF,3,582,6 private function getLongPlayIndicator():String{ var value:String = ""; //get clip type value += lp.toUpperCase()+","; if(lp.toUpperCase() == "LF") value += _nielsenMediator.eventData["segmentId"]+","; value += _nielsenMediator.eventData["length"]; if(lp.toUpperCase() == "LF") value += ","+_nielsenMediator.eventData["totalSegments"]; return value; } private function decodeString():void{ } private function onComplete(e:Event):void{ loader.removeEventListener(Event.COMPLETE, onComplete); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); loader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError); } private function onSecurityError(e:SecurityErrorEvent):void{ trace("ERROR: NIELSEN Plugin - error sending beacon : "+e); } private function onIOError(e:IOErrorEvent):void{ trace("ERROR: NIELSEN Plugin - error sending beacon : "+e); } } }
package { import com.kaltura.kdpfl.model.SequenceProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.plugin.IPlugin; import com.kaltura.kdpfl.plugin.IPluginFactory; import com.kaltura.kdpfl.plugin.component.NielsenVideoCensusMediator; import com.yahoo.astra.fl.controls.AbstractButtonRow; import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLVariables; import flash.utils.Dictionary; import flash.utils.Timer; import org.puremvc.as3.interfaces.IFacade; public dynamic class nielsenVideoCensusPluginCode extends Sprite implements IPlugin { private var _nielsenMediator:NielsenVideoCensusMediator; private var _customEvents : Array; public function set customEvents(val:String):void{ _customEvents = val.split(","); } public var requestMethod : String = "queryString"; //ads (st,a for ads or st,c for content streams) public var c3 : String; //cookie check (cc=1) public var cc : String; //Show name (encoded) public var cg : String; public var clientId: String; public var videoCensusId:String; //video title (encoded dav0-encoded title) public var tl : String; public var lp : String; public var ls : String; public var serverUrl:String; public var c10 : String; public var c11 : String; private var _facade:IFacade; private var _eventData:Object; private var _paramsMap:Object = {videoCensusId:"C6", clientId:"CI", cg:"CG", tl:"TL", lp:"LP", ls:"LS", cc:"CC", rnd:"RND", c3:"C3", c10:"C10", c11:"C11"}; private var _sequenceProxy:SequenceProxy; public function nielsenVideoCensusPluginCode() { super(); } public function initializePlugin(facade:IFacade):void { _facade = facade; _nielsenMediator = new NielsenVideoCensusMediator(_customEvents); _nielsenMediator.eventDispatcher.addEventListener(NielsenVideoCensusMediator.DISPATCH_BEACON, onBeacon); //_nielsenMediator.eventDispatcher.addEventListener(NielsenVideoCensusMediator.AD_START, onAdStart); facade.registerMediator(_nielsenMediator); _sequenceProxy = facade.retrieveProxy(SequenceProxy.NAME) as SequenceProxy; } /** * Do nothing. * No implementation required for this interface method on this plugin. * @param styleName * @param setSkinSize */ public function setSkin(styleName:String, setSkinSize:Boolean = false):void {} private var loader : URLLoader; private function onAdStart(e:Event):void{ onBeacon(); } private function onCuePoints(e:Event):void{_eventData = _nielsenMediator.eventData;} private function createQueryString(url:String, key:String, val:String):String{ url = url.concat(key,"=",val,"&"); return url; } public function onBeacon(e:Event=null):void{ var url : String = (serverUrl)?serverUrl+"cgi-bin/m":"http://secure-us.imrworldwide.com/cgi-bin/m"; var vars : URLVariables = new URLVariables(); loader = new URLLoader(); url += "?"; for(var s:String in this) if(s.indexOf("c") == 0 && s.length == 2){ url = createQueryString(url,s,this[s]); } //CC - Cookie check. Hard coded to cc=1 url=createQueryString(url,_paramsMap.cc,"1"); //TL -Video title. Should be prefixed by “dav0-“. Percent (%) encode the TL value after the “dav0-“ previx. //Encoding prevents restricted charactrs from impacting any processing scripts if(tl) url=createQueryString(url,_paramsMap.tl,"dav0-"+tl); //CG - Show name or category name TV networks required to use program name here //The entire cg value should be percent (%) encoded if(cg) url=createQueryString(url,_paramsMap.cg,cg); //CI -Client ID provider by Nielsen if(clientId) url=createQueryString(url,_paramsMap.clientId,clientId); //C6 -Video Census ID if(videoCensusId) url=createQueryString(url,_paramsMap.videoCensusId,videoCensusId); //RND - Random number. Must be dynamic per event. Do not use scientific notation url=createQueryString(url,_paramsMap.rnd,getRndNumber()); //LP - Long play indicator //Four sub parameters: //1. Short form/long form override. The publisher can explicitly state the this is a short form or long form clip. If set to SF then parameters 2 and 4 will be ignored. //2. Current segment/chapter number. Set to 0 if not known //3. Length in seconds of this segment/chapter. Set to 0 if not known //4. Anticipated total number of segments/chapters for this episode. Set to 0 if not known // NOTE: total length can only be determined. unable to determine length of segments with current KDP3 libraries if(lp) url=createQueryString(url,_paramsMap.lp,getLongPlayIndicator()); if(c3) url=createQueryString(url,_paramsMap.c3,c3); //adid is sent only for ads. eidr is sent for both content and ads if(_sequenceProxy.vo.isInSequence && c10) url=createQueryString(url,_paramsMap.c10,c10); if(c11) url=createQueryString(url,_paramsMap.c11,c11); //LS -Live stream indicator. One parameter: //1. Set to Y if this is a live stream //2. Set to N if this is a standard video on demand stream if(ls) url=createQueryString(url,_paramsMap.ls,getLiveStreamIndicator()); //C3 - Ad indicator. If this parameter is omitted then the stream will be assumed to be content. //url = createQueryString(url,_paramsMap.c3,getAdIndicator()); loader.addEventListener(Event.COMPLETE, onComplete); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError); var request : URLRequest = new URLRequest(url); request.data = vars; if(requestMethod == "post") request.method = URLRequestMethod.POST; loader.load(request); } private function getRndNumber():String{ return String(Math.random()).split(".")[1]; } //C3 - Ad indicator. If this parameter is omitted then the stream will be assumed to be content. private function getAdIndicator():String{ return "";//("st,c":"st,a"); } //LS -Live stream indicator. One parameter: //1. Set to Y if this is a live stream //2. Set to N if this is a standard video on demand stream private function getLiveStreamIndicator():String{ return (_facade.retrieveProxy("mediaProxy")["vo"]["isLive"])?"Y":"N"; } //LP - Long play indicator //Four sub parameters: //1. LF & SF Short form/long form override. The publisher can explicitly state this is a short form or long form clip. If set to SF then parameters 2 and 4 will be ignored. //2. LF Current segment/chapter number. Set to 0 if not known //3. LF & SF Length in seconds of this segment/chapter. Set to 0 if not known //4. LF Anticipated total number of segments/chapters for this episode. Set to 0 if not known //lp=LF,3,582,6 private function getLongPlayIndicator():String{ var value:String = ""; //get clip type value += lp.toUpperCase()+","; if(lp.toUpperCase() == "LF") value += _nielsenMediator.eventData["segmentId"]+","; value += _nielsenMediator.eventData["length"]; if(lp.toUpperCase() == "LF") value += ","+_nielsenMediator.eventData["totalSegments"]; return value; } private function decodeString():void{ } private function onComplete(e:Event):void{ loader.removeEventListener(Event.COMPLETE, onComplete); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError); loader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError); } private function onSecurityError(e:SecurityErrorEvent):void{ trace("ERROR: NIELSEN Plugin - error sending beacon : "+e); } private function onIOError(e:IOErrorEvent):void{ trace("ERROR: NIELSEN Plugin - error sending beacon : "+e); } } }
add c10 and c11 params
qnd: add c10 and c11 params git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@92059 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
2c53a1d5bb87816d2a56d2c035b1e108deead865
src/aerys/minko/render/shader/compiler/graph/nodes/vertex/Instruction.as
src/aerys/minko/render/shader/compiler/graph/nodes/vertex/Instruction.as
package aerys.minko.render.shader.compiler.graph.nodes.vertex { import aerys.minko.render.shader.compiler.CRC32; import aerys.minko.render.shader.compiler.InstructionFlag; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.register.Components; import flash.utils.Dictionary; /** * @private * @author Romain Gilliotte */ public class Instruction extends AbstractNode { public static const MOV : uint = 0x00; public static const ADD : uint = 0x01; public static const SUB : uint = 0x02; public static const MUL : uint = 0x03; public static const DIV : uint = 0x04; public static const RCP : uint = 0x05; public static const MIN : uint = 0x06; public static const MAX : uint = 0x07; public static const FRC : uint = 0x08; public static const SQT : uint = 0x09; public static const RSQ : uint = 0x0a; public static const POW : uint = 0x0b; public static const LOG : uint = 0x0c; public static const EXP : uint = 0x0d; public static const NRM : uint = 0x0e; public static const SIN : uint = 0x0f; public static const COS : uint = 0x10; public static const CRS : uint = 0x11; public static const DP3 : uint = 0x12; public static const DP4 : uint = 0x13; public static const ABS : uint = 0x14; public static const NEG : uint = 0x15; public static const SAT : uint = 0x16; public static const M33 : uint = 0x17; public static const M44 : uint = 0x18; public static const M34 : uint = 0x19; public static const KIL : uint = 0x27; public static const TEX : uint = 0x28; public static const SGE : uint = 0x29; public static const SLT : uint = 0x2a; public static const SEQ : uint = 0x2c; public static const SNE : uint = 0x2d; public static const MUL_MAT33 : uint = 0x100; public static const MUL_MAT44 : uint = 0x101; public static const NAME : Dictionary = new Dictionary(); { NAME[MOV] = 'mov'; NAME[ADD] = 'add'; NAME[SUB] = 'sub'; NAME[MUL] = 'mul'; NAME[DIV] = 'div'; NAME[RCP] = 'rcp'; NAME[MIN] = 'min'; NAME[MAX] = 'max'; NAME[FRC] = 'frc'; NAME[SQT] = 'sqt'; NAME[RSQ] = 'rsq'; NAME[POW] = 'pow'; NAME[LOG] = 'log'; NAME[EXP] = 'exp'; NAME[NRM] = 'nrm'; NAME[SIN] = 'sin'; NAME[COS] = 'cos'; NAME[CRS] = 'crs'; NAME[DP3] = 'dp3'; NAME[DP4] = 'dp4'; NAME[ABS] = 'abs'; NAME[NEG] = 'neg'; NAME[SAT] = 'sat'; NAME[M33] = 'm33'; NAME[M44] = 'm44'; NAME[M34] = 'm34'; NAME[TEX] = 'tex'; NAME[KIL] = 'kil'; NAME[SGE] = 'sge'; NAME[SLT] = 'slt'; NAME[SEQ] = 'seq'; NAME[SNE] = 'sne'; NAME[MUL_MAT33] = 'mulMat33'; NAME[MUL_MAT44] = 'mulMat44'; } private static const FLAGS : Dictionary = new Dictionary(); { FLAGS[MOV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[ADD] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[SUB] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[MUL] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[DIV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[RCP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[MIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MAX] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[FRC] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[SQT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[RSQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[POW] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[LOG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[EXP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NRM] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SINGLE; FLAGS[SIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[COS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[CRS] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP3] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP4] = InstructionFlag.AVAILABLE_ALL; FLAGS[ABS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NEG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[SAT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[M33] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M44] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M34] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[KIL] = InstructionFlag.AVAILABLE_FS | InstructionFlag.SINGLE; FLAGS[TEX] = InstructionFlag.AVAILABLE_FS; FLAGS[SGE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SLT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SEQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[SNE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MUL_MAT33] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; FLAGS[MUL_MAT44] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; } private var _id : uint; public function get id() : uint { return _id; } public function get name() : String { return NAME[_id]; } public function get argument1() : AbstractNode { return getArgumentAt(0); } public function get argument2() : AbstractNode { return getArgumentAt(1); } public function get component1() : uint { return getComponentAt(0); } public function get component2() : uint { return getComponentAt(1); } public function set argument1(v : AbstractNode) : void { setArgumentAt(0, v); } public function set argument2(v : AbstractNode) : void { setArgumentAt(1, v); } public function set component1(v : uint) : void { setComponentAt(0, v); } public function set component2(v : uint) : void { setComponentAt(1, v); } public function get isAssociative() : Boolean { return (FLAGS[_id] & InstructionFlag.ASSOCIATIVE) != 0; } public function get isComponentWise() : Boolean { return (FLAGS[_id] & InstructionFlag.COMPONENT_WISE) != 0; } public function get isSingle() : Boolean { return (FLAGS[_id] & InstructionFlag.SINGLE) != 0; } public function get isLinear() : Boolean { return (FLAGS[_id] & InstructionFlag.LINEAR) != 0; } public function isCommutative() : Boolean { return (FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0; } public function Instruction(id : uint, argument1 : AbstractNode, argument2 : AbstractNode = null) { _id = id; var component1 : uint = id == MUL_MAT33 || id == MUL_MAT44 ? Components.createContinuous(0, 0, 4, 4) : Components.createContinuous(0, 0, argument1.size, argument1.size) var arguments : Vector.<AbstractNode> = new <AbstractNode>[argument1]; var components : Vector.<uint> = new <uint>[component1]; if (!isSingle) { var component2 : uint; if ((FLAGS[id] & InstructionFlag.SPECIAL_MATRIX) != 0) component2 = Components.createContinuous(0, 0, 4, 4); else if (id != TEX && id != MUL_MAT33 && id != MUL_MAT44) component2 = Components.createContinuous(0, 0, argument2.size, argument2.size); arguments.push(argument2); components.push(component2); } arguments.fixed = components.fixed = true; super(arguments, components); } override protected function computeHash() : uint { // commutative operations invert the arguments when computing the hash if arg1.crc > arg2.crc // that way, mul(a, b).hash == mul(b, a).hash var hashLeft : String = argument1.hash.toString(16) + '_' + component1.toString(16); if ((FLAGS[_id] & InstructionFlag.SINGLE) != 0) return CRC32.computeForString(hashLeft); else { var hashRight : String = argument2.hash.toString(16) + '_' + component2.toString(16); if ((FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0 && argument1.hash > argument2.hash) return CRC32.computeForString(hashRight + hashLeft); else return CRC32.computeForString(hashLeft + hashRight); } } override protected function computeSize() : uint { switch (_id) { case DP3: case DP4: return 1; case M33: case M34: case NRM: case CRS: return 3; case TEX: case M44: return 4; default: var nodeSize : uint; nodeSize = Components.getMaxWriteOffset(component1) - Components.getMinWriteOffset(component1) + 1; if (nodeSize > 4) throw new Error(); if (!isSingle) nodeSize = Math.max(nodeSize, Components.getMaxWriteOffset(component2) - Components.getMinWriteOffset(component2) + 1 ); if (nodeSize < 1) throw new Error(); if (nodeSize > 4) throw new Error(); return nodeSize; } } override public function toString() : String { return name; } override public function clone() : AbstractNode { var clone : Instruction; if (isSingle) { clone = new Instruction(_id, argument1); clone.component1 = component1; } else { clone = new Instruction(_id, argument1, argument2); clone.component1 = component1; clone.component2 = component2; } return clone; } } }
package aerys.minko.render.shader.compiler.graph.nodes.vertex { import aerys.minko.render.shader.compiler.CRC32; import aerys.minko.render.shader.compiler.InstructionFlag; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.register.Components; import flash.utils.Dictionary; /** * @private * @author Romain Gilliotte */ public class Instruction extends AbstractNode { public static const MOV : uint = 0x00; public static const ADD : uint = 0x01; public static const SUB : uint = 0x02; public static const MUL : uint = 0x03; public static const DIV : uint = 0x04; public static const RCP : uint = 0x05; public static const MIN : uint = 0x06; public static const MAX : uint = 0x07; public static const FRC : uint = 0x08; public static const SQT : uint = 0x09; public static const RSQ : uint = 0x0a; public static const POW : uint = 0x0b; public static const LOG : uint = 0x0c; public static const EXP : uint = 0x0d; public static const NRM : uint = 0x0e; public static const SIN : uint = 0x0f; public static const COS : uint = 0x10; public static const CRS : uint = 0x11; public static const DP3 : uint = 0x12; public static const DP4 : uint = 0x13; public static const ABS : uint = 0x14; public static const NEG : uint = 0x15; public static const SAT : uint = 0x16; public static const M33 : uint = 0x17; public static const M44 : uint = 0x18; public static const M34 : uint = 0x19; public static const KIL : uint = 0x27; public static const TEX : uint = 0x28; public static const SGE : uint = 0x29; public static const SLT : uint = 0x2a; public static const SEQ : uint = 0x2c; public static const SNE : uint = 0x2d; public static const MUL_MAT33 : uint = 0x100; public static const MUL_MAT44 : uint = 0x101; public static const NAME : Dictionary = new Dictionary(); { NAME[MOV] = 'mov'; NAME[ADD] = 'add'; NAME[SUB] = 'sub'; NAME[MUL] = 'mul'; NAME[DIV] = 'div'; NAME[RCP] = 'rcp'; NAME[MIN] = 'min'; NAME[MAX] = 'max'; NAME[FRC] = 'frc'; NAME[SQT] = 'sqt'; NAME[RSQ] = 'rsq'; NAME[POW] = 'pow'; NAME[LOG] = 'log'; NAME[EXP] = 'exp'; NAME[NRM] = 'nrm'; NAME[SIN] = 'sin'; NAME[COS] = 'cos'; NAME[CRS] = 'crs'; NAME[DP3] = 'dp3'; NAME[DP4] = 'dp4'; NAME[ABS] = 'abs'; NAME[NEG] = 'neg'; NAME[SAT] = 'sat'; NAME[M33] = 'm33'; NAME[M44] = 'm44'; NAME[M34] = 'm34'; NAME[TEX] = 'tex'; NAME[KIL] = 'kil'; NAME[SGE] = 'sge'; NAME[SLT] = 'slt'; NAME[SEQ] = 'seq'; NAME[SNE] = 'sne'; NAME[MUL_MAT33] = 'mulMat33'; NAME[MUL_MAT44] = 'mulMat44'; } private static const FLAGS : Dictionary = new Dictionary(); { FLAGS[MOV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[ADD] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[SUB] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[MUL] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[DIV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[RCP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[MIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MAX] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[FRC] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[SQT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[RSQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[POW] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[LOG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[EXP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NRM] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SINGLE; FLAGS[SIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[COS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[CRS] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP3] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP4] = InstructionFlag.AVAILABLE_ALL; FLAGS[ABS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NEG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[SAT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[M33] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M44] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M34] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[KIL] = InstructionFlag.AVAILABLE_FS | InstructionFlag.SINGLE; FLAGS[TEX] = InstructionFlag.AVAILABLE_FS; FLAGS[SGE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SLT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SEQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[SNE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MUL_MAT33] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; FLAGS[MUL_MAT44] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; } private var _id : uint; public function get id() : uint { return _id; } public function get name() : String { return NAME[_id]; } public function get argument1() : AbstractNode { return getArgumentAt(0); } public function get argument2() : AbstractNode { return getArgumentAt(1); } public function get component1() : uint { return getComponentAt(0); } public function get component2() : uint { return getComponentAt(1); } public function set argument1(v : AbstractNode) : void { setArgumentAt(0, v); } public function set argument2(v : AbstractNode) : void { setArgumentAt(1, v); } public function set component1(v : uint) : void { setComponentAt(0, v); } public function set component2(v : uint) : void { setComponentAt(1, v); } public function get isAssociative() : Boolean { return (FLAGS[_id] & InstructionFlag.ASSOCIATIVE) != 0; } public function get isComponentWise() : Boolean { return (FLAGS[_id] & InstructionFlag.COMPONENT_WISE) != 0; } public function get isSingle() : Boolean { return (FLAGS[_id] & InstructionFlag.SINGLE) != 0; } public function get isLinear() : Boolean { return (FLAGS[_id] & InstructionFlag.LINEAR) != 0; } public function isCommutative() : Boolean { return (FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0; } public function Instruction(id : uint, argument1 : AbstractNode, argument2 : AbstractNode = null) { _id = id; var component1 : uint = id == MUL_MAT33 || id == MUL_MAT44 ? Components.createContinuous(0, 0, 4, 4) : Components.createContinuous(0, 0, argument1.size, argument1.size) var arguments : Vector.<AbstractNode> = new <AbstractNode>[argument1]; var components : Vector.<uint> = new <uint>[component1]; if (!isSingle) { var component2 : uint; if ((FLAGS[id] & InstructionFlag.SPECIAL_MATRIX) != 0) component2 = Components.createContinuous(0, 0, 4, 4); else if (id != TEX && id != MUL_MAT33 && id != MUL_MAT44) component2 = Components.createContinuous(0, 0, argument2.size, argument2.size); arguments.push(argument2); components.push(component2); } arguments.fixed = components.fixed = true; super(arguments, components); } override protected function computeHash() : uint { // commutative operations invert the arguments when computing the hash if arg1.crc > arg2.crc // that way, mul(a, b).hash == mul(b, a).hash var hashLeft : String = id.toFixed(16) + '_' + argument1.hash.toString(16) + '_' + component1.toString(16); if ((FLAGS[_id] & InstructionFlag.SINGLE) != 0) return CRC32.computeForString(hashLeft); else { var hashRight : String = argument2.hash.toString(16) + '_' + component2.toString(16); if ((FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0 && argument1.hash > argument2.hash) return CRC32.computeForString(hashRight + hashLeft); else return CRC32.computeForString(hashLeft + hashRight); } } override protected function computeSize() : uint { switch (_id) { case DP3: case DP4: return 1; case M33: case M34: case NRM: case CRS: return 3; case TEX: case M44: return 4; default: var nodeSize : uint; nodeSize = Components.getMaxWriteOffset(component1) - Components.getMinWriteOffset(component1) + 1; if (nodeSize > 4) throw new Error(); if (!isSingle) nodeSize = Math.max(nodeSize, Components.getMaxWriteOffset(component2) - Components.getMinWriteOffset(component2) + 1 ); if (nodeSize < 1) throw new Error(); if (nodeSize > 4) throw new Error(); return nodeSize; } } override public function toString() : String { return name; } override public function clone() : AbstractNode { var clone : Instruction; if (isSingle) { clone = new Instruction(_id, argument1); clone.component1 = component1; } else { clone = new Instruction(_id, argument1, argument2); clone.component1 = component1; clone.component2 = component2; } return clone; } } }
fix Instruction.computeHash() to prefix the string hash with the instruction id and avoid instructions with the same arguments being mixed up
fix Instruction.computeHash() to prefix the string hash with the instruction id and avoid instructions with the same arguments being mixed up
ActionScript
mit
aerys/minko-as3
79c56302b1cff9df81eecb0184c79a99ffb393f5
dolly-framework/src/main/actionscript/dolly/Cloner.as
dolly-framework/src/main/actionscript/dolly/Cloner.as
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.as3commons.reflect.Variable; use namespace dolly_internal; public class Cloner { private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean { return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE)); } private static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean { return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() && (skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE)); } dolly_internal static function getWritableFieldsOfType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); var variable:Variable; var accessor:Accessor; for each(variable in type.variables) { if (isVariableCloneable(variable)) { result.push(variable); } } for each(accessor in type.accessors) { if (isAccessorCloneable(accessor)) { result.push(accessor); } } return result; } dolly_internal static function findAllCloneableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = getWritableFieldsOfType(type); const superclassNames:Array = type.extendsClasses; for each(var superclassName:String in superclassNames) { var superclassType:Type = Type.forName(superclassName); var superclassWritableFields:Vector.<Field> = getWritableFieldsOfType(superclassType); if (superclassWritableFields.length > 0) { result.concat(superclassWritableFields); } } return result; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const clone:* = new (type.clazz)(); // Find all public writable fields in a hierarchy of a source object // and assign their values to a clone object. const fieldsToClone:Vector.<Field> = findAllCloneableFieldsForType(type); var name:String; for each(var field:Field in fieldsToClone) { name = field.name; clone[name] = source[name]; } return clone; } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.fields) { if (field.isStatic) { continue; } if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } const clone:* = new (type.clazz)(); // Find all public writable fields in a hierarchy of a source object // and assign their values to a clone object. const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); var name:String; for each(var field:Field in fieldsToClone) { name = field.name; clone[name] = source[name]; } return clone; } } }
Optimize cloning performance.
Optimize cloning performance.
ActionScript
mit
Yarovoy/dolly
b32da1e516fe5738f2e99cd2263f26150e410907
frameworks/projects/framework/src/mx/core/FlexVersion.as
frameworks/projects/framework/src/mx/core/FlexVersion.as
//////////////////////////////////////////////////////////////////////////////// // // 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.core { import mx.resources.ResourceManager; [ResourceBundle("core")] /** * This class controls the backward-compatibility of the framework. * With every new release, some aspects of the framework such as behaviors, * styles, and default settings, are changed which can affect your application. * By setting the <code>compatibilityVersion</code> property, the behavior can be changed * to match previous releases. * This is a 'global' flag; you cannot apply one version to one component or group of components * and a different version to another component or group of components. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class FlexVersion { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The current released version of the Flex SDK, encoded as a uint. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const CURRENT_VERSION:uint = 0x04110000; /** * The <code>compatibilityVersion</code> value of Flex 4.11, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.11 */ public static const VERSION_4_11:uint = 0x04110000; /** * The <code>compatibilityVersion</code> value of Flex 4.10, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.10 */ public static const VERSION_4_10:uint = 0x04100000; /** * The <code>compatibilityVersion</code> value of Flex 4.9, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.9 */ public static const VERSION_4_9:uint = 0x04090000; /** * The <code>compatibilityVersion</code> value of Flex 4.8, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.8 */ public static const VERSION_4_8:uint = 0x04080000; /** * The <code>compatibilityVersion</code> value of Flex 4.6, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public static const VERSION_4_6:uint = 0x04060000; /** * The <code>compatibilityVersion</code> value of Flex 4.5, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_4_5:uint = 0x04050000; /** * The <code>compatibilityVersion</code> value of Flex 4.0, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_4_0:uint = 0x04000000; /** * The <code>compatibilityVersion</code> value of Flex 3.0, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_3_0:uint = 0x03000000; /** * The <code>compatibilityVersion</code> value of Flex 2.0.1, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_2_0_1:uint = 0x02000001; /** * The <code>compatibilityVersion</code> value of Flex 2.0, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_2_0:uint = 0x02000000; /** * A String passed as a parameter * to the <code>compatibilityErrorFunction()</code> method * if the compatibility version has already been set. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_ALREADY_SET:String = "versionAlreadySet"; // Also used as resource string, so be careful changing it. /** * A String passed as a parameter * to the <code>compatibilityErrorFunction()</code> method * if the compatibility version has already been read. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_ALREADY_READ:String = "versionAlreadyRead"; // Also used as resource string, so be careful changing it. //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- //---------------------------------- // compatibilityErrorFunction //---------------------------------- /** * @private * Storage for the compatibilityErrorFunction property. */ private static var _compatibilityErrorFunction:Function; /** * A function that gets called when the compatibility version * is set more than once, or set after it has been read. * If this function is not set, the SDK throws an error. * If set, File calls this function, but it is * up to the developer to decide how to handle the call. * This function will also be called if the function is set more than once. * The function takes two parameters: the first is a <code>uint</code> * which is the version that was attempted to be set; the second * is a string that is the reason it failed, either * <code>VERSION_ALREADY_SET</code> or <code>VERSION_ALREADY_READ</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get compatibilityErrorFunction():Function { return _compatibilityErrorFunction; } /** * @private */ public static function set compatibilityErrorFunction(value:Function):void { _compatibilityErrorFunction = value; } //---------------------------------- // compatibilityVersion //---------------------------------- /** * @private * Storage for the compatibilityVersion property. */ private static var _compatibilityVersion:uint = CURRENT_VERSION; /** * @private */ private static var compatibilityVersionChanged:Boolean = false; /** * @private */ private static var compatibilityVersionRead:Boolean = false; /** * The current version that the framework maintains compatibility for. * This defaults to <code>CURRENT_VERSION</code>. * It can be changed only once; changing it a second time * results in a call to the <code>compatibilityErrorFunction()</code> method * if it exists, or results in a runtime error. * Changing it after the <code>compatibilityVersion</code> property has been read results in an error * because code that is dependent on the version has already run. * There are no notifications; the assumption is that this is set only once, and this it is set * early enough that no code that depends on it has run yet. * * @default FlexVersion.CURRENT_VERSION * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get compatibilityVersion():uint { compatibilityVersionRead = true; return _compatibilityVersion; } /** * @private */ public static function set compatibilityVersion(value:uint):void { if (value == _compatibilityVersion) return; var s:String; if (compatibilityVersionChanged) { if (compatibilityErrorFunction == null) { s = ResourceManager.getInstance().getString( "core", VERSION_ALREADY_SET); throw new Error(s); } else compatibilityErrorFunction(value, VERSION_ALREADY_SET); } if (compatibilityVersionRead) { if (compatibilityErrorFunction == null) { s = ResourceManager.getInstance().getString( "core", VERSION_ALREADY_READ); throw new Error(s); } else compatibilityErrorFunction(value, VERSION_ALREADY_READ); } _compatibilityVersion = value; compatibilityVersionChanged = true; } //---------------------------------- // compatibilityVersionString //---------------------------------- /** * The compatibility version, as a string of the form "X.X.X". * This is a pass-through to the <code>compatibilityVersion</code> * property, which converts the number to and from a more * human-readable String version. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get compatibilityVersionString():String { var major:uint = (compatibilityVersion >> 24) & 0xFF; var minor:uint = (compatibilityVersion >> 16) & 0xFF; var update:uint = compatibilityVersion & 0xFFFF; return major.toString() + "." + minor.toString() + "." + update.toString(); } /** * @private */ public static function set compatibilityVersionString(value:String):void { var pieces:Array = value.split("."); var major:uint = parseInt(pieces[0]); var minor:uint = parseInt(pieces[1]); var update:uint = parseInt(pieces[2]); compatibilityVersion = (major << 24) + (minor << 16) + update; } /** * @private * A back door for changing the compatibility version. * This is provided for Flash Builder's Design View, * which needs to be able to change compatibility mode. * In general, we won't support late changes to compatibility, * because the framework won't watch for changes. * Design View will need to set this early during initialization. */ mx_internal static function changeCompatibilityVersionString( value:String):void { var pieces:Array = value.split("."); var major:uint = parseInt(pieces[0]); var minor:uint = parseInt(pieces[1]); var update:uint = parseInt(pieces[2]); _compatibilityVersion = (major << 24) + (minor << 16) + update; } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.core { import mx.resources.ResourceManager; [ResourceBundle("core")] /** * This class controls the backward-compatibility of the framework. * With every new release, some aspects of the framework such as behaviors, * styles, and default settings, are changed which can affect your application. * By setting the <code>compatibilityVersion</code> property, the behavior can be changed * to match previous releases. * This is a 'global' flag; you cannot apply one version to one component or group of components * and a different version to another component or group of components. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public class FlexVersion { include "../core/Version.as"; //-------------------------------------------------------------------------- // // Class constants // //-------------------------------------------------------------------------- /** * The current released version of the Flex SDK, encoded as a uint. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const CURRENT_VERSION:uint = 0x040B0000; /** * The <code>compatibilityVersion</code> value of Flex 4.11, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.11 */ public static const VERSION_4_11:uint = 0x040B0000; /** * The <code>compatibilityVersion</code> value of Flex 4.10, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.10 */ public static const VERSION_4_10:uint = 0x040A0000; /** * The <code>compatibilityVersion</code> value of Flex 4.9, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.9 */ public static const VERSION_4_9:uint = 0x04090000; /** * The <code>compatibilityVersion</code> value of Flex 4.8, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Apache Flex 4.8 */ public static const VERSION_4_8:uint = 0x04080000; /** * The <code>compatibilityVersion</code> value of Flex 4.6, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 11 * @playerversion AIR 3 * @productversion Flex 4.6 */ public static const VERSION_4_6:uint = 0x04060000; /** * The <code>compatibilityVersion</code> value of Flex 4.5, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_4_5:uint = 0x04050000; /** * The <code>compatibilityVersion</code> value of Flex 4.0, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_4_0:uint = 0x04000000; /** * The <code>compatibilityVersion</code> value of Flex 3.0, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_3_0:uint = 0x03000000; /** * The <code>compatibilityVersion</code> value of Flex 2.0.1, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_2_0_1:uint = 0x02000001; /** * The <code>compatibilityVersion</code> value of Flex 2.0, * encoded numerically as a <code>uint</code>. * Code can compare this constant against * the <code>compatibilityVersion</code> * to implement version-specific behavior. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_2_0:uint = 0x02000000; /** * A String passed as a parameter * to the <code>compatibilityErrorFunction()</code> method * if the compatibility version has already been set. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_ALREADY_SET:String = "versionAlreadySet"; // Also used as resource string, so be careful changing it. /** * A String passed as a parameter * to the <code>compatibilityErrorFunction()</code> method * if the compatibility version has already been read. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static const VERSION_ALREADY_READ:String = "versionAlreadyRead"; // Also used as resource string, so be careful changing it. //-------------------------------------------------------------------------- // // Class properties // //-------------------------------------------------------------------------- //---------------------------------- // compatibilityErrorFunction //---------------------------------- /** * @private * Storage for the compatibilityErrorFunction property. */ private static var _compatibilityErrorFunction:Function; /** * A function that gets called when the compatibility version * is set more than once, or set after it has been read. * If this function is not set, the SDK throws an error. * If set, File calls this function, but it is * up to the developer to decide how to handle the call. * This function will also be called if the function is set more than once. * The function takes two parameters: the first is a <code>uint</code> * which is the version that was attempted to be set; the second * is a string that is the reason it failed, either * <code>VERSION_ALREADY_SET</code> or <code>VERSION_ALREADY_READ</code>. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get compatibilityErrorFunction():Function { return _compatibilityErrorFunction; } /** * @private */ public static function set compatibilityErrorFunction(value:Function):void { _compatibilityErrorFunction = value; } //---------------------------------- // compatibilityVersion //---------------------------------- /** * @private * Storage for the compatibilityVersion property. */ private static var _compatibilityVersion:uint = CURRENT_VERSION; /** * @private */ private static var compatibilityVersionChanged:Boolean = false; /** * @private */ private static var compatibilityVersionRead:Boolean = false; /** * The current version that the framework maintains compatibility for. * This defaults to <code>CURRENT_VERSION</code>. * It can be changed only once; changing it a second time * results in a call to the <code>compatibilityErrorFunction()</code> method * if it exists, or results in a runtime error. * Changing it after the <code>compatibilityVersion</code> property has been read results in an error * because code that is dependent on the version has already run. * There are no notifications; the assumption is that this is set only once, and this it is set * early enough that no code that depends on it has run yet. * * @default FlexVersion.CURRENT_VERSION * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get compatibilityVersion():uint { compatibilityVersionRead = true; return _compatibilityVersion; } /** * @private */ public static function set compatibilityVersion(value:uint):void { if (value == _compatibilityVersion) return; var s:String; if (compatibilityVersionChanged) { if (compatibilityErrorFunction == null) { s = ResourceManager.getInstance().getString( "core", VERSION_ALREADY_SET); throw new Error(s); } else compatibilityErrorFunction(value, VERSION_ALREADY_SET); } if (compatibilityVersionRead) { if (compatibilityErrorFunction == null) { s = ResourceManager.getInstance().getString( "core", VERSION_ALREADY_READ); throw new Error(s); } else compatibilityErrorFunction(value, VERSION_ALREADY_READ); } _compatibilityVersion = value; compatibilityVersionChanged = true; } //---------------------------------- // compatibilityVersionString //---------------------------------- /** * The compatibility version, as a string of the form "X.X.X". * This is a pass-through to the <code>compatibilityVersion</code> * property, which converts the number to and from a more * human-readable String version. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public static function get compatibilityVersionString():String { var major:uint = (compatibilityVersion >> 24) & 0xFF; var minor:uint = (compatibilityVersion >> 16) & 0xFF; var update:uint = compatibilityVersion & 0xFFFF; return major.toString() + "." + minor.toString() + "." + update.toString(); } /** * @private */ public static function set compatibilityVersionString(value:String):void { var pieces:Array = value.split("."); var major:uint = parseInt(pieces[0]); var minor:uint = parseInt(pieces[1]); var update:uint = parseInt(pieces[2]); compatibilityVersion = (major << 24) + (minor << 16) + update; } /** * @private * A back door for changing the compatibility version. * This is provided for Flash Builder's Design View, * which needs to be able to change compatibility mode. * In general, we won't support late changes to compatibility, * because the framework won't watch for changes. * Design View will need to set this early during initialization. */ mx_internal static function changeCompatibilityVersionString( value:String):void { var pieces:Array = value.split("."); var major:uint = parseInt(pieces[0]); var minor:uint = parseInt(pieces[1]); var update:uint = parseInt(pieces[2]); _compatibilityVersion = (major << 24) + (minor << 16) + update; } } }
Fix internal version numbers
Fix internal version numbers
ActionScript
apache-2.0
shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk
368296eef71ca044cd1681008236b4482773957b
src/battlecode/client/viewer/render/ExplosionAnimation.as
src/battlecode/client/viewer/render/ExplosionAnimation.as
package battlecode.client.viewer.render { import battlecode.common.RobotType; import mx.controls.Image; import mx.core.UIComponent; public class ExplosionAnimation extends UIComponent implements DrawObject { private var image:Image; private var robotType:String; private var round:int = 0; private var exploding:Boolean = false; public function ExplosionAnimation(robotType:String) { this.image = new Image(); this.robotType = robotType; this.addChild(image); } public function explode():void { exploding = true; } public function draw(force:Boolean = false):void { if (!RenderConfiguration.showExplosions() || !exploding) { this.image.source = null; return; } // TODO big missile explosion animations? var w:Number = RenderConfiguration.getGridSize(); // * (robotType == RobotType.MISSILE ? 3 : 1); var imageSource:Class = getExplosionImage(); this.image.source = new imageSource(); this.image.width = w; this.image.height = w; this.image.x = -w / 2; this.image.y = -w / 2; } public function clone():DrawObject { var anim:ExplosionAnimation = new ExplosionAnimation(robotType); anim.round = round; anim.exploding = exploding; return anim; } public function getRound():uint { return round; } public function isExploding():Boolean { return exploding; } public function isAlive():Boolean { return round < 8 && exploding; } public function updateRound():void { if (exploding) round++; } private function getExplosionImage():Class { switch (round) { case 0: return ImageAssets.EXPLODE_1; case 1: return ImageAssets.EXPLODE_2; case 2: return ImageAssets.EXPLODE_3; case 3: return ImageAssets.EXPLODE_4; case 4: return ImageAssets.EXPLODE_5; case 5: return ImageAssets.EXPLODE_6; case 6: return ImageAssets.EXPLODE_7; case 7: return ImageAssets.EXPLODE_8; default: return ImageAssets.EXPLODE_8; } } } }
package battlecode.client.viewer.render { import battlecode.common.RobotType; import mx.controls.Image; import mx.core.UIComponent; public class ExplosionAnimation extends UIComponent implements DrawObject { private var image:Image; private var robotType:String; private var round:int = 0; private var exploding:Boolean = false; public function ExplosionAnimation(robotType:String) { this.image = new Image(); this.robotType = robotType; this.addChild(image); } public function explode():void { exploding = true; } public function draw(force:Boolean = false):void { if (!RenderConfiguration.showExplosions() || !exploding) { this.image.source = null; return; } // TODO big missile explosion animations? var w:Number = RenderConfiguration.getGridSize(); // * (robotType == RobotType.MISSILE ? 3 : 1); var imageSource:Class = getExplosionImage(); this.image.source = new imageSource(); this.image.width = w; this.image.height = w; this.image.x = -w / 2; this.image.y = -w / 2; } public function clone():DrawObject { var anim:ExplosionAnimation = new ExplosionAnimation(robotType); anim.round = round; anim.exploding = exploding; return anim; } public function getRound():uint { return round; } public function isExploding():Boolean { return exploding; } public function isAlive():Boolean { return round < 8 && exploding; } public function updateRound():void { if (exploding) round++; } private function getExplosionImage():Class { if (round < 8) { return ImageAssets["EXPLODE_" + (round + 1)]; } else { return ImageAssets.EXPLODE_8; } } } }
simplify explision animations
simplify explision animations
ActionScript
mit
trun/battlecode-webclient
02bd0813004d39ba505a715fb440dbccf4764aab
src/battlecode/client/viewer/render/DrawHUD.as
src/battlecode/client/viewer/render/DrawHUD.as
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.RobotType; import battlecode.common.Team; import battlecode.events.MatchEvent; import battlecode.serial.Match; import flash.filters.DropShadowFilter; import mx.containers.Canvas; import mx.containers.VBox; import mx.controls.Label; import mx.controls.Spacer; import mx.events.ResizeEvent; import mx.formatters.NumberFormatter; public class DrawHUD extends VBox { private var controller:MatchController; private var team:String; private var pointLabel:Label; private var hqBox:DrawHUDHQ; private var towerBoxes:Object; // id -> DrawHUDTower private var buildingLabel:Label; private var buildingBoxes:Array; private var unitLabel:Label; private var unitBoxes:Array; private var winMarkerCanvas:Canvas; private var lastRound:uint = 0; private var maxTowers:uint = 0; private var formatter:NumberFormatter; public function DrawHUD(controller:MatchController, team:String) { this.controller = controller; this.team = team; controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); addEventListener(ResizeEvent.RESIZE, onResize); width = 180; percentHeight = 100; autoLayout = false; horizontalScrollPolicy = "off"; verticalScrollPolicy = "off"; pointLabel = new Label(); pointLabel.width = width; pointLabel.height = 30; pointLabel.x = 0; pointLabel.y = 10; pointLabel.filters = [ new DropShadowFilter(3, 45, 0x333333, 1, 2, 2) ]; pointLabel.setStyle("color", team == Team.A ? 0xFF6666 : 0x9999FF); pointLabel.setStyle("fontSize", 24); pointLabel.setStyle("fontWeight", "bold"); pointLabel.setStyle("textAlign", "center"); pointLabel.setStyle("fontFamily", "Courier New"); winMarkerCanvas = new Canvas(); winMarkerCanvas.width = width; winMarkerCanvas.height = 40; addChild(pointLabel); hqBox = new DrawHUDHQ(); addChild(hqBox); buildingLabel = new Label(); buildingLabel.width = width; buildingLabel.height = 30; buildingLabel.setStyle("color", 0xFFFFFF); buildingLabel.setStyle("fontSize", 18); buildingLabel.setStyle("textAlign", "center"); buildingLabel.setStyle("fontFamily", "Courier New"); buildingLabel.text = "Buildings"; addChild(buildingLabel); unitLabel = new Label(); unitLabel.width = width; unitLabel.height = 30; unitLabel.setStyle("color", 0xFFFFFF); unitLabel.setStyle("fontSize", 18); unitLabel.setStyle("textAlign", "center"); unitLabel.setStyle("fontFamily", "Courier New"); unitLabel.text = "Units"; addChild(unitLabel); towerBoxes = {}; buildingBoxes = new Array(); for each (var building:String in RobotType.buildings()) { var buildingBox:DrawHUDUnit = new DrawHUDUnit(building, team); buildingBoxes.push(buildingBox); addChild(buildingBox); } unitBoxes = new Array(); for each (var unit:String in RobotType.units()) { var unitBox:DrawHUDUnit = new DrawHUDUnit(unit, team); unitBoxes.push(unitBox); addChild(unitBox); } formatter = new NumberFormatter(); formatter.rounding = "down"; formatter.precision = 0; addChild(winMarkerCanvas); repositionWinMarkers(); resizeHQBox(); drawTowerBoxes(); drawBuildingCounts(); drawUnitCounts(); } private function onRoundChange(e:MatchEvent):void { var points:Number = controller.currentState.getPoints(team); pointLabel.text = formatter.format(points); if (e.currentRound <= lastRound) { hqBox.removeRobot(); drawWinMarkers(); } lastRound = e.currentRound; var hq:DrawRobot = controller.currentState.getHQ(team); if (hq && hq.isAlive()) { hqBox.setRobot(hq); hq.draw(); } var towers:Object = controller.currentState.getTowers(team); var towerCount:uint = 0; for each (var tower:DrawRobot in towers) { if (!towerBoxes[tower.getRobotID()]) { towerBoxes[tower.getRobotID()] = new DrawHUDTower(); addChild(towerBoxes[tower.getRobotID()]); } towerBoxes[tower.getRobotID()].setRobot(tower); tower.draw(); towerCount++; } maxTowers = Math.max(maxTowers, towerCount); drawTowerBoxes(); for each (var buildingBox:DrawHUDUnit in buildingBoxes) { buildingBox.setCount(controller.currentState.getUnitCount(buildingBox.getType(), team)); } drawBuildingCounts(); for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.setCount(controller.currentState.getUnitCount(unitBox.getType(), team)); } drawUnitCounts(); if (controller.currentRound == controller.match.getRounds()) { drawWinMarkers(); } } private function onMatchChange(e:MatchEvent):void { pointLabel.text = "0"; hqBox.removeRobot(); // clear tower boxes for (var a:String in towerBoxes) { towerBoxes[a].removeRobot(); if (towerBoxes[a].parent == this) { removeChild(towerBoxes[a]); } } towerBoxes = {}; maxTowers = 0; drawWinMarkers(); } private function resizeHQBox():void { var boxSize:Number = Math.min(100, (height - 70 - pointLabel.height - winMarkerCanvas.height) - 20); hqBox.resize(boxSize); hqBox.x = (width - boxSize) / 2; hqBox.y = 50; } private function drawTowerBoxes():void { var top:Number = hqBox.height + hqBox.y + 10; var i:uint = 0; for (var a:String in towerBoxes) { var towerBox:DrawHUDTower = towerBoxes[a]; towerBox.x = (width - towerBox.width * 3) / 2 + (i % 3) * towerBox.width; towerBox.y = ((towerBox.height + 10) * Math.floor(i / 3)) + top; i++; } } private function drawBuildingCounts():void { var towerBoxTop:Number = Math.ceil(maxTowers / 3.0) * (DrawHUDTower.HEIGHT + 10); var top:Number = hqBox.height + hqBox.y + towerBoxTop + 10; buildingLabel.y = top + 10; top = buildingLabel.height + buildingLabel.y + 5; var i:uint = 0; for each (var buildingBox:DrawHUDUnit in buildingBoxes) { buildingBox.x = (width - buildingBox.width * 3) / 2 + (i % 3) * buildingBox.width; buildingBox.y = ((buildingBox.height + 10) * Math.floor(i / 3)) + top; if (buildingBox.getCount() > 0) { buildingBox.visible = true; i++; } else { buildingBox.visible = false; } } } private function drawUnitCounts():void { var topBuildingBox:DrawHUDUnit = buildingBoxes[buildingBoxes.length-1]; for (var j:int = buildingBoxes.length - 1; j >= 0; j--) { topBuildingBox = buildingBoxes[j]; if (topBuildingBox.visible) { break; } } var top:Number = topBuildingBox.height + topBuildingBox.y + 10; unitLabel.y = top + 10; top = unitLabel.height + unitLabel.y + 5; var i:uint = 0; for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.x = (width - unitBox.width * 3) / 2 + (i % 3) * unitBox.width; unitBox.y = ((unitBox.height + 10) * Math.floor(i / 3)) + top; if (unitBox.getCount() > 0) { unitBox.visible = true; i++; } else { unitBox.visible = false; } } } private function drawWinMarkers():void { var matches:Vector.<Match> = controller.getMatches(); winMarkerCanvas.graphics.clear(); var i:uint, wins:uint = 0; var numMatches:int = (controller.currentRound == controller.match.getRounds()) ? controller.currentMatch : controller.currentMatch - 1; for (i = 0; i <= numMatches; i++) { if (matches[i].getWinner() == team) { var x:Number = (winMarkerCanvas.height - 5) / 2 + wins * winMarkerCanvas.height + 30; var y:Number = (winMarkerCanvas.height - 5) / 2; var r:Number = (winMarkerCanvas.height - 5) / 2; winMarkerCanvas.graphics.lineStyle(2, 0x000000); winMarkerCanvas.graphics.beginFill((team == Team.A) ? 0xFF6666 : 0x9999FF); winMarkerCanvas.graphics.drawCircle(x, y, r); winMarkerCanvas.graphics.endFill(); wins++; } } } private function repositionWinMarkers():void { winMarkerCanvas.y = height - winMarkerCanvas.height - 20; } private function onResize(e:ResizeEvent):void { repositionWinMarkers(); resizeHQBox(); drawTowerBoxes(); drawBuildingCounts(); drawUnitCounts(); } } }
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.RobotType; import battlecode.common.Team; import battlecode.events.MatchEvent; import battlecode.serial.Match; import flash.filters.DropShadowFilter; import mx.containers.Canvas; import mx.containers.VBox; import mx.controls.Label; import mx.controls.Spacer; import mx.events.ResizeEvent; import mx.formatters.NumberFormatter; public class DrawHUD extends VBox { private var controller:MatchController; private var team:String; private var pointLabel:Label; private var hqBox:DrawHUDHQ; private var towerBoxes:Object; // id -> DrawHUDTower private var buildingLabel:Label; private var buildingBoxes:Array; private var unitLabel:Label; private var unitBoxes:Array; private var winMarkerCanvas:Canvas; private var lastRound:uint = 0; private var maxTowers:uint = 0; private var formatter:NumberFormatter; public function DrawHUD(controller:MatchController, team:String) { this.controller = controller; this.team = team; controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); addEventListener(ResizeEvent.RESIZE, onResize); width = 180; percentHeight = 100; autoLayout = false; horizontalScrollPolicy = "off"; verticalScrollPolicy = "off"; pointLabel = new Label(); pointLabel.width = width; pointLabel.height = 30; pointLabel.x = 0; pointLabel.y = 10; pointLabel.filters = [ new DropShadowFilter(3, 45, 0x333333, 1, 2, 2) ]; pointLabel.setStyle("color", team == Team.A ? 0xFF6666 : 0x9999FF); pointLabel.setStyle("fontSize", 24); pointLabel.setStyle("fontWeight", "bold"); pointLabel.setStyle("textAlign", "center"); pointLabel.setStyle("fontFamily", "Courier New"); winMarkerCanvas = new Canvas(); winMarkerCanvas.width = width; winMarkerCanvas.height = 40; addChild(pointLabel); hqBox = new DrawHUDHQ(); addChild(hqBox); buildingLabel = new Label(); buildingLabel.width = width; buildingLabel.height = 30; buildingLabel.setStyle("color", 0xFFFFFF); buildingLabel.setStyle("fontSize", 18); buildingLabel.setStyle("textAlign", "center"); buildingLabel.setStyle("fontFamily", "Courier New"); buildingLabel.text = "Buildings"; addChild(buildingLabel); unitLabel = new Label(); unitLabel.width = width; unitLabel.height = 30; unitLabel.setStyle("color", 0xFFFFFF); unitLabel.setStyle("fontSize", 18); unitLabel.setStyle("textAlign", "center"); unitLabel.setStyle("fontFamily", "Courier New"); unitLabel.text = "Units"; addChild(unitLabel); towerBoxes = {}; buildingBoxes = new Array(); for each (var building:String in RobotType.buildings()) { var buildingBox:DrawHUDUnit = new DrawHUDUnit(building, team); buildingBoxes.push(buildingBox); addChild(buildingBox); } unitBoxes = new Array(); for each (var unit:String in RobotType.units()) { var unitBox:DrawHUDUnit = new DrawHUDUnit(unit, team); unitBoxes.push(unitBox); addChild(unitBox); } formatter = new NumberFormatter(); formatter.rounding = "down"; formatter.precision = 0; addChild(winMarkerCanvas); repositionWinMarkers(); resizeHQBox(); drawTowerBoxes(); drawUnitCounts(); drawBuildingCounts(); } private function onRoundChange(e:MatchEvent):void { var points:Number = controller.currentState.getPoints(team); pointLabel.text = formatter.format(points); if (e.currentRound <= lastRound) { hqBox.removeRobot(); drawWinMarkers(); } lastRound = e.currentRound; var hq:DrawRobot = controller.currentState.getHQ(team); if (hq && hq.isAlive()) { hqBox.setRobot(hq); hq.draw(); } var towers:Object = controller.currentState.getTowers(team); var towerCount:uint = 0; for each (var tower:DrawRobot in towers) { if (!towerBoxes[tower.getRobotID()]) { towerBoxes[tower.getRobotID()] = new DrawHUDTower(); addChild(towerBoxes[tower.getRobotID()]); } towerBoxes[tower.getRobotID()].setRobot(tower); tower.draw(); towerCount++; } maxTowers = Math.max(maxTowers, towerCount); drawTowerBoxes(); for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.setCount(controller.currentState.getUnitCount(unitBox.getType(), team)); } for each (var buildingBox:DrawHUDUnit in buildingBoxes) { buildingBox.setCount(controller.currentState.getUnitCount(buildingBox.getType(), team)); } drawUnitCounts(); drawBuildingCounts(); if (controller.currentRound == controller.match.getRounds()) { drawWinMarkers(); } } private function onMatchChange(e:MatchEvent):void { pointLabel.text = "0"; hqBox.removeRobot(); // clear tower boxes for (var a:String in towerBoxes) { towerBoxes[a].removeRobot(); if (towerBoxes[a].parent == this) { removeChild(towerBoxes[a]); } } towerBoxes = {}; maxTowers = 0; drawWinMarkers(); } private function resizeHQBox():void { var boxSize:Number = Math.min(100, (height - 70 - pointLabel.height - winMarkerCanvas.height) - 20); hqBox.resize(boxSize); hqBox.x = (width - boxSize) / 2; hqBox.y = 50; } private function drawTowerBoxes():void { var top:Number = hqBox.height + hqBox.y + 10; var i:uint = 0; for (var a:String in towerBoxes) { var towerBox:DrawHUDTower = towerBoxes[a]; towerBox.x = (width - towerBox.width * 3) / 2 + (i % 3) * towerBox.width; towerBox.y = ((towerBox.height + 10) * Math.floor(i / 3)) + top; i++; } } private function drawUnitCounts():void { var towerBoxTop:Number = Math.ceil(maxTowers / 3.0) * (DrawHUDTower.HEIGHT + 10); var top:Number = hqBox.height + hqBox.y + towerBoxTop + 10; unitLabel.y = top + 10; top = unitLabel.height + unitLabel.y + 5; var i:uint = 0; for each (var unitBox:DrawHUDUnit in unitBoxes) { unitBox.x = (width - unitBox.width * 3) / 2 + (i % 3) * unitBox.width; unitBox.y = ((unitBox.height + 10) * Math.floor(i / 3)) + top; if (unitBox.getCount() > 0) { unitBox.visible = true; i++; } else { unitBox.visible = false; } } } private function drawBuildingCounts():void { var topUnitBox:DrawHUDUnit = unitBoxes[unitBoxes.length-1]; for (var j:int = unitBoxes.length - 1; j >= 0; j--) { topUnitBox = unitBoxes[j]; if (topUnitBox.visible) { break; } } var top:Number = topUnitBox.height + topUnitBox.y + 10; buildingLabel.y = top + 10; top = buildingLabel.height + buildingLabel.y + 5; var i:uint = 0; for each (var buildingBox:DrawHUDUnit in buildingBoxes) { buildingBox.x = (width - buildingBox.width * 3) / 2 + (i % 3) * buildingBox.width; buildingBox.y = ((buildingBox.height + 10) * Math.floor(i / 3)) + top; if (buildingBox.getCount() > 0) { buildingBox.visible = true; i++; } else { buildingBox.visible = false; } } } private function drawWinMarkers():void { var matches:Vector.<Match> = controller.getMatches(); winMarkerCanvas.graphics.clear(); var i:uint, wins:uint = 0; var numMatches:int = (controller.currentRound == controller.match.getRounds()) ? controller.currentMatch : controller.currentMatch - 1; for (i = 0; i <= numMatches; i++) { if (matches[i].getWinner() == team) { var x:Number = (winMarkerCanvas.height - 5) / 2 + wins * winMarkerCanvas.height + 30; var y:Number = (winMarkerCanvas.height - 5) / 2; var r:Number = (winMarkerCanvas.height - 5) / 2; winMarkerCanvas.graphics.lineStyle(2, 0x000000); winMarkerCanvas.graphics.beginFill((team == Team.A) ? 0xFF6666 : 0x9999FF); winMarkerCanvas.graphics.drawCircle(x, y, r); winMarkerCanvas.graphics.endFill(); wins++; } } } private function repositionWinMarkers():void { winMarkerCanvas.y = height - winMarkerCanvas.height - 20; } private function onResize(e:ResizeEvent):void { repositionWinMarkers(); resizeHQBox(); drawTowerBoxes(); drawUnitCounts(); drawBuildingCounts(); } } }
put unit count above building count
put unit count above building count
ActionScript
mit
trun/battlecode-webclient
f30c773abc35b8b5aa8e7f2c1e3afad8d4e253de
src/aerys/minko/scene/visitor/data/LocalData.as
src/aerys/minko/scene/visitor/data/LocalData.as
package aerys.minko.scene.visitor.data { import aerys.minko.type.math.Matrix4x4; public final class LocalData { private static const _SCREEN_TO_UV : Matrix4x4 = new Matrix4x4( 0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0 ); public static const VIEW : String = 'view'; public static const WORLD : String = 'world'; public static const PROJECTION : String = 'projection'; public static const WORLD_INVERSE : String = 'worldInverse'; public static const VIEW_INVERSE : String = 'viewInverse'; public static const SCREEN_TO_UV : String = 'screenToUv'; public static const LOCAL_TO_VIEW : String = 'localToView'; public static const LOCAL_TO_SCREEN : String = 'localToScreen'; public static const LOCAL_TO_UV : String = 'localToUv'; protected var _world : Matrix4x4; protected var _view : Matrix4x4; protected var _projection : Matrix4x4; protected var _viewInverse : Matrix4x4; protected var _viewInverse_viewVersion : uint; protected var _worldInverse : Matrix4x4; protected var _worldInverse_worldVersion : uint; protected var _localToView : Matrix4x4; protected var _localToView_viewVersion : uint; protected var _localToView_worldVersion : uint; protected var _localToScreen : Matrix4x4; protected var _localToScreen_localToViewVersion : uint; protected var _localToScreen_projectionVersion : uint; protected var _localToUv : Matrix4x4; protected var _localToUv_localToScreenVersion : uint; public function get view() : Matrix4x4 { return _view; } public function get world() : Matrix4x4 { return _world; } public function get projection() : Matrix4x4 { return _projection; } public function get worldInverse() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; if (_worldInverse_worldVersion != worldMatrix.version) { _worldInverse = Matrix4x4.invert(worldMatrix, _worldInverse); _worldInverse_worldVersion = worldMatrix.version; } return _worldInverse; } public function get viewInverse() : Matrix4x4 { var viewMatrix : Matrix4x4 = view; if (_viewInverse_viewVersion != viewMatrix.version) { _viewInverse = Matrix4x4.invert(viewMatrix, _viewInverse); _viewInverse_viewVersion = viewMatrix.version; } return _viewInverse; } public function get localToView() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; var viewMatrix : Matrix4x4 = view; if (_localToView_worldVersion != worldMatrix.version || _localToView_viewVersion != viewMatrix.version) { _localToView = Matrix4x4.multiply(viewMatrix, worldMatrix, _localToView); _localToView_worldVersion = worldMatrix.version; _localToView_viewVersion = viewMatrix.version; } return _localToView; } public function get localToScreen() : Matrix4x4 { var localToViewMatrix : Matrix4x4 = localToView; var projectionMatrix : Matrix4x4 = projection; if (_localToScreen_localToViewVersion != localToViewMatrix.version || _localToScreen_projectionVersion != projectionMatrix.version) { _localToScreen = Matrix4x4.multiply(projectionMatrix, localToViewMatrix, _localToScreen); _localToScreen_localToViewVersion = localToViewMatrix.version; _localToScreen_projectionVersion = projectionMatrix.version; } return _localToScreen; } public function get screentoUv() : Matrix4x4 { return _SCREEN_TO_UV; } public function get localToUv() : Matrix4x4 { var localToScreenMatrix : Matrix4x4 = localToScreen; var screenToUvMatrix : Matrix4x4 = screentoUv; if (_localToUv_localToScreenVersion != localToScreenMatrix.version) { _localToUv = Matrix4x4.multiply(screenToUvMatrix, localToScreenMatrix); _localToUv_localToScreenVersion = localToScreenMatrix.version; } return _localToUv; } public function set world(value : Matrix4x4) : void { Matrix4x4.copy(value, _world); } public function set view(value : Matrix4x4) : void { Matrix4x4.copy(value, _view); } public function set projection(value : Matrix4x4) : void { Matrix4x4.copy(value, _projection); } public function LocalData() { _world = new Matrix4x4(); _view = new Matrix4x4(); _projection = new Matrix4x4(); reset(); } public function reset() : void { _viewInverse_viewVersion = uint.MAX_VALUE; _worldInverse_worldVersion = uint.MAX_VALUE; _localToView_viewVersion = uint.MAX_VALUE; _localToView_worldVersion = uint.MAX_VALUE; _localToScreen_localToViewVersion = uint.MAX_VALUE; _localToScreen_projectionVersion = uint.MAX_VALUE; } } }
package aerys.minko.scene.visitor.data { import aerys.minko.type.math.Matrix4x4; public final class LocalData { private static const _SCREEN_TO_UV : Matrix4x4 = new Matrix4x4( 0.5, 0.0, 0.0, 0.0, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0 ); public static const VIEW : String = 'view'; public static const WORLD : String = 'world'; public static const PROJECTION : String = 'projection'; public static const WORLD_INVERSE : String = 'worldInverse'; public static const VIEW_INVERSE : String = 'viewInverse'; public static const SCREEN_TO_UV : String = 'screenToUv'; public static const LOCAL_TO_VIEW : String = 'localToView'; public static const LOCAL_TO_SCREEN : String = 'localToScreen'; public static const LOCAL_TO_UV : String = 'localToUv'; public static const GLOBAL_TO_SCREEN : String = 'globalToScreen'; protected var _world : Matrix4x4; protected var _view : Matrix4x4; protected var _projection : Matrix4x4; protected var _viewInverse : Matrix4x4; protected var _viewInverse_viewVersion : uint; protected var _worldInverse : Matrix4x4; protected var _worldInverse_worldVersion : uint; protected var _localToView : Matrix4x4; protected var _localToView_viewVersion : uint; protected var _localToView_worldVersion : uint; protected var _localToScreen : Matrix4x4; protected var _localToScreen_localToViewVersion : uint; protected var _localToScreen_projectionVersion : uint; protected var _localToUv : Matrix4x4; protected var _localToUv_localToScreenVersion : uint; protected var _globalToScreen : Matrix4x4; protected var _globalToScreen_viewVersion : uint; protected var _globalToScreen_projectionVersion : uint; public function get view() : Matrix4x4 { return _view; } public function get world() : Matrix4x4 { return _world; } public function get projection() : Matrix4x4 { return _projection; } public function get worldInverse() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; if (_worldInverse_worldVersion != worldMatrix.version) { _worldInverse = Matrix4x4.invert(worldMatrix, _worldInverse); _worldInverse_worldVersion = worldMatrix.version; } return _worldInverse; } public function get viewInverse() : Matrix4x4 { var viewMatrix : Matrix4x4 = view; if (_viewInverse_viewVersion != viewMatrix.version) { _viewInverse = Matrix4x4.invert(viewMatrix, _viewInverse); _viewInverse_viewVersion = viewMatrix.version; } return _viewInverse; } public function get localToView() : Matrix4x4 { var worldMatrix : Matrix4x4 = world; var viewMatrix : Matrix4x4 = view; if (_localToView_worldVersion != worldMatrix.version || _localToView_viewVersion != viewMatrix.version) { _localToView = Matrix4x4.multiply(viewMatrix, worldMatrix, _localToView); _localToView_worldVersion = worldMatrix.version; _localToView_viewVersion = viewMatrix.version; } return _localToView; } public function get localToScreen() : Matrix4x4 { var localToViewMatrix : Matrix4x4 = localToView; var projectionMatrix : Matrix4x4 = projection; if (_localToScreen_localToViewVersion != localToViewMatrix.version || _localToScreen_projectionVersion != projectionMatrix.version) { _localToScreen = Matrix4x4.multiply(projectionMatrix, localToViewMatrix, _localToScreen); _localToScreen_localToViewVersion = localToViewMatrix.version; _localToScreen_projectionVersion = projectionMatrix.version; } return _localToScreen; } public function get screentoUv() : Matrix4x4 { return _SCREEN_TO_UV; } public function get localToUv() : Matrix4x4 { var localToScreenMatrix : Matrix4x4 = localToScreen; var screenToUvMatrix : Matrix4x4 = screentoUv; if (_localToUv_localToScreenVersion != localToScreenMatrix.version) { _localToUv = Matrix4x4.multiply(screenToUvMatrix, localToScreenMatrix); _localToUv_localToScreenVersion = localToScreenMatrix.version; } return _localToUv; } public function get globalToScreen() : Matrix4x4 { var projectionMatrix : Matrix4x4 = projection; var viewMatrix : Matrix4x4 = view; if (_globalToScreen_projectionVersion != projectionMatrix.version || _globalToScreen_viewVersion != viewMatrix.version) { _globalToScreen = Matrix4x4.multiply(projectionMatrix, viewMatrix, _globalToScreen); _globalToScreen_projectionVersion = projectionMatrix.version; _globalToScreen_viewVersion = viewMatrix.version; } return _globalToScreen; } public function set world(value : Matrix4x4) : void { Matrix4x4.copy(value, _world); } public function set view(value : Matrix4x4) : void { Matrix4x4.copy(value, _view); } public function set projection(value : Matrix4x4) : void { Matrix4x4.copy(value, _projection); } public function LocalData() { _world = new Matrix4x4(); _view = new Matrix4x4(); _projection = new Matrix4x4(); reset(); } public function reset() : void { _viewInverse_viewVersion = uint.MAX_VALUE; _worldInverse_worldVersion = uint.MAX_VALUE; _localToView_viewVersion = uint.MAX_VALUE; _localToView_worldVersion = uint.MAX_VALUE; _localToScreen_localToViewVersion = uint.MAX_VALUE; _localToScreen_projectionVersion = uint.MAX_VALUE; _globalToScreen_projectionVersion = uint.MAX_VALUE; _globalToScreen_viewVersion = uint.MAX_VALUE; } } }
Add a globalToScreen matrix getter in LocalData
Add a globalToScreen matrix getter in LocalData
ActionScript
mit
aerys/minko-as3
965f85f43f44145075333e2127c612ae9985a64c
Impetus.as
Impetus.as
package io.github.jwhile.impetus { import flash.display.Sprite; import flash.external.ExternalInterface; public class Impetus extends Sprite { private sounds:Vector.<ImpetusSound>; public function Impetus():void { sounds = new Vector.<ImpetusSound>(); if(ExternalInterface.available) { ExternalInterface.addCallback('getSound', getSound); ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)"); } } public function getSound(url:String) { var len:int = sounds.length; for(var i:int = 0; i < len; i++) { if(sounds[i].getUrl() === url) { return sounds[i]; } } var s:ImpetusSound = new ImpetusSound(); sounds.push(s); return s; } } }
package io.github.jwhile.impetus { import flash.display.Sprite; import flash.external.ExternalInterface; public class Impetus extends Sprite { private sounds:Vector.<ImpetusSound>; public function Impetus():void { this.sounds = new Vector.<ImpetusSound>(); if(ExternalInterface.available) { ExternalInterface.addCallback('getSound', this.getSound); ExternalInterface.call("console.log", "Impetus loaded. (https://github.com/JWhile/Impetus)"); } } public function getSound(url:String) { var len:int = this.sounds.length; for(var i:int = 0; i < len; i++) { if(this.sounds[i].getUrl() === url) { return this.sounds[i]; } } var s:ImpetusSound = new ImpetusSound(url); this.sounds.push(s); return s; } } }
Use this keyword + Send sound url to ImpetusSound
Use this keyword + Send sound url to ImpetusSound
ActionScript
mit
Julow/Impetus
9315dd08b3940039ca64f13d3a7154b5b403c824
src/aerys/minko/scene/controller/camera/ArcBallController.as
src/aerys/minko/scene/controller/camera/ArcBallController.as
package aerys.minko.scene.controller.camera { import aerys.minko.render.Viewport; import aerys.minko.scene.controller.EnterFrameController; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display.BitmapData; import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.geom.Point; import flash.ui.Mouse; import flash.ui.MouseCursor; public class ArcBallController extends EnterFrameController { private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4(); private static const EPSILON : Number = 0.001; protected var _mousePosition : Point = new Point(); private var _enabled : Boolean = true; private var _distance : Number = 1.; private var _yaw : Number = 0; private var _pitch : Number = 0; private var _update : Boolean = true; private var _position : Vector4 = new Vector4(0, 0, 0, 1); private var _lookAt : Vector4 = new Vector4(0, 0, 0, 1); private var _up : Vector4 = new Vector4(0, 1, 0, 1); private var _minDistance : Number = 0.1; private var _maxDistance : Number = 1000; private var _distanceStep : Number = 1; private var _yawStep : Number = 0.01; private var _pitchStep : Number = 0.01; public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } protected function set update(value : Boolean) : void { _update = value; } /** * Distance between look at point and target */ public function get distance() : Number { return _distance; } public function set distance(value : Number) : void { _distance = value; _update = true; } /** * Horizontal rotation angle (in radians) */ public function get yaw() : Number { return _yaw; } public function set yaw(value : Number) : void { _yaw = value; _update = true; } /** * Vertical rotation angle (in radians) */ public function get pitch() : Number { return _pitch; } public function set pitch(value : Number) : void { _pitch = value; _update = true; } /** * Position the targets will look at */ public function get lookAt() : Vector4 { return _lookAt; } /** * Up vector the targets will rotate around */ public function get up() : Vector4 { return _up; } /** * Minimum distance constrain between look at point and target. */ public function get minDistance() : Number { return _minDistance; } public function set minDistance(value : Number) : void { _minDistance = value; _update = true; } /** * Maximum distance constrain between look at point and target. */ public function get maxDistance() : Number { return _maxDistance; } public function set maxDistance(value : Number) : void { _maxDistance = value; _update = true; } /** * Distance step applied to the camera when the mouse wheel is used in meters/wheel rotation unit */ public function get distanceStep() : Number { return _distanceStep; } public function set distanceStep(value : Number) : void { _distanceStep = value; } /** * Horizontal angular step applied to the camera when the mouse is moved in radian/pixel */ public function get yawStep() : Number { return _yawStep; } public function set yawStep(value : Number) : void { _yawStep = value; } /** * Vertical angular step applied to the camera when the mouse is moved in radian/pixel */ public function get pitchStep() : Number { return _pitchStep; } public function set pitchStep(value : Number) : void { _pitchStep = value; } public function ArcBallController() { super(); _pitch = Math.PI * .5; _lookAt.changed.add(updateNextFrameHandler); _up.changed.add(updateNextFrameHandler); } public function bindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController { dispatcher.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler); dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); return this; } public function unbindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController { dispatcher.removeEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler); dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); return this; } override protected function targetAddedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { super.targetAddedHandler(ctrl, target); _update = true; updateTargets(); } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { updateTargets(); } private function updateTargets() : void { if (_update && _enabled) { if (_distance < _minDistance) _distance = _minDistance; if (_distance > _maxDistance) _distance = _maxDistance; if (_pitch <= EPSILON) _pitch = EPSILON; if (_pitch > Math.PI - EPSILON) _pitch = Math.PI - EPSILON; _position.set( _lookAt.x + _distance * Math.cos(_yaw) * Math.sin(_pitch), _lookAt.y + _distance * Math.cos(_pitch), _lookAt.z + _distance * Math.sin(_yaw) * Math.sin(_pitch) ); TMP_MATRIX.lookAt(_lookAt, _position, _up); var numTargets : uint = this.numTargets; for (var targetId : uint = 0; targetId < numTargets; ++targetId) getTarget(targetId).transform.copyFrom(TMP_MATRIX); _update = false; } } protected function mouseWheelHandler(e : MouseEvent) : void { _distance -= e.delta * _distanceStep; _update = true; } protected function mouseMoveHandler(e : MouseEvent) : void { // compute position if (e.buttonDown && _enabled) { _yaw += (_mousePosition.x - e.stageX) * _yawStep; _pitch += (_mousePosition.y - e.stageY) * _pitchStep; _update = true; } _mousePosition.setTo(e.stageX, e.stageY); } private function updateNextFrameHandler(vector : Vector4) : void { _update = true; } } }
package aerys.minko.scene.controller.camera { import aerys.minko.render.Viewport; import aerys.minko.scene.controller.EnterFrameController; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Vector4; import flash.display.BitmapData; import flash.events.IEventDispatcher; import flash.events.MouseEvent; import flash.geom.Point; import flash.ui.Mouse; import flash.ui.MouseCursor; public class ArcBallController extends EnterFrameController { private static const TMP_MATRIX : Matrix4x4 = new Matrix4x4(); private static const EPSILON : Number = 0.001; protected var _mousePosition : Point = new Point(); private var _enabled : Boolean = true; private var _distance : Number = 1.; private var _yaw : Number = 0; private var _pitch : Number = 0; private var _update : Boolean = true; private var _position : Vector4 = new Vector4(0, 0, 0, 1); private var _lookAt : Vector4 = new Vector4(0, 0, 0, 1); private var _up : Vector4 = new Vector4(0, 1, 0, 1); private var _minDistance : Number = 1.; private var _maxDistance : Number = 1000; private var _distanceStep : Number = 1; private var _yawStep : Number = 0.01; private var _pitchStep : Number = 0.01; public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } protected function set update(value : Boolean) : void { _update = value; } /** * Distance between look at point and target */ public function get distance() : Number { return _distance; } public function set distance(value : Number) : void { _distance = value; _update = true; } /** * Horizontal rotation angle (in radians) */ public function get yaw() : Number { return _yaw; } public function set yaw(value : Number) : void { _yaw = value; _update = true; } /** * Vertical rotation angle (in radians) */ public function get pitch() : Number { return _pitch; } public function set pitch(value : Number) : void { _pitch = value; _update = true; } /** * Position the targets will look at */ public function get lookAt() : Vector4 { return _lookAt; } /** * Up vector the targets will rotate around */ public function get up() : Vector4 { return _up; } /** * Minimum distance constrain between look at point and target. */ public function get minDistance() : Number { return _minDistance; } public function set minDistance(value : Number) : void { _minDistance = value; _update = true; } /** * Maximum distance constrain between look at point and target. */ public function get maxDistance() : Number { return _maxDistance; } public function set maxDistance(value : Number) : void { _maxDistance = value; _update = true; } /** * Distance step applied to the camera when the mouse wheel is used in meters/wheel rotation unit */ public function get distanceStep() : Number { return _distanceStep; } public function set distanceStep(value : Number) : void { _distanceStep = value; } /** * Horizontal angular step applied to the camera when the mouse is moved in radian/pixel */ public function get yawStep() : Number { return _yawStep; } public function set yawStep(value : Number) : void { _yawStep = value; } /** * Vertical angular step applied to the camera when the mouse is moved in radian/pixel */ public function get pitchStep() : Number { return _pitchStep; } public function set pitchStep(value : Number) : void { _pitchStep = value; } public function ArcBallController() { super(); _pitch = Math.PI * .5; _lookAt.changed.add(updateNextFrameHandler); _up.changed.add(updateNextFrameHandler); } public function bindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController { dispatcher.addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler); dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); return this; } public function unbindDefaultControls(dispatcher : IEventDispatcher) : ArcBallController { dispatcher.removeEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler); dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler); return this; } override protected function targetAddedHandler(ctrl : EnterFrameController, target : ISceneNode) : void { super.targetAddedHandler(ctrl, target); _update = true; updateTargets(); } override protected function sceneEnterFrameHandler(scene : Scene, viewport : Viewport, destination : BitmapData, time : Number) : void { updateTargets(); } private function updateTargets() : void { if (_update && _enabled) { if (_distance < _minDistance) _distance = _minDistance; if (_distance > _maxDistance) _distance = _maxDistance; if (_pitch <= EPSILON) _pitch = EPSILON; if (_pitch > Math.PI - EPSILON) _pitch = Math.PI - EPSILON; _position.set( _lookAt.x + _distance * Math.cos(_yaw) * Math.sin(_pitch), _lookAt.y + _distance * Math.cos(_pitch), _lookAt.z + _distance * Math.sin(_yaw) * Math.sin(_pitch) ); TMP_MATRIX.lookAt(_lookAt, _position, _up); var numTargets : uint = this.numTargets; for (var targetId : uint = 0; targetId < numTargets; ++targetId) getTarget(targetId).transform.copyFrom(TMP_MATRIX); _update = false; } } protected function mouseWheelHandler(e : MouseEvent) : void { _distance -= e.delta * _distanceStep; _update = true; } protected function mouseMoveHandler(e : MouseEvent) : void { // compute position if (e.buttonDown && _enabled) { _yaw += (_mousePosition.x - e.stageX) * _yawStep; _pitch += (_mousePosition.y - e.stageY) * _pitchStep; _update = true; } _mousePosition.setTo(e.stageX, e.stageY); } private function updateNextFrameHandler(vector : Vector4) : void { _update = true; } } }
set ArcBallController.minDistance to 1.0 by default
set ArcBallController.minDistance to 1.0 by default
ActionScript
mit
aerys/minko-as3
9999c448099dd2c6171b941f9f9961322faec956
bin/Data/Scripts/Editor/EditorEventsHandlers.as
bin/Data/Scripts/Editor/EditorEventsHandlers.as
// Editor main handlers (add your local handler in proper main handler to prevent losing events) const String EDITOR_EVENT_SCENE_LOADED("EditorEventSceneLoaded"); const String EDITOR_EVENT_ORIGIN_START_HOVER("EditorEventOriginStartHover"); const String EDITOR_EVENT_ORIGIN_END_HOVER("EditorEventOriginEndHover"); void EditorSubscribeToEvents() { SubscribeToEvent("KeyDown", "EditorMainHandleKeyDown"); SubscribeToEvent("KeyUp", "EditorMainHandleKeyUp"); SubscribeToEvent("MouseMove", "EditorMainHandleMouseMove"); SubscribeToEvent("MouseWheel", "EditorMainHandleMouseWheel"); SubscribeToEvent("MouseButtonDown", "EditorMainHandleMouseButtonDown"); SubscribeToEvent("MouseButtonUp", "EditorMainHandleMouseButtonUp"); SubscribeToEvent("PostRenderUpdate", "EditorMainHandlePostRenderUpdate"); SubscribeToEvent("UIMouseClick", "EditorMainHandleUIMouseClick"); SubscribeToEvent("UIMouseClickEnd", "EditorMainHandleUIMouseClickEnd"); SubscribeToEvent("BeginViewUpdate", "EditorMainHandleBeginViewUpdate"); SubscribeToEvent("EndViewUpdate", "EditorMainHandleEndViewUpdate"); SubscribeToEvent("BeginViewRender", "EditorMainHandleBeginViewRender"); SubscribeToEvent("EndViewRender", "EditorMainHandleEndViewRender"); SubscribeToEvent(EDITOR_EVENT_SCENE_LOADED, "EditorMainHandleSceneLoaded"); SubscribeToEvent("HoverBegin", "EditorMainHandleHoverBegin"); SubscribeToEvent("HoverEnd", "EditorMainHandleHoverEnd"); SubscribeToEvent(EDITOR_EVENT_ORIGIN_START_HOVER, "EditorMainHandleOriginStartHover"); SubscribeToEvent(EDITOR_EVENT_ORIGIN_END_HOVER, "EditorMainHandleOriginEndHover"); SubscribeToEvent("NodeAdded", "EditorMainHandleNodeAdded"); SubscribeToEvent("NodeRemoved", "EditorMainHandleNodeRemoved"); SubscribeToEvent("NodeNameChanged", "EditorMainHandleNodeNameChanged"); } void EditorMainHandleKeyDown(StringHash eventType, VariantMap& eventData) { // EditorUI.as handler HandleKeyDown(eventType, eventData); // EditorColorWheel.as handler HandleColorWheelKeyDown(eventType, eventData); } void EditorMainHandleKeyUp(StringHash eventType, VariantMap& eventData) { // EditorUI.as handler UnfadeUI(); } void EditorMainHandleMouseMove(StringHash eventType, VariantMap& eventData) { // EditorView.as handler ViewMouseMove(); // EditorColorWheel.as handler HandleColorWheelMouseMove(eventType, eventData); // EditorLayer.as handler HandleHideLayerEditor(eventType, eventData); // PaintSelectionMouseMove HandlePaintSelectionMouseMove(eventType, eventData); } void EditorMainHandleMouseWheel(StringHash eventType, VariantMap& eventData) { // EditorColorWheel.as handler HandleColorWheelMouseWheel(eventType, eventData); // EditorLayer.as handler HandleMaskTypeScroll(eventType, eventData); // PaintSelection handler HandlePaintSelectionWheel(eventType, eventData); } void EditorMainHandleMouseButtonDown(StringHash eventType, VariantMap& eventData) { // EditorColorWheel.as handler HandleColorWheelMouseButtonDown(eventType, eventData); // EditorLayer.as handler HandleHideLayerEditor(eventType, eventData); } void EditorMainHandleMouseButtonUp(StringHash eventType, VariantMap& eventData) { // EditorUI.as handler UnfadeUI(); } void EditorMainHandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) { // EditorView.as handler HandlePostRenderUpdate(); } void EditorMainHandleUIMouseClick(StringHash eventType, VariantMap& eventData) { // EditorView.as handler ViewMouseClick(); HandleOriginToggled(eventType, eventData); } void EditorMainHandleUIMouseClickEnd(StringHash eventType, VariantMap& eventData) { // EditorView.as handler ViewMouseClickEnd(); } void EditorMainHandleBeginViewUpdate(StringHash eventType, VariantMap& eventData) { // EditorView.as handler HandleBeginViewUpdate(eventType, eventData); } void EditorMainHandleEndViewUpdate(StringHash eventType, VariantMap& eventData) { // EditorView.as handler HandleEndViewUpdate(eventType, eventData); } void EditorMainHandleBeginViewRender(StringHash eventType, VariantMap& eventData) { HandleBeginViewRender(eventType, eventData); } void EditorMainHandleEndViewRender(StringHash eventType, VariantMap& eventData) { HandleEndViewRender(eventType, eventData); } void EditorMainHandleSceneLoaded(StringHash eventType, VariantMap& eventData) { HandleSceneLoadedForOrigins(); } void EditorMainHandleHoverBegin(StringHash eventType, VariantMap& eventData) { HandleOriginsHoverBegin(eventType, eventData); } void EditorMainHandleHoverEnd(StringHash eventType, VariantMap& eventData) { HandleOriginsHoverEnd(eventType, eventData); } void EditorMainHandleNodeAdded(StringHash eventType, VariantMap& eventData) { HandleNodeAdded(eventType, eventData); rebuildSceneOrigins = true; } void EditorMainHandleNodeRemoved(StringHash eventType, VariantMap& eventData) { HandleNodeRemoved(eventType, eventData); rebuildSceneOrigins = true; } void EditorMainHandleNodeNameChanged(StringHash eventType, VariantMap& eventData) { HandleNodeNameChanged(eventType, eventData); } void EditorMainHandleOriginStartHover(StringHash eventType, VariantMap& eventData) { } void EditorMainHandleOriginEndHover(StringHash eventType, VariantMap& eventData) { }
// Editor main handlers (add your local handler in proper main handler to prevent losing events) const String EDITOR_EVENT_SCENE_LOADED("EditorEventSceneLoaded"); const String EDITOR_EVENT_ORIGIN_START_HOVER("EditorEventOriginStartHover"); const String EDITOR_EVENT_ORIGIN_END_HOVER("EditorEventOriginEndHover"); void EditorSubscribeToEvents() { SubscribeToEvent("KeyDown", "EditorMainHandleKeyDown"); SubscribeToEvent("KeyUp", "EditorMainHandleKeyUp"); SubscribeToEvent("MouseMove", "EditorMainHandleMouseMove"); SubscribeToEvent("MouseWheel", "EditorMainHandleMouseWheel"); SubscribeToEvent("MouseButtonDown", "EditorMainHandleMouseButtonDown"); SubscribeToEvent("MouseButtonUp", "EditorMainHandleMouseButtonUp"); SubscribeToEvent("PostRenderUpdate", "EditorMainHandlePostRenderUpdate"); SubscribeToEvent("UIMouseClick", "EditorMainHandleUIMouseClick"); SubscribeToEvent("UIMouseClickEnd", "EditorMainHandleUIMouseClickEnd"); SubscribeToEvent("BeginViewUpdate", "EditorMainHandleBeginViewUpdate"); SubscribeToEvent("EndViewUpdate", "EditorMainHandleEndViewUpdate"); SubscribeToEvent("BeginViewRender", "EditorMainHandleBeginViewRender"); SubscribeToEvent("EndViewRender", "EditorMainHandleEndViewRender"); SubscribeToEvent(EDITOR_EVENT_SCENE_LOADED, "EditorMainHandleSceneLoaded"); SubscribeToEvent("HoverBegin", "EditorMainHandleHoverBegin"); SubscribeToEvent("HoverEnd", "EditorMainHandleHoverEnd"); SubscribeToEvent(EDITOR_EVENT_ORIGIN_START_HOVER, "EditorMainHandleOriginStartHover"); SubscribeToEvent(EDITOR_EVENT_ORIGIN_END_HOVER, "EditorMainHandleOriginEndHover"); SubscribeToEvent("NodeAdded", "EditorMainHandleNodeAdded"); SubscribeToEvent("NodeRemoved", "EditorMainHandleNodeRemoved"); SubscribeToEvent("NodeNameChanged", "EditorMainHandleNodeNameChanged"); } void EditorMainHandleKeyDown(StringHash eventType, VariantMap& eventData) { // EditorUI.as handler HandleKeyDown(eventType, eventData); // EditorColorWheel.as handler HandleColorWheelKeyDown(eventType, eventData); } void EditorMainHandleKeyUp(StringHash eventType, VariantMap& eventData) { // EditorUI.as handler UnfadeUI(); } void EditorMainHandleMouseMove(StringHash eventType, VariantMap& eventData) { // EditorView.as handler ViewMouseMove(); // EditorColorWheel.as handler HandleColorWheelMouseMove(eventType, eventData); // EditorLayer.as handler HandleHideLayerEditor(eventType, eventData); // PaintSelectionMouseMove HandlePaintSelectionMouseMove(eventType, eventData); } void EditorMainHandleMouseWheel(StringHash eventType, VariantMap& eventData) { // EditorColorWheel.as handler HandleColorWheelMouseWheel(eventType, eventData); // EditorLayer.as handler HandleMaskTypeScroll(eventType, eventData); // PaintSelection handler HandlePaintSelectionWheel(eventType, eventData); } void EditorMainHandleMouseButtonDown(StringHash eventType, VariantMap& eventData) { // EditorColorWheel.as handler HandleColorWheelMouseButtonDown(eventType, eventData); // EditorLayer.as handler HandleHideLayerEditor(eventType, eventData); } void EditorMainHandleMouseButtonUp(StringHash eventType, VariantMap& eventData) { // EditorUI.as handler UnfadeUI(); } void EditorMainHandlePostRenderUpdate(StringHash eventType, VariantMap& eventData) { // EditorView.as handler HandlePostRenderUpdate(); } void EditorMainHandleUIMouseClick(StringHash eventType, VariantMap& eventData) { // EditorView.as handler ViewMouseClick(); HandleOriginToggled(eventType, eventData); } void EditorMainHandleUIMouseClickEnd(StringHash eventType, VariantMap& eventData) { // EditorView.as handler ViewMouseClickEnd(); } void EditorMainHandleBeginViewUpdate(StringHash eventType, VariantMap& eventData) { // EditorView.as handler HandleBeginViewUpdate(eventType, eventData); } void EditorMainHandleEndViewUpdate(StringHash eventType, VariantMap& eventData) { // EditorView.as handler HandleEndViewUpdate(eventType, eventData); } void EditorMainHandleBeginViewRender(StringHash eventType, VariantMap& eventData) { HandleBeginViewRender(eventType, eventData); } void EditorMainHandleEndViewRender(StringHash eventType, VariantMap& eventData) { HandleEndViewRender(eventType, eventData); } void EditorMainHandleSceneLoaded(StringHash eventType, VariantMap& eventData) { HandleSceneLoadedForOrigins(); } void EditorMainHandleHoverBegin(StringHash eventType, VariantMap& eventData) { HandleOriginsHoverBegin(eventType, eventData); } void EditorMainHandleHoverEnd(StringHash eventType, VariantMap& eventData) { HandleOriginsHoverEnd(eventType, eventData); } void EditorMainHandleNodeAdded(StringHash eventType, VariantMap& eventData) { if (GetEventSender() !is editorScene) return; HandleNodeAdded(eventType, eventData); rebuildSceneOrigins = true; } void EditorMainHandleNodeRemoved(StringHash eventType, VariantMap& eventData) { if (GetEventSender() !is editorScene) return; HandleNodeRemoved(eventType, eventData); rebuildSceneOrigins = true; } void EditorMainHandleNodeNameChanged(StringHash eventType, VariantMap& eventData) { if (GetEventSender() !is editorScene) return; HandleNodeNameChanged(eventType, eventData); } void EditorMainHandleOriginStartHover(StringHash eventType, VariantMap& eventData) { } void EditorMainHandleOriginEndHover(StringHash eventType, VariantMap& eventData) { }
Fix resource browser scene node addition/removal getting reflected in the editor hierarchy window.
Fix resource browser scene node addition/removal getting reflected in the editor hierarchy window.
ActionScript
mit
c4augustus/Urho3D,carnalis/Urho3D,MeshGeometry/Urho3D,SirNate0/Urho3D,xiliu98/Urho3D,weitjong/Urho3D,victorholt/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,299299/Urho3D,orefkov/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,iainmerrick/Urho3D,urho3d/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,299299/Urho3D,kostik1337/Urho3D,orefkov/Urho3D,tommy3/Urho3D,rokups/Urho3D,eugeneko/Urho3D,henu/Urho3D,MonkeyFirst/Urho3D,299299/Urho3D,henu/Urho3D,weitjong/Urho3D,codemon66/Urho3D,bacsmar/Urho3D,codemon66/Urho3D,kostik1337/Urho3D,fire/Urho3D-1,MonkeyFirst/Urho3D,victorholt/Urho3D,codedash64/Urho3D,fire/Urho3D-1,eugeneko/Urho3D,urho3d/Urho3D,kostik1337/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,urho3d/Urho3D,bacsmar/Urho3D,codemon66/Urho3D,SuperWangKai/Urho3D,MeshGeometry/Urho3D,cosmy1/Urho3D,urho3d/Urho3D,MeshGeometry/Urho3D,PredatorMF/Urho3D,tommy3/Urho3D,bacsmar/Urho3D,xiliu98/Urho3D,codedash64/Urho3D,cosmy1/Urho3D,codedash64/Urho3D,weitjong/Urho3D,299299/Urho3D,carnalis/Urho3D,c4augustus/Urho3D,MonkeyFirst/Urho3D,c4augustus/Urho3D,299299/Urho3D,weitjong/Urho3D,tommy3/Urho3D,MonkeyFirst/Urho3D,codedash64/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,victorholt/Urho3D,kostik1337/Urho3D,eugeneko/Urho3D,victorholt/Urho3D,eugeneko/Urho3D,PredatorMF/Urho3D,rokups/Urho3D,c4augustus/Urho3D,orefkov/Urho3D,tommy3/Urho3D,fire/Urho3D-1,299299/Urho3D,henu/Urho3D,victorholt/Urho3D,codedash64/Urho3D,bacsmar/Urho3D,kostik1337/Urho3D,rokups/Urho3D,cosmy1/Urho3D,PredatorMF/Urho3D,SirNate0/Urho3D,rokups/Urho3D,iainmerrick/Urho3D,carnalis/Urho3D,SuperWangKai/Urho3D,iainmerrick/Urho3D,tommy3/Urho3D,fire/Urho3D-1,xiliu98/Urho3D,SirNate0/Urho3D,iainmerrick/Urho3D,fire/Urho3D-1,orefkov/Urho3D,rokups/Urho3D,carnalis/Urho3D,PredatorMF/Urho3D,henu/Urho3D,xiliu98/Urho3D,SirNate0/Urho3D,rokups/Urho3D,xiliu98/Urho3D,codemon66/Urho3D,codemon66/Urho3D,weitjong/Urho3D,iainmerrick/Urho3D
6cb30a9a1588c0b62ea948d15c2dd489cd07922a
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextFieldBeadBase.as
frameworks/as/src/org/apache/flex/html/staticControls/beads/TextFieldBeadBase.as
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.staticControls.beads { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import org.apache.flex.core.CSSTextField; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.ITextBead; import org.apache.flex.core.ITextModel; import org.apache.flex.events.Event; public class TextFieldBeadBase implements IBead, ITextBead { public function TextFieldBeadBase() { _textField = new CSSTextField(); } private var _textField:CSSTextField; public function get textField() : CSSTextField { return _textField; } private var _textModel:ITextModel; public function get textModel() : ITextModel { return _textModel; } private var _strand:IStrand; public function set strand(value:IStrand):void { _strand = value; _textModel = value.getBeadByType(ITextModel) as ITextModel; textModel.addEventListener("textChange", textChangeHandler); textModel.addEventListener("htmlChange", htmlChangeHandler); textModel.addEventListener("widthChanged", sizeChangeHandler); textModel.addEventListener("heightChanged", sizeChangeHandler); DisplayObjectContainer(value).addChild(_textField); sizeChangeHandler(null); if (textModel.text !== null) text = textModel.text; if (textModel.html !== null) html = textModel.html; } public function get strand() : IStrand { return _strand; } public function get text():String { return _textField.text; } public function set text(value:String):void { if (value == null) value == ""; _textField.text = value; } public function get html():String { return _textField.htmlText; } public function set html(value:String):void { _textField.htmlText = value; } private function textChangeHandler(event:Event):void { text = textModel.text; } private function htmlChangeHandler(event:Event):void { html = textModel.html; } private function sizeChangeHandler(event:Event):void { textField.width = DisplayObject(_strand).width; textField.height = DisplayObject(_strand).height; } } }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.flex.html.staticControls.beads { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import org.apache.flex.core.CSSTextField; import org.apache.flex.core.IBead; import org.apache.flex.core.IStrand; import org.apache.flex.core.ITextBead; import org.apache.flex.core.ITextModel; import org.apache.flex.events.Event; public class TextFieldBeadBase implements IBead, ITextBead { public function TextFieldBeadBase() { _textField = new CSSTextField(); } private var _textField:CSSTextField; public function get textField() : CSSTextField { return _textField; } private var _textModel:ITextModel; public function get textModel() : ITextModel { return _textModel; } private var _strand:IStrand; public function set strand(value:IStrand):void { _strand = value; _textModel = value.getBeadByType(ITextModel) as ITextModel; textModel.addEventListener("textChange", textChangeHandler); textModel.addEventListener("htmlChange", htmlChangeHandler); textModel.addEventListener("widthChanged", sizeChangeHandler); textModel.addEventListener("heightChanged", sizeChangeHandler); DisplayObjectContainer(value).addChild(_textField); sizeChangeHandler(null); if (textModel.text !== null) text = textModel.text; if (textModel.html !== null) html = textModel.html; } public function get strand() : IStrand { return _strand; } public function get text():String { return _textField.text; } public function set text(value:String):void { if (value == null) value = ""; _textField.text = value; } public function get html():String { return _textField.htmlText; } public function set html(value:String):void { _textField.htmlText = value; } private function textChangeHandler(event:Event):void { text = textModel.text; } private function htmlChangeHandler(event:Event):void { html = textModel.html; } private function sizeChangeHandler(event:Event):void { textField.width = DisplayObject(_strand).width; textField.height = DisplayObject(_strand).height; } } }
handle null which could happen when restoring states
handle null which could happen when restoring states
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
2f371d88f95807be7cc33116ab2a885e73bb88cf
lib/goplayer/Packer.as
lib/goplayer/Packer.as
package goplayer { import flash.display.DisplayObject public class Packer { private var base : Item private var items : Array public function Packer(base : Item, items : Array) { this.base = base, this.items = items } public function execute() : void { var current : Item = base for each (var item : Item in items) item.packLeft(current), current = item } public static function packLeft(space : Number, ... items : Array) : void { $packLeft(space, items) } public static function $packLeft(space : Number, items : Array) : void { if (items.length > 0) $$packLeft(new Importer(space, items).getItems()) } private static function $$packLeft(items : Array) : void { new Packer(items[0], items.slice(1)).execute() } } } import flash.display.DisplayObject class Item { private var object : DisplayObject private var _width : Number public function Item(object : DisplayObject, width : Number) { this.object = object, _width = width } public function get width() : Number { return _width } public function get right() : Number { return object.x + width } public function packLeft(base : Item) : void { object.x = base.right } } class Importer { private var space : Number private var items : Array public function Importer(space : Number, items : Array) { this.space = space, this.items = items } public function getItems() : Array { const result : Array = [] for each (var item : Object in items) if (item != null) result.push(getItem(item)) return result } private function getItem(item : Object) : Item { if (isCallbackFlexible(item)) getCallback(item)(getWidth(item)) return new Item(getDisplayObject(item), getWidth(item)) } private function getDisplayObject(item : Object) : DisplayObject { return isImplicit(item) ? item as DisplayObject : (item as Array)[0] } private function getWidth(item : Object) : Number { if (isExplicit(item)) return (item as Array)[1] else if (isFlexible(item)) return flexibleWidth else if (isImplicit(item)) return (item as DisplayObject).width else throw new Error } private function isImplicit(item : Object) : Boolean { return item is DisplayObject } private function isIgnoredFlexible(item : Object) : Boolean { return item is Array && !hasSecondEntry(item) } private function isExplicit(item : Object) : Boolean { return hasSecondEntry(item) && getSecondEntry(item) is Number } private function isCallbackFlexible(item : Object) : Boolean { return hasSecondEntry(item) && getSecondEntry(item) is Function } private function getCallback(item : Object) : Function { return getSecondEntry(item) as Function } private function hasSecondEntry(item : Object) : Boolean { return item is Array && (item as Array).length == 2 } private function getSecondEntry(item : Object) : Object { return (item as Array)[1] } private function isFlexible(item : Object) : Boolean { return isCallbackFlexible(item) || isIgnoredFlexible(item) } private function get flexibleWidth() : Number { return space / flexibleCount - totalStaticWidth } private function get totalStaticWidth() : Number { var result : Number = 0 for each (var item : Object in items) if (!isFlexible(item)) result += getWidth(item) return result } private function get flexibleCount() : int { var result : int = 0 for each (var item : Object in items) if (isFlexible(item)) ++result return result } }
package goplayer { import flash.display.DisplayObject public class Packer { private var base : Item private var items : Array public function Packer(base : Item, items : Array) { this.base = base, this.items = items } public function execute() : void { var current : Item = base for each (var item : Item in items) item.packLeft(current), current = item } public static function packLeft(space : Number, ... items : Array) : void { $packLeft(space, items) } public static function $packLeft(space : Number, items : Array) : void { if (items.length > 0) $$packLeft(new Importer(space, items).getItems()) } private static function $$packLeft(items : Array) : void { new Packer(items[0], items.slice(1)).execute() } } } import flash.display.DisplayObject class Item { private var object : DisplayObject private var _width : Number public function Item(object : DisplayObject, width : Number) { this.object = object, _width = width } public function get width() : Number { return _width } public function get right() : Number { return object.x + width } public function packLeft(base : Item) : void { object.x = base.right } } class Importer { private var space : Number private var items : Array public function Importer(space : Number, items : Array) { this.space = space, this.items = items } public function getItems() : Array { const result : Array = [] for each (var item : Object in items) if (item != null) result.push(getItem(item)) return result } private function getItem(item : Object) : Item { if (isCallbackFlexible(item)) getCallback(item)(getWidth(item)) return new Item(getDisplayObject(item), getWidth(item)) } private function getDisplayObject(item : Object) : DisplayObject { return isImplicit(item) ? item as DisplayObject : (item as Array)[0] } private function getWidth(item : Object) : Number { if (isExplicit(item)) return (item as Array)[1] else if (isFlexible(item)) return flexibleWidth else if (isImplicit(item)) return (item as DisplayObject).width else throw new Error("Invalid item: " + item) } private function isImplicit(item : Object) : Boolean { return item is DisplayObject } private function isIgnoredFlexible(item : Object) : Boolean { return item is Array && !hasSecondEntry(item) } private function isExplicit(item : Object) : Boolean { return hasSecondEntry(item) && getSecondEntry(item) is Number } private function isCallbackFlexible(item : Object) : Boolean { return hasSecondEntry(item) && getSecondEntry(item) is Function } private function getCallback(item : Object) : Function { return getSecondEntry(item) as Function } private function hasSecondEntry(item : Object) : Boolean { return item is Array && (item as Array).length == 2 } private function getSecondEntry(item : Object) : Object { return (item as Array)[1] } private function isFlexible(item : Object) : Boolean { return isCallbackFlexible(item) || isIgnoredFlexible(item) } private function get flexibleWidth() : Number { return space / flexibleCount - totalStaticWidth } private function get totalStaticWidth() : Number { var result : Number = 0 for each (var item : Object in items) if (!isFlexible(item)) result += getWidth(item) return result } private function get flexibleCount() : int { var result : int = 0 for each (var item : Object in items) if (isFlexible(item)) ++result return result } }
Add error message to Packer.
Add error message to Packer.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
06f07f63388d474e9dbdb8daa37c7647a35533d6
dolly-framework/src/main/actionscript/dolly/Cloner.as
dolly-framework/src/main/actionscript/dolly/Cloner.as
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import dolly.utils.ClassUtil; import flash.utils.ByteArray; import flash.utils.Dictionary; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary(); private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } private static function isTypePreparedForCloning(type:Type):Boolean { return _isClassPreparedForCloningMap[type.clazz]; } private static function failIfTypeIsNotCloneable(type:Type):void { if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } } private static function prepareTypeForCloning(type:Type):void { ClassUtil.registerAliasFor(type.clazz); _isClassPreparedForCloningMap[type.clazz] = true; } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { failIfTypeIsNotCloneable(type); if (!isTypePreparedForCloning(type)) { prepareTypeForCloning(type); } const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } dolly_internal static function doClone(source:*, type:Type = null):* { if (!type) { type = Type.forInstance(source); } if (!isTypePreparedForCloning(type)) { prepareTypeForCloning(type); } const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); for each(var field:Field in fieldsToClone) { var fieldType:Type = field.type; if (isTypeCloneable(fieldType) && !isTypePreparedForCloning(fieldType)) { prepareTypeForCloning(fieldType); } } const byteArray:ByteArray = new ByteArray(); byteArray.writeObject(source); byteArray.position = 0; const clonedInstance:* = byteArray.readObject(); return clonedInstance; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); failIfTypeIsNotCloneable(type); return doClone(source, type); } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import dolly.utils.ClassUtil; import flash.utils.ByteArray; import flash.utils.Dictionary; import org.as3commons.reflect.Accessor; import org.as3commons.reflect.AccessorAccess; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; use namespace dolly_internal; public class Cloner { private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary(); private static function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } private static function isTypePreparedForCloning(type:Type):Boolean { return _isClassPreparedForCloningMap[type.clazz]; } private static function failIfTypeIsNotCloneable(type:Type):void { if (!isTypeCloneable(type)) { throw new CloningError( CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE, CloningError.CLASS_IS_NOT_CLONEABLE_CODE ); } } private static function prepareTypeForCloning(type:Type):void { if (isTypePreparedForCloning(type)) { return; } ClassUtil.registerAliasFor(type.clazz); _isClassPreparedForCloningMap[type.clazz] = true; } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { failIfTypeIsNotCloneable(type); if (!isTypePreparedForCloning(type)) { prepareTypeForCloning(type); } const result:Vector.<Field> = new Vector.<Field>(); for each(var field:Field in type.properties) { if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) { result.push(field); } } return result; } dolly_internal static function doClone(source:*, type:Type = null):* { if (!type) { type = Type.forInstance(source); } prepareTypeForCloning(type); const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); for each(var field:Field in fieldsToClone) { var fieldType:Type = field.type; if (isTypeCloneable(fieldType)) { prepareTypeForCloning(fieldType); } } const byteArray:ByteArray = new ByteArray(); byteArray.writeObject(source); byteArray.position = 0; const clonedInstance:* = byteArray.readObject(); return clonedInstance; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); failIfTypeIsNotCloneable(type); return doClone(source, type); } } }
Move "if" statement checking for is type prepared for cloning to method Cloner.prepareTypeForCloning().
Move "if" statement checking for is type prepared for cloning to method Cloner.prepareTypeForCloning().
ActionScript
mit
Yarovoy/dolly
0435acc8340919cc2b55268597020bff3311db64
src/aerys/minko/render/geometry/stream/IndexStream.as
src/aerys/minko/render/geometry/stream/IndexStream.as
package aerys.minko.render.geometry.stream { import flash.utils.ByteArray; import flash.utils.Endian; import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.type.Signal; public final class IndexStream { use namespace minko_stream; minko_stream var _data : ByteArray; minko_stream var _localDispose : Boolean; private var _usage : uint; private var _resource : IndexBuffer3DResource; private var _length : uint; private var _locked : Boolean; private var _changed : Signal; private var _contextLost : Signal; public function get contextLost():Signal { return _contextLost; } public function get usage() : uint { return _usage; } public function get resource() : IndexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } public function set length(value : uint) : void { _data.length = value << 1; invalidate(); } public function get changed() : Signal { return _changed; } public function IndexStream(usage : uint, data : ByteArray = null, length : uint = 0) { super(); initialize(data, length, usage); } minko_stream function invalidate() : void { _data.position = 0; _length = _data.length >>> 1; if (_length % 3 != 0) throw new Error('Invalid size'); if (!_locked) _changed.execute(this); } private function initialize(data : ByteArray, length : uint, usage : uint) : void { _changed = new Signal('IndexStream.changed'); _usage = usage; _resource = new IndexBuffer3DResource(this); _data = new ByteArray(); _data.endian = Endian.LITTLE_ENDIAN; if (data) { if (data.endian != Endian.LITTLE_ENDIAN) throw new Error('Endianness must be Endian.LITTLE_ENDIAN.'); if (length == 0) length = data.bytesAvailable; if (length % 6 != 0) throw new Error('Invalid size'); data.readBytes(_data, 0, length); } else { _data = dummyData(length); } _data.position = 0; invalidate(); } public function get(index : uint) : uint { var value : uint = 0; checkReadUsage(this); _data.position = index << 1; value = _data.readUnsignedShort(); _data.position = 0; return value; } public function set(index : uint, value : uint) : void { checkWriteUsage(this); _data.position = index << 1; _data.writeShort(value); _data.position = 0; invalidate(); } public function deleteTriangle(triangleIndex : uint) : void { checkWriteUsage(this); _data.position = _data.length - 6; var v0 : uint = _data.readShort(); var v1 : uint = _data.readShort(); var v2 : uint = _data.readShort(); _data.position = triangleIndex * 12; _data.writeShort(v0); _data.writeShort(v1); _data.writeShort(v2); // _data.writeBytes(_data, triangleIndex * 12, 12); _data.length -= 6; _data.position = 0; invalidate(); } public function clone(usage : uint = 0) : IndexStream { return new IndexStream(usage || _usage, _data); } public function toString() : String { return _data.toString(); } public function concat(indexStream : IndexStream, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { checkReadUsage(indexStream); checkWriteUsage(this); pushBytes(indexStream._data, firstIndex, count, indexOffset); indexStream._data.position = 0; return this; } public function pushBytes(bytes : ByteArray, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { count ||= bytes.length >>> 1; _data.position = _data.length; if (indexOffset == 0) _data.writeBytes(bytes, firstIndex << 1, count << 1); else { bytes.position = firstIndex << 1; for (var i : uint = 0; i < count; ++i) _data.writeShort(bytes.readUnsignedShort() + indexOffset); } _data.position = 0; bytes.position = (firstIndex + count) << 1; invalidate(); return this; } public function pushVector(indices : Vector.<uint>, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : IndexStream { checkWriteUsage(this); var numIndices : int = _data.length; count ||= indices.length; _data.position = _data.length; for (var i : int = 0; i < count; ++i) _data.writeShort(indices[int(firstIndex + i)] + offset); _data.position = 0; invalidate(); return this; } public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream { return setTriangle(length, index1, index2, index3); } public function setTriangle(triangleIndex : uint, index1 : uint, index2 : uint, index3 : uint) : IndexStream { _data.position = triangleIndex << 1; _data.writeShort(index1); _data.writeShort(index2); _data.writeShort(index3); _data.position = 0; invalidate(); return this; } public function disposeLocalData(waitForUpload : Boolean = true) : void { if (waitForUpload && _length != resource.numIndices) _localDispose = true; else { _data = null; _usage = StreamUsage.STATIC; } } public function dispose() : void { _resource.dispose(); } public function lock() : ByteArray { checkReadUsage(this); _data.position = 0; _locked = true; return _data; } public function unlock(hasChanged : Boolean = true) : void { _data.position = 0; _locked = false; if (hasChanged) invalidate(); } /** * Clones the IndexStream by creating a new underlying ByteArray and applying an offset on the indices. * * @param indexStream The IndexStream to clone. * @param offset The offset to apply on the indices. * * @return The offseted new IndexStream. * */ public static function cloneWithOffset(indexStream : IndexStream, offset : uint = 0) : IndexStream { if (!(indexStream.usage & StreamUsage.READ)) { throw new Error('Unable to read from index stream: stream usage is not set to StreamUsage.READ.'); } var newData : ByteArray = new ByteArray(); newData.endian = Endian.LITTLE_ENDIAN; var oldData : ByteArray = indexStream._data; oldData.position = 0; while (oldData.bytesAvailable) { var index : uint = oldData.readUnsignedShort() + offset; newData.writeShort(index); } newData.position = 0; return new IndexStream(indexStream.usage, newData); } private static function checkReadUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.READ)) throw new Error( 'Unable to read from index stream: stream usage is not set to StreamUsage.READ.' ); } private static function checkWriteUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.WRITE)) throw new Error( 'Unable to write in index stream: stream usage is not set to StreamUsage.WRITE.' ); } public static function dummyData(size : uint, offset : uint = 0) : ByteArray { var indices : ByteArray = new ByteArray(); indices.endian = Endian.LITTLE_ENDIAN; for (var i : int = 0; i < size; ++i) indices.writeShort(i + offset); indices.position = 0; return indices; } public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream { var stream : IndexStream = new IndexStream(usage); var numIndices : uint = data.length; for (var i : uint = 0; i < numIndices; ++i) stream._data.writeShort(data[i]); stream._data.position = 0; stream._length = numIndices; return stream; } } }
package aerys.minko.render.geometry.stream { import flash.utils.ByteArray; import flash.utils.Endian; import aerys.minko.ns.minko_stream; import aerys.minko.render.resource.IndexBuffer3DResource; import aerys.minko.type.Signal; public final class IndexStream { use namespace minko_stream; minko_stream var _data : ByteArray; minko_stream var _localDispose : Boolean; private var _usage : uint; private var _resource : IndexBuffer3DResource; private var _length : uint; private var _locked : Boolean; private var _changed : Signal; private var _contextLost : Signal; public function get contextLost():Signal { return _contextLost; } public function get usage() : uint { return _usage; } public function get resource() : IndexBuffer3DResource { return _resource; } public function get length() : uint { return _length; } public function set length(value : uint) : void { _data.length = value << 1; invalidate(); } public function get changed() : Signal { return _changed; } public function IndexStream(usage : uint, data : ByteArray = null, length : uint = 0) { super(); initialize(data, length, usage); } minko_stream function invalidate() : void { _data.position = 0; _length = _data.length >>> 1; if (_length % 3 != 0) throw new Error('Invalid size'); if (!_locked) _changed.execute(this); } private function initialize(data : ByteArray, length : uint, usage : uint) : void { _changed = new Signal('IndexStream.changed'); _usage = usage; _resource = new IndexBuffer3DResource(this); _data = new ByteArray(); _data.endian = Endian.LITTLE_ENDIAN; if (data) { if (data.endian != Endian.LITTLE_ENDIAN) throw new Error('Endianness must be Endian.LITTLE_ENDIAN.'); if (length == 0) length = data.bytesAvailable; if (length % 6 != 0) throw new Error('Invalid size'); data.readBytes(_data, 0, length); } else { _data = dummyData(length); } _data.position = 0; invalidate(); } public function get(index : uint) : uint { var value : uint = 0; checkReadUsage(this); _data.position = index << 1; value = _data.readUnsignedShort(); _data.position = 0; return value; } public function set(index : uint, value : uint) : void { checkWriteUsage(this); _data.position = index << 1; _data.writeShort(value); _data.position = 0; invalidate(); } public function deleteTriangle(triangleIndex : uint) : void { checkWriteUsage(this); _data.position = _data.length - 6; var v0 : uint = _data.readShort(); var v1 : uint = _data.readShort(); var v2 : uint = _data.readShort(); _data.position = triangleIndex * 6; _data.writeShort(v0); _data.writeShort(v1); _data.writeShort(v2); // _data.writeBytes(_data, triangleIndex * 12, 12); _data.length -= 6; _data.position = 0; invalidate(); } public function clone(usage : uint = 0) : IndexStream { return new IndexStream(usage || _usage, _data); } public function toString() : String { return _data.toString(); } public function concat(indexStream : IndexStream, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { checkReadUsage(indexStream); checkWriteUsage(this); pushBytes(indexStream._data, firstIndex, count, indexOffset); indexStream._data.position = 0; return this; } public function pushBytes(bytes : ByteArray, firstIndex : uint = 0, count : uint = 0, indexOffset : uint = 0) : IndexStream { count ||= bytes.length >>> 1; _data.position = _data.length; if (indexOffset == 0) _data.writeBytes(bytes, firstIndex << 1, count << 1); else { bytes.position = firstIndex << 1; for (var i : uint = 0; i < count; ++i) _data.writeShort(bytes.readUnsignedShort() + indexOffset); } _data.position = 0; bytes.position = (firstIndex + count) << 1; invalidate(); return this; } public function pushVector(indices : Vector.<uint>, firstIndex : uint = 0, count : uint = 0, offset : uint = 0) : IndexStream { checkWriteUsage(this); var numIndices : int = _data.length; count ||= indices.length; _data.position = _data.length; for (var i : int = 0; i < count; ++i) _data.writeShort(indices[int(firstIndex + i)] + offset); _data.position = 0; invalidate(); return this; } public function pushTriangle(index1 : uint, index2 : uint, index3 : uint) : IndexStream { return setTriangle(length, index1, index2, index3); } public function setTriangle(triangleIndex : uint, index1 : uint, index2 : uint, index3 : uint) : IndexStream { _data.position = triangleIndex << 1; _data.writeShort(index1); _data.writeShort(index2); _data.writeShort(index3); _data.position = 0; invalidate(); return this; } public function disposeLocalData(waitForUpload : Boolean = true) : void { if (waitForUpload && _length != resource.numIndices) _localDispose = true; else { _data = null; _usage = StreamUsage.STATIC; } } public function dispose() : void { _resource.dispose(); } public function lock() : ByteArray { checkReadUsage(this); _data.position = 0; _locked = true; return _data; } public function unlock(hasChanged : Boolean = true) : void { _data.position = 0; _locked = false; if (hasChanged) invalidate(); } /** * Clones the IndexStream by creating a new underlying ByteArray and applying an offset on the indices. * * @param indexStream The IndexStream to clone. * @param offset The offset to apply on the indices. * * @return The offseted new IndexStream. * */ public static function cloneWithOffset(indexStream : IndexStream, offset : uint = 0) : IndexStream { if (!(indexStream.usage & StreamUsage.READ)) { throw new Error('Unable to read from index stream: stream usage is not set to StreamUsage.READ.'); } var newData : ByteArray = new ByteArray(); newData.endian = Endian.LITTLE_ENDIAN; var oldData : ByteArray = indexStream._data; oldData.position = 0; while (oldData.bytesAvailable) { var index : uint = oldData.readUnsignedShort() + offset; newData.writeShort(index); } newData.position = 0; return new IndexStream(indexStream.usage, newData); } private static function checkReadUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.READ)) throw new Error( 'Unable to read from index stream: stream usage is not set to StreamUsage.READ.' ); } private static function checkWriteUsage(stream : IndexStream) : void { if (!(stream._usage & StreamUsage.WRITE)) throw new Error( 'Unable to write in index stream: stream usage is not set to StreamUsage.WRITE.' ); } public static function dummyData(size : uint, offset : uint = 0) : ByteArray { var indices : ByteArray = new ByteArray(); indices.endian = Endian.LITTLE_ENDIAN; for (var i : int = 0; i < size; ++i) indices.writeShort(i + offset); indices.position = 0; return indices; } public static function fromVector(usage : uint, data : Vector.<uint>) : IndexStream { var stream : IndexStream = new IndexStream(usage); var numIndices : uint = data.length; for (var i : uint = 0; i < numIndices; ++i) stream._data.writeShort(data[i]); stream._data.position = 0; stream._length = numIndices; return stream; } } }
Fix delete triangle
Fix delete triangle
ActionScript
mit
aerys/minko-as3
bb65a1063af66e2f96710c5dd467db374f327f8a
krew-framework/krewfw/builtin_actor/ui/SimpleVirtualJoystick.as
krew-framework/krewfw/builtin_actor/ui/SimpleVirtualJoystick.as
package krewfw.builtin_actor.ui { import flash.display.Stage; import flash.events.KeyboardEvent; import flash.geom.Point; import flash.ui.Keyboard; import flash.utils.Dictionary; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Quad; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; import krewfw.NativeStageAccessor; import krewfw.core.KrewActor; /** * いわゆるバーチャルジョイスティック。 * * maxFingerMove に 100 を指定すると、中心から 100 ピクセル指を動かした際に * スティックの傾きが最大となる。maxImageMove はこのときのスティック画像の * 中心からの移動量である。 */ //------------------------------------------------------------ public class SimpleVirtualJoystick extends KrewActor { /** * ジョイスティックに対して触れた・動かした・離した際にこのイベントが投げられる。 * イベントの引数は {velocityX:Number, velocityY:Number}. * ジョイスティックの傾きの x, y 成分が [0, 1] の値で渡される。 * 離した際のイベントでは velocityX, velocityY は共に 0 となる。 */ public static const UPDATE_JOYSTICK:String = "krew.updateJoystick"; public var maxFingerMove:Number = 60; public var maxImageMove:Number = 40; private var _stickImage:DisplayObject; private var _keyDowns:Dictionary = new Dictionary(); private var _numKeyDown:int = 0; //------------------------------------------------------------ public function SimpleVirtualJoystick(holderImage:Image=null, stickImage:Image=null, touchSize:Number=130) { touchable = true; // default display object if (holderImage == null) { var defaultHolder:Quad = new Quad(100, 100, 0x777777); var defaultStick :Quad = new Quad( 50, 50, 0xee4444); _setCenterPivot(defaultHolder); _setCenterPivot(defaultStick); addChild(defaultHolder); addChild(defaultStick); _stickImage = defaultStick; } else { addImage(holderImage); addImage(stickImage); _stickImage = stickImage; } super.addTouchMarginNode(touchSize, touchSize); addEventListener(TouchEvent.TOUCH, _onTouch); _initKeyboardEventListener(); } private function _setCenterPivot(dispObj:DisplayObject):void { dispObj.pivotX = dispObj.width / 2; dispObj.pivotY = dispObj.height / 2; } protected override function onDispose():void { var stage:Stage = NativeStageAccessor.stage; if (stage == null) { return; } stage.removeEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown); stage.removeEventListener(KeyboardEvent.KEY_UP, _onKeyUp); } private function _onTouch(event:TouchEvent):void { var touchBegan:Touch = event.getTouch(this, TouchPhase.BEGAN); if (touchBegan) { _onTouchStart(touchBegan); } var touchMoved:Touch = event.getTouch(this, TouchPhase.MOVED); if (touchMoved) { _onTouchMove(touchMoved); } var touchEnded:Touch = event.getTouch(this, TouchPhase.ENDED); if (touchEnded) { _onTouchEnd(touchEnded); } } private function _onTouchStart(touchBegan:Touch):void { _onTouchMove(touchBegan); } private function _onTouchMove(touchMoved:Touch):void { var localPos:Point = touchMoved.getLocation(this); var stickX:Number = localPos.x; var stickY:Number = localPos.y; var fingerDistance:Number = krew.getDistance(0, 0, stickX, stickY); var scaleToFingerLimit:Number = fingerDistance / maxFingerMove; if (scaleToFingerLimit > 1) { stickX /= scaleToFingerLimit; stickY /= scaleToFingerLimit; } var moveScale:Number = maxImageMove / maxFingerMove; _stickImage.x = stickX * moveScale; _stickImage.y = stickY * moveScale; sendMessage(UPDATE_JOYSTICK, { velocityX: _stickImage.x / maxImageMove, velocityY: _stickImage.y / maxImageMove }); } private function _onTouchEnd(touchEnded:Touch):void { _stickImage.x = 0; _stickImage.y = 0; sendMessage(UPDATE_JOYSTICK, {velocityX: 0, velocityY: 0}); } public override function onUpdate(passedTime:Number):void { _onKeyUpdate(); } //------------------------------------------------------------ // Keyboard Event //------------------------------------------------------------ private function _initKeyboardEventListener():void { var stage:Stage = NativeStageAccessor.stage; if (stage == null) { return; } stage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP, _onKeyUp); } private function _onKeyDown(event:KeyboardEvent):void { if (!_keyDowns[event.keyCode]) { ++_numKeyDown; } _keyDowns[event.keyCode] = true; } private function _onKeyUp(event:KeyboardEvent):void { if (_keyDowns[event.keyCode]) { --_numKeyDown; } _keyDowns[event.keyCode] = false; // 全部離したタイミング if (_numKeyDown == 0) { sendMessage(UPDATE_JOYSTICK, { velocityX: 0, velocityY: 0 }); } } /** * PC 用にキーボードでの操作でもメッセージを投げる。 * マウスでジョイスティックが動かされていた場合はそちらを優先 */ private function _onKeyUpdate():void { if (_numKeyDown == 0) { return; } if (!(_stickImage.x == 0 && _stickImage.y == 0)) { return; } var keyVelocityX:Number = 0; var keyVelocityY:Number = 0; if (_keyDowns[Keyboard.LEFT ]) { keyVelocityX -= 1.0; } if (_keyDowns[Keyboard.RIGHT]) { keyVelocityX += 1.0; } if (_keyDowns[Keyboard.UP ]) { keyVelocityY -= 1.0; } if (_keyDowns[Keyboard.DOWN ]) { keyVelocityY += 1.0; } sendMessage(UPDATE_JOYSTICK, { velocityX: keyVelocityX, velocityY: keyVelocityY }); } } }
package krewfw.builtin_actor.ui { import flash.display.Stage; import flash.events.KeyboardEvent; import flash.geom.Point; import flash.ui.Keyboard; import flash.utils.Dictionary; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Quad; import starling.events.Touch; import starling.events.TouchEvent; import starling.events.TouchPhase; import krewfw.NativeStageAccessor; import krewfw.core.KrewActor; /** * いわゆるバーチャルジョイスティック。 * * maxFingerMove に 100 を指定すると、中心から 100 ピクセル指を動かした際に * スティックの傾きが最大となる。maxImageMove はこのときのスティック画像の * 中心からの移動量である。 */ //------------------------------------------------------------ public class SimpleVirtualJoystick extends KrewActor { /** * ジョイスティックに対して触れた・動かした・離した際にこのイベントが投げられる。 * イベントの引数は {velocityX:Number, velocityY:Number}. * ジョイスティックの傾きの x, y 成分が [0, 1] の値で渡される。 * 離した際のイベントでは velocityX, velocityY は共に 0 となる。 */ public static const UPDATE_JOYSTICK:String = "krew.updateJoystick"; public var maxFingerMove:Number = 60; public var maxImageMove:Number = 40; private var _stickImage:DisplayObject; private var _keyDowns:Dictionary = new Dictionary(); private var _numKeyDown:int = 0; //------------------------------------------------------------ public function SimpleVirtualJoystick(holderImage:Image=null, stickImage:Image=null, touchSize:Number=130) { touchable = true; // default display object if (holderImage == null) { var defaultHolder:Quad = new Quad(100, 100, 0x777777); var defaultStick :Quad = new Quad( 50, 50, 0xee4444); _setCenterPivot(defaultHolder); _setCenterPivot(defaultStick); addChild(defaultHolder); addChild(defaultStick); _stickImage = defaultStick; } else { addImage(holderImage); addImage(stickImage); _stickImage = stickImage; } super.addTouchMarginNode(touchSize, touchSize); addEventListener(TouchEvent.TOUCH, _onTouch); _initKeyboardEventListener(); } private function _setCenterPivot(dispObj:DisplayObject):void { dispObj.pivotX = dispObj.width / 2; dispObj.pivotY = dispObj.height / 2; } protected override function onDispose():void { var stage:Stage = NativeStageAccessor.stage; if (stage == null) { return; } stage.removeEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown); stage.removeEventListener(KeyboardEvent.KEY_UP, _onKeyUp); } private function _onTouch(event:TouchEvent):void { var touchBegan:Touch = event.getTouch(this, TouchPhase.BEGAN); if (touchBegan) { _onTouchStart(touchBegan); } var touchMoved:Touch = event.getTouch(this, TouchPhase.MOVED); if (touchMoved) { _onTouchMove(touchMoved); } var touchEnded:Touch = event.getTouch(this, TouchPhase.ENDED); if (touchEnded) { _onTouchEnd(touchEnded); } } private function _onTouchStart(touchBegan:Touch):void { _onTouchMove(touchBegan); } private function _onTouchMove(touchMoved:Touch):void { var localPos:Point = touchMoved.getLocation(this); var stickX:Number = localPos.x; var stickY:Number = localPos.y; var fingerDistance:Number = krew.distance(0, 0, stickX, stickY); var scaleToFingerLimit:Number = fingerDistance / maxFingerMove; if (scaleToFingerLimit > 1) { stickX /= scaleToFingerLimit; stickY /= scaleToFingerLimit; } var moveScale:Number = maxImageMove / maxFingerMove; _stickImage.x = stickX * moveScale; _stickImage.y = stickY * moveScale; sendMessage(UPDATE_JOYSTICK, { velocityX: _stickImage.x / maxImageMove, velocityY: _stickImage.y / maxImageMove }); } private function _onTouchEnd(touchEnded:Touch):void { _stickImage.x = 0; _stickImage.y = 0; sendMessage(UPDATE_JOYSTICK, {velocityX: 0, velocityY: 0}); } public override function onUpdate(passedTime:Number):void { _onKeyUpdate(); } //------------------------------------------------------------ // Keyboard Event //------------------------------------------------------------ private function _initKeyboardEventListener():void { var stage:Stage = NativeStageAccessor.stage; if (stage == null) { return; } stage.addEventListener(KeyboardEvent.KEY_DOWN, _onKeyDown); stage.addEventListener(KeyboardEvent.KEY_UP, _onKeyUp); } private function _onKeyDown(event:KeyboardEvent):void { if (!_keyDowns[event.keyCode]) { ++_numKeyDown; } _keyDowns[event.keyCode] = true; } private function _onKeyUp(event:KeyboardEvent):void { if (_keyDowns[event.keyCode]) { --_numKeyDown; } _keyDowns[event.keyCode] = false; // 全部離したタイミング if (_numKeyDown == 0) { sendMessage(UPDATE_JOYSTICK, { velocityX: 0, velocityY: 0 }); } } /** * PC 用にキーボードでの操作でもメッセージを投げる。 * マウスでジョイスティックが動かされていた場合はそちらを優先 */ private function _onKeyUpdate():void { if (_numKeyDown == 0) { return; } if (!(_stickImage.x == 0 && _stickImage.y == 0)) { return; } var keyVelocityX:Number = 0; var keyVelocityY:Number = 0; if (_keyDowns[Keyboard.LEFT ]) { keyVelocityX -= 1.0; } if (_keyDowns[Keyboard.RIGHT]) { keyVelocityX += 1.0; } if (_keyDowns[Keyboard.UP ]) { keyVelocityY -= 1.0; } if (_keyDowns[Keyboard.DOWN ]) { keyVelocityY += 1.0; } sendMessage(UPDATE_JOYSTICK, { velocityX: keyVelocityX, velocityY: keyVelocityY }); } } }
Fix old interface
Fix old interface
ActionScript
mit
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
a3397af4366466c972a4f157c4fc553bd8870b76
plugins/akamaiMediaAnalyticsPlugin/src/com/kaltura/kdpfl/plugin/akamaiMediaAnalyticsMediator.as
plugins/akamaiMediaAnalyticsPlugin/src/com/kaltura/kdpfl/plugin/akamaiMediaAnalyticsMediator.as
package com.kaltura.kdpfl.plugin { import com.akamai.playeranalytics.AnalyticsPluginLoader; import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.model.type.StreamerType; import com.kaltura.types.KalturaMediaType; import com.kaltura.vo.KalturaBaseEntry; import com.kaltura.vo.KalturaFlavorAsset; import com.kaltura.vo.KalturaMediaEntry; import flash.system.Capabilities; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class akamaiMediaAnalyticsMediator extends Mediator { public static const NAME:String = "akamaiMediaAnalyticsMediator"; private var _mediaProxy:MediaProxy; public function akamaiMediaAnalyticsMediator(viewComponent:Object=null) { super(NAME, viewComponent); } override public function onRegister():void { _mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; super.onRegister(); } override public function listNotificationInterests():Array { return [NotificationType.MEDIA_READY, NotificationType.MEDIA_ELEMENT_READY, NotificationType.SWITCHING_CHANGE_COMPLETE]; } override public function handleNotification(notification:INotification):void { switch (notification.getName()) { case NotificationType.MEDIA_READY: //populate analytics metadata var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy; var entry:KalturaBaseEntry = _mediaProxy.vo.entry; AnalyticsPluginLoader.setData("title", entry.name); AnalyticsPluginLoader.setData("entryId", entry.id); AnalyticsPluginLoader.setData("category", entry.categories); AnalyticsPluginLoader.setData("partnerId", configProxy.vo.flashvars.partnerId); //find content type if (entry is KalturaMediaEntry) { var mediaEntry:KalturaMediaEntry = entry as KalturaMediaEntry; AnalyticsPluginLoader.setData("contentLength", mediaEntry.duration); var contentType:String; switch (mediaEntry.mediaType) { case KalturaMediaType.VIDEO: contentType = "video"; break; case KalturaMediaType.AUDIO: contentType = "audio"; break; case KalturaMediaType.IMAGE: contentType = "image"; break; default: contentType = "live"; } AnalyticsPluginLoader.setData("contentType", contentType); } AnalyticsPluginLoader.setData("device", Capabilities.os ); AnalyticsPluginLoader.setData("playerId", configProxy.vo.flashvars.uiConfId); break; case NotificationType.SWITCHING_CHANGE_COMPLETE: AnalyticsPluginLoader.setData("flavorId", getFlavorIdByIndex(notification.getBody().newIndex)); break; case NotificationType.MEDIA_ELEMENT_READY: //find starting flavor ID var flavorId:String; if (_mediaProxy.vo.deliveryType == StreamerType.HTTP) { flavorId = _mediaProxy.vo.selectedFlavorId; } else if (_mediaProxy.vo.deliveryType == StreamerType.RTMP) { flavorId = getFlavorIdByIndex(_mediaProxy.startingIndex); } if (flavorId) AnalyticsPluginLoader.setData("flavorId", flavorId); break; } } /** * returns the id of the flavor asset in the given index. null if index is invalid. * @param index * @return * */ private function getFlavorIdByIndex(index:int):String { var flavorId:String; if (index >= 0 && _mediaProxy.vo.kalturaMediaFlavorArray && index < _mediaProxy.vo.kalturaMediaFlavorArray.length) { flavorId = (_mediaProxy.vo.kalturaMediaFlavorArray[index] as KalturaFlavorAsset).id; } return flavorId; } } }
package com.kaltura.kdpfl.plugin { import com.akamai.playeranalytics.AnalyticsPluginLoader; import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.model.type.NotificationType; import com.kaltura.kdpfl.model.type.StreamerType; import com.kaltura.types.KalturaMediaType; import com.kaltura.vo.KalturaBaseEntry; import com.kaltura.vo.KalturaFlavorAsset; import com.kaltura.vo.KalturaMediaEntry; import flash.system.Capabilities; import org.puremvc.as3.interfaces.INotification; import org.puremvc.as3.patterns.mediator.Mediator; public class akamaiMediaAnalyticsMediator extends Mediator { public static const NAME:String = "akamaiMediaAnalyticsMediator"; private var _mediaProxy:MediaProxy; public function akamaiMediaAnalyticsMediator(viewComponent:Object=null) { super(NAME, viewComponent); } override public function onRegister():void { _mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy; super.onRegister(); } override public function listNotificationInterests():Array { return [NotificationType.MEDIA_READY, NotificationType.MEDIA_ELEMENT_READY]; } override public function handleNotification(notification:INotification):void { switch (notification.getName()) { case NotificationType.MEDIA_READY: //populate analytics metadata var configProxy:ConfigProxy = facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy; var entry:KalturaBaseEntry = _mediaProxy.vo.entry; AnalyticsPluginLoader.setData("title", entry.name); AnalyticsPluginLoader.setData("entryId", entry.id); AnalyticsPluginLoader.setData("category", entry.categories); AnalyticsPluginLoader.setData("publisherId", configProxy.vo.flashvars.partnerId); //find content type if (entry is KalturaMediaEntry) { var mediaEntry:KalturaMediaEntry = entry as KalturaMediaEntry; AnalyticsPluginLoader.setData("contentLength", mediaEntry.duration); var contentType:String; switch (mediaEntry.mediaType) { case KalturaMediaType.VIDEO: contentType = "video"; break; case KalturaMediaType.AUDIO: contentType = "audio"; break; case KalturaMediaType.IMAGE: contentType = "image"; break; default: contentType = "live"; } AnalyticsPluginLoader.setData("contentType", contentType); } AnalyticsPluginLoader.setData("device", Capabilities.os ); AnalyticsPluginLoader.setData("playerId", configProxy.vo.flashvars.uiConfId); break; case NotificationType.MEDIA_ELEMENT_READY: //find starting flavor ID var flavorId:String; if (_mediaProxy.vo.deliveryType == StreamerType.HTTP) { flavorId = _mediaProxy.vo.selectedFlavorId; } else if (_mediaProxy.vo.deliveryType == StreamerType.RTMP) { flavorId = getFlavorIdByIndex(_mediaProxy.startingIndex); } if (flavorId) AnalyticsPluginLoader.setData("flavorId", flavorId); break; } } /** * returns the id of the flavor asset in the given index. null if index is invalid. * @param index * @return * */ private function getFlavorIdByIndex(index:int):String { var flavorId:String; if (index >= 0 && _mediaProxy.vo.kalturaMediaFlavorArray && index < _mediaProxy.vo.kalturaMediaFlavorArray.length) { flavorId = (_mediaProxy.vo.kalturaMediaFlavorArray[index] as KalturaFlavorAsset).id; } return flavorId; } } }
fix custom data after a clarification call with akamai
qnd: fix custom data after a clarification call with akamai git-svn-id: 3f608e5a9a704dd448217c0a64c508e7f145cfa1@87779 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
shvyrev/kdp,kaltura/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp
91b476f71c7eb672e0a3f9fee81d1e4a078a5586
src/aerys/minko/scene/node/mesh/Mesh.as
src/aerys/minko/scene/node/mesh/Mesh.as
package aerys.minko.scene.node.mesh { import aerys.minko.render.effect.Effect; import aerys.minko.render.effect.basic.BasicShader; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.mesh.geometry.Geometry; import aerys.minko.type.Signal; import aerys.minko.type.bounding.FrustumCulling; import aerys.minko.type.data.DataBindings; import aerys.minko.type.data.DataProvider; import aerys.minko.type.enum.DataProviderUsage; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractSceneNode { public static const DEFAULT_EFFECT : Effect = new Effect( new BasicShader() ); private var _geometry : Geometry = null; private var _effect : Effect = null; private var _properties : DataProvider = null; private var _material : DataProvider = null; private var _bindings : DataBindings = null; private var _visibility : MeshVisibilityController = new MeshVisibilityController(); private var _frame : uint = 0; private var _cloned : Signal = new Signal('Mesh.clones'); private var _effectChanged : Signal = new Signal('Mesh.effectChanged'); private var _frameChanged : Signal = new Signal('Mesh.frameChanged'); private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged'); /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : DataProvider { return _material; } public function set material(value : DataProvider) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); _material = value; if (value) _bindings.addProvider(value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Effect used for rendering. * @return * */ public function get effect() : Effect { return _effect; } public function set effect(value : Effect) : void { if (_effect == value) return ; if (value == null) throw new Error(); var oldEffect : Effect = _effect; _effect = value; _effectChanged.execute(this, oldEffect, value); } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { if (_geometry != value) { var oldGeometry : Geometry = _geometry; _geometry = value; _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh is visible or not. * * @return * */ public function get visibility() : MeshVisibilityController { return _visibility; } public function get cloned() : Signal { return _cloned; } public function get effectChanged() : Signal { return _effectChanged; } public function get frameChanged() : Signal { return _frameChanged; } public function get geometryChanged() : Signal { return _geometryChanged; } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { if (_frame != value) { var oldFrame : uint = _frame; _frame = value; _frameChanged.execute(this, oldFrame, value); } } public function Mesh(geometry : Geometry = null, properties : Object = null, effect : Effect = null, ...controllers) { super(); initialize(geometry, properties, effect, controllers); } private function initialize(geometry : Geometry, properties : Object, effect : Effect, controllers : Array) : void { this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE); _bindings = new DataBindings(this); _geometry = geometry; this.effect = effect || DEFAULT_EFFECT; _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); while (controllers && !(controllers[0] is AbstractController)) controllers = controllers[0]; if (controllers) for each (var ctrl : AbstractController in controllers) addController(ctrl); } override public function clone(cloneControllers : Boolean = false) : ISceneNode { var clone : Mesh = new Mesh(); clone.copyFrom(this, true, cloneControllers); return clone; } override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { super.addedToSceneHandler(child, scene); if (child === this) _bindings.addProvider(transformData); } override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { super.removedFromSceneHandler(child, scene); if (child === this) _bindings.removeProvider(transformData); } protected function copyFrom(source : Mesh, withBindings : Boolean, cloneControllers : Boolean) : void { var numControllers : uint = source.numControllers; name = source.name; geometry = source._geometry; properties = DataProvider(source._properties.clone()); _visibility = source._visibility.clone() as MeshVisibilityController; _bindings.copySharedProvidersFrom(source._bindings); copyControllersFrom(source, this, cloneControllers); transform.copyFrom(source.transform); effect = source._effect; source.cloned.execute(this, source); } } }
package aerys.minko.scene.node.mesh { import aerys.minko.render.effect.Effect; import aerys.minko.render.effect.basic.BasicShader; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.mesh.MeshVisibilityController; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.scene.node.ISceneNode; import aerys.minko.scene.node.Scene; import aerys.minko.scene.node.mesh.geometry.Geometry; import aerys.minko.type.Signal; import aerys.minko.type.bounding.FrustumCulling; import aerys.minko.type.data.DataBindings; import aerys.minko.type.data.DataProvider; import aerys.minko.type.enum.DataProviderUsage; /** * Mesh objects are a visible instance of a Geometry rendered using a specific * Effect with specific rendering properties. * * <p> * Those rendering properties are stored in a DataBindings object so they can * be directly used by the shaders in the rendering API. * </p> * * @author Jean-Marc Le Roux * */ public class Mesh extends AbstractSceneNode { public static const DEFAULT_EFFECT : Effect = new Effect( new BasicShader() ); private var _geometry : Geometry = null; private var _effect : Effect = null; private var _properties : DataProvider = null; private var _material : DataProvider = null; private var _bindings : DataBindings = null; private var _visibility : MeshVisibilityController = new MeshVisibilityController(); private var _frame : uint = 0; private var _cloned : Signal = new Signal('Mesh.clones'); private var _effectChanged : Signal = new Signal('Mesh.effectChanged'); private var _frameChanged : Signal = new Signal('Mesh.frameChanged'); private var _geometryChanged : Signal = new Signal('Mesh.geometryChanged'); /** * A DataProvider object already bound to the Mesh bindings. * * <pre> * // set the "diffuseColor" property to 0x0000ffff * mesh.properties.diffuseColor = 0x0000ffff; * * // animate the "diffuseColor" property * mesh.addController( * new AnimationController( * new &lt;ITimeline&gt;[new ColorTimeline( * "dataProvider.diffuseColor", * 5000, * new &lt;uint&gt;[0xffffffff, 0xffffff00, 0xffffffff] * )] * ) * ); * </pre> * * @return * */ public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get material() : DataProvider { return _material; } public function set material(value : DataProvider) : void { if (_material != value) { if (_material) _bindings.removeProvider(_material); _material = value; if (value) _bindings.addProvider(value); } } /** * The rendering properties provided to the shaders to customize * how the mesh will appear on screen. * * @return * */ public function get bindings() : DataBindings { return _bindings; } /** * The Effect used for rendering. * @return * */ public function get effect() : Effect { return _effect; } public function set effect(value : Effect) : void { if (_effect == value) return ; if (value == null) throw new Error(); var oldEffect : Effect = _effect; _effect = value; _effectChanged.execute(this, oldEffect, value); } /** * The Geometry of the mesh. * @return * */ public function get geometry() : Geometry { return _geometry; } public function set geometry(value : Geometry) : void { if (_geometry != value) { var oldGeometry : Geometry = _geometry; _geometry = value; _geometryChanged.execute(this, oldGeometry, value); } } /** * Whether the mesh is visible or not. * * @return * */ public function get visibility() : MeshVisibilityController { return _visibility; } public function get cloned() : Signal { return _cloned; } public function get effectChanged() : Signal { return _effectChanged; } public function get frameChanged() : Signal { return _frameChanged; } public function get geometryChanged() : Signal { return _geometryChanged; } public function get frame() : uint { return _frame; } public function set frame(value : uint) : void { if (_frame != value) { var oldFrame : uint = _frame; _frame = value; _frameChanged.execute(this, oldFrame, value); } } public function Mesh(geometry : Geometry = null, properties : Object = null, effect : Effect = null, ...controllers) { super(); initialize(geometry, properties, effect, controllers); } private function initialize(geometry : Geometry, properties : Object, effect : Effect, controllers : Array) : void { _bindings = new DataBindings(this); this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE); _geometry = geometry; this.effect = effect || DEFAULT_EFFECT; _visibility.frustumCulling = FrustumCulling.ENABLED; addController(_visibility); while (controllers && !(controllers[0] is AbstractController)) controllers = controllers[0]; if (controllers) for each (var ctrl : AbstractController in controllers) addController(ctrl); } override public function clone(cloneControllers : Boolean = false) : ISceneNode { var clone : Mesh = new Mesh(); clone.copyFrom(this, true, cloneControllers); return clone; } override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { super.addedToSceneHandler(child, scene); if (child === this) _bindings.addProvider(transformData); } override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { super.removedFromSceneHandler(child, scene); if (child === this) _bindings.removeProvider(transformData); } protected function copyFrom(source : Mesh, withBindings : Boolean, cloneControllers : Boolean) : void { var numControllers : uint = source.numControllers; name = source.name; geometry = source._geometry; properties = DataProvider(source._properties.clone()); _visibility = source._visibility.clone() as MeshVisibilityController; _bindings.copySharedProvidersFrom(source._bindings); copyControllersFrom(source, this, cloneControllers); transform.copyFrom(source.transform); effect = source._effect; source.cloned.execute(this, source); } } }
Fix binding instanciation order.
Fix binding instanciation order.
ActionScript
mit
aerys/minko-as3
2a4ba949e043cf76d978f116ba6e58a121fd209f
src/corsaair/tool/hash/App.as
src/corsaair/tool/hash/App.as
package corsaair.tool.hash { import C.stdlib.*; import cli.args.*; import encoding.ansi.AnsiString; import flash.utils.ByteArray; import hash.ap; import hash.bkdr; import hash.brp; import hash.dek; import hash.djb; import hash.elf; import hash.fnv; import hash.js; import hash.pjw; import hash.rs; import hash.sdbm; import shell.FileSystem; public class App { private var _parser:ArgParser; private var _results:ArgResults; public var executableName:String; public var description:String; public function App() { super(); _ctor(); } private function _ctor():void { _parser = new ArgParser(); _parser.addFlag( "DEBUG", "D", "Debugging", false, false, null, true ); _parser.addFlag( "help", "h", "Print this usage information.", false, false ); _parser.addFlag( "verbose", "v", "Show additional diagnostic informations.", false, false ); _parser.addOption( "hash", "a", "Hashing function used", "", [ "ap", "bkdr", "brp", "dek", "djb", "elf", "fnv", "js", "pjw", "rs", "sdbm" ], { ap: "Arash Partow hash function", bkdr: "Brian Kernighan and Dennis Ritchie hash function", brp: "Bruno R. Preiss hash function", dek: "Donald E. Knuth hash function", djb: "Professor Daniel J. Bernstein hash function", elf: "ELF hash function", fnv: "Fowler–Noll–Vo hash function", js: "Justin Sobel hash function", pjw: "Peter J. Weinberger hash function", rs: "Robert Sedgwicks hash function", sdbm: "open source SDBM project hash function" }, "ap" ); _parser.addOption( "format", "f", "Output format used", "", [ "hex", "num" ], { hex: "hexadecimal", num: "numeric" }, "hex" ); _parser.addOption( "color", "c", "Output color", "", [ "none", "red", "green", "blue" ], { none: "no color", red: "red color", green: "green color", blue: "blue color" }, "none" ); executableName = "as3hash"; description = "Multiple hashing functions."; } private function _uintToHex( n:uint ):String { var hex:String = n.toString( 16 ); if( hex.length%2 != 0 ) { hex = "0" + hex; } return hex; } public function showUsage( message:String = "" ):void { trace( executableName + " - " + description + "\n" ); if( message != "" ) { trace( message ); } trace( "Usage: " ); trace( _parser.usage ); } public function main( argv:Array = null ):void { if( (argv == null) || (argv && argv.length == 0) ) { showUsage(); exit( EXIT_FAILURE ); } try { _results = _parser.parse( argv ); } catch( e:SyntaxError ) { showUsage( e.message ); exit( EXIT_FAILURE ); } if( _results[ "DEBUG" ] ) { trace( "" ); trace( JSON.stringify( _results, null, " " ) ); trace( "" ); trace( " help = " + _results[ "help" ] ); trace( "verbose = " + _results[ "verbose" ] ); trace( " hash = " + _results[ "hash" ] ); trace( " format = " + _results[ "format" ] ); trace( " color = " + _results[ "color" ] ); trace( " string = " + _results.rest[0] ); } if( _results.options[ "help" ] == true ) { showUsage(); } else { var str:String = ""; var type:String; var tmp:String = _results.rest.join( " " ); if( tmp ) { str = tmp; } if( _results[ "DEBUG" ] ) { trace( " str = " + str ); } var bytes:ByteArray = new ByteArray(); if( (str != "") && FileSystem.exists( str ) ) { bytes = FileSystem.readByteArray( str ); type = "file"; } else { bytes.writeUTFBytes( str ); type = "string"; } bytes.position = 0; var hash:uint = 0; switch( _results[ "hash" ] ) { case "ap": hash = ap( bytes ); break; case "bkdr": hash = bkdr( bytes ); break; case "brp": hash = brp( bytes ); break; case "dek": hash = dek( bytes ); break; case "djb": hash = djb( bytes ); break; case "elf": hash = elf( bytes ); break; case "fnv": hash = fnv( bytes ); break; case "js": hash = js( bytes ); break; case "pjw": hash = pjw( bytes ); break; case "rs": hash = rs( bytes ); break; case "sdbm": hash = sdbm( bytes ); break; } if( _results[ "DEBUG" ] ) { trace( " hash = " + hash ); } var result:String = ""; switch( _results[ "format" ] ) { case "num": result = String( hash ); break; case "hex": result = _uintToHex( hash ); break; } switch( _results[ "color" ] ) { case "red": result += "「R! 」"; break; case "green": result += "「G! 」"; break; case "blue": result += "「B! 」"; break; case "none": default: // nothing } if( _results[ "color" ] != "none" ) { var ansi:AnsiString = new AnsiString( result ); result = ansi.toString(); } if( _results[ "verbose" ] ) { var pre:String = _results[ "hash" ]; var sep:String = ":"; var post:String = type; if( _results[ "color" ] != "none" ) { var tmp1:AnsiString = new AnsiString( pre + "「W! 」" ); pre = tmp1.toString(); var tmp2:AnsiString = new AnsiString( sep + "「K! 」" ); sep = tmp2.toString(); var tmp3:AnsiString = new AnsiString( post + "「Y! 」" ); post = tmp3.toString(); } trace( pre + sep + result + sep + post ); } else { trace( result ); } } exit( EXIT_SUCCESS ); } } }
package corsaair.tool.hash { import C.stdlib.*; import cli.args.*; import encoding.ansi.AnsiString; import flash.utils.ByteArray; import hash.ap; import hash.bkdr; import hash.brp; import hash.dek; import hash.djb; import hash.elf; import hash.fnv; import hash.js; import hash.pjw; import hash.rs; import hash.sdbm; import shell.FileSystem; public class App { private var _parser:ArgParser; private var _results:ArgResults; public var executableName:String; public var description:String; public function App() { super(); _ctor(); } private function _ctor():void { _parser = new ArgParser(); _parser.addFlag( "DEBUG", "D", "Debugging", false, false, null, true ); _parser.addFlag( "help", "h", "Print this usage information.", false, false ); _parser.addFlag( "verbose", "v", "Show additional diagnostic informations.", false, false ); _parser.addOption( "hash", "a", "Hashing function used", "", [ "ap", "bkdr", "brp", "dek", "djb", "elf", "fnv", "js", "pjw", "rs", "sdbm" ], { ap: "Arash Partow hash function", bkdr: "Brian Kernighan and Dennis Ritchie hash function", brp: "Bruno R. Preiss hash function", dek: "Donald E. Knuth hash function", djb: "Professor Daniel J. Bernstein hash function", elf: "ELF hash function", fnv: "Fowler–Noll–Vo hash function", js: "Justin Sobel hash function", pjw: "Peter J. Weinberger hash function", rs: "Robert Sedgwicks hash function", sdbm: "open source SDBM project hash function" }, "ap" ); _parser.addOption( "format", "f", "Output format used", "", [ "hex", "num" ], { hex: "hexadecimal", num: "numeric" }, "hex" ); _parser.addOption( "color", "c", "Output color", "", [ "none", "red", "green", "blue" ], { none: "no color", red: "red color", green: "green color", blue: "blue color" }, "none" ); executableName = "as3hash"; description = "Multiple hashing functions."; } private function _uintToHex( n:uint ):String { var hex:String = n.toString( 16 ); if( hex.length%2 != 0 ) { hex = "0" + hex; } return hex; } public function showUsage( message:String = "" ):void { trace( executableName + " - " + description + "\n" ); if( message != "" ) { trace( message ); } trace( "Usage: " ); trace( _parser.usage ); } public function main( argv:Array = null ):void { if( (argv == null) || (argv && argv.length == 0) ) { showUsage(); exit( EXIT_FAILURE ); } try { _results = _parser.parse( argv ); } catch( e:SyntaxError ) { showUsage( e.message ); exit( EXIT_FAILURE ); } if( _results[ "DEBUG" ] ) { trace( "" ); trace( JSON.stringify( _results, null, " " ) ); trace( "" ); trace( " help = " + _results[ "help" ] ); trace( "verbose = " + _results[ "verbose" ] ); trace( " hash = " + _results[ "hash" ] ); trace( " format = " + _results[ "format" ] ); trace( " color = " + _results[ "color" ] ); trace( " string = " + _results.rest[0] ); } if( _results.options[ "help" ] == true ) { showUsage(); } else { var str:String = ""; var type:String; var tmp:String = _results.rest.join( " " ); if( tmp ) { str = tmp; } if( _results[ "DEBUG" ] ) { trace( " str = " + str ); } var bytes:ByteArray = new ByteArray(); if( (str != "") && FileSystem.exists( str ) ) { bytes = FileSystem.readByteArray( str ); type = "file"; } else { bytes.writeUTFBytes( str ); type = "string"; } bytes.position = 0; var hash:uint = 0; switch( _results[ "hash" ] ) { case "ap": hash = ap( bytes ); break; case "bkdr": hash = bkdr( bytes ); break; case "brp": hash = brp( bytes ); break; case "dek": hash = dek( bytes ); break; case "djb": hash = djb( bytes ); break; case "elf": hash = elf( bytes ); break; case "fnv": hash = fnv( bytes ); break; case "js": hash = js( bytes ); break; case "pjw": hash = pjw( bytes ); break; case "rs": hash = rs( bytes ); break; case "sdbm": hash = sdbm( bytes ); break; } if( _results[ "DEBUG" ] ) { trace( " hash = " + hash ); } var result:String = ""; switch( _results[ "format" ] ) { case "num": result = String( hash ); break; case "hex": result = _uintToHex( hash ); break; } switch( _results[ "color" ] ) { case "red": result += "「R! 」"; break; case "green": result += "「G! 」"; break; case "blue": result += "「B! 」"; break; case "none": default: // nothing } if( _results[ "color" ] != "none" ) { var ansi:AnsiString = new AnsiString( result ); result = ansi.toString(); } if( _results[ "verbose" ] ) { var pre:String = _results[ "hash" ]; var sep:String = ":"; var post:String = type; if( _results[ "color" ] != "none" ) { var tmp1:AnsiString = new AnsiString( pre + "「W! 」" ); pre = tmp1.toString(); var tmp2:AnsiString = new AnsiString( sep + "「K! 」" ); sep = tmp2.toString(); var tmp3:AnsiString = new AnsiString( post + "「Y! 」" ); post = tmp3.toString(); } trace( pre + sep + result + sep + post ); } else { trace( result ); } } exit( EXIT_SUCCESS ); } } }
update indentation
update indentation git-svn-id: 533dbd50173d42a8a7a6f488dbc0c05430609410@11 37abe446-e973-4b93-b0d7-31cb093a2758
ActionScript
mpl-2.0
Corsaair/as3hash