Alternative hq2x

by Cheshir forked from Alternative (diff: 190)
♥0 | Line 443 | Modified 2015-02-02 22:22:42 | MIT License
play

ActionScript3 source code

/**
 * Copyright Cheshir ( http://wonderfl.net/user/Cheshir )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/fafy
 */

// forked from Cheshir's Alternative
// forked from Cheshir's Observer and simple Console
package {
    import flash.system.ApplicationDomain;
    import flash.system.SecurityDomain;
    import flash.system.LoaderContext;
    import flash.events.IOErrorEvent;

    import flash.display.Loader;
    import flash.display.Bitmap;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.filters.GlowFilter;
    import flash.text.TextField;
    import flash.display.Sprite;

    public class FlashTest extends Sprite {
        public static var myConsole:Console;
        private var myObserver:Observer;
        private var galaxyHolder:Sprite;
        
        private var tileClipSheep:TileClip;
        
        public function FlashTest() {
            // write as3 code here..
            myConsole = new Console(stage);
            myObserver = new Observer(stage);
            galaxyHolder = new Sprite();
            
            this.graphics.beginFill(0x7c9b81);
            this.graphics.drawRect(0,0,600,600);
            addChild(galaxyHolder);
            myConsole.addComand('-cl',myObserver.removeAll, 'clear obserber');
            myConsole.help();
      //    Ooooo Yeaaa... it work... but was problem whis securityDomain
            var context:LoaderContext = new LoaderContext();
            context.checkPolicyFile = true;
            context.securityDomain = SecurityDomain.currentDomain;
            context.applicationDomain = ApplicationDomain.currentDomain;
            var url:URLRequest = new URLRequest('http://cheshir.zabix.net/footlocker/sheep_16_16.png'); //aloneDwarf3_16.png');
            var img:Loader = new Loader();
            img.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
            img.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            img.load(url, context);
        }
        private function ioErrorHandler(e:IOErrorEvent):void{
            myConsole.log('error '+e.text);
        }

        private function loaded(e:Event):void
        {
            var bitmap:Bitmap = e.target.content;
            bitmap.y = 240;
            galaxyHolder.addChild(bitmap);    // show full set of graphics
            myConsole.log('minimalist dwarf in result scaled by hq3x');
            tileClipSheep = new TileClip(16,16,bitmap.bitmapData, 1);
            tileClipSheep.x = tileClipSheep.y = 250;
            tileClipSheep.scaleX = tileClipSheep.scaleY = 3;
            tileClipSheep.delays = [25,15,20,20,20];
         //   tileClipSheep.demoMode = true;    // show all states one by one
            galaxyHolder.addChild(tileClipSheep);
            // Create new sheep - the adjusted animation
            var finalySheep:TileClip = new TileClip(16,16,bitmap.bitmapData, 3);
            finalySheep.x = 200;
            finalySheep.y = 200;
            finalySheep.delays = [25,15,20,20,20];    // maybe it should be ... random delay? I like random.
            // but if I make random delay I must to make them more
    //        finalySheep.scaleX =  finalySheep.scaleY = 3; 
           // finalySheep.randomDelay = true; // minimum delay -> maximum delay... I'm tired, but You can do it!
            galaxyHolder.addChild(finalySheep);           
            e.target.removeEventListener(Event.COMPLETE, loaded);
        }
    }
}
import flash.geom.Matrix;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Point;
import flash.events.Event;
import flash.utils.Dictionary;
import flash.ui.Keyboard;
import flash.events.FocusEvent;
import flash.text.TextFieldType;
import flash.events.TextEvent;
import flash.events.KeyboardEvent;
import flash.display.Stage;
import flash.text.TextField;
import flash.display.Sprite;
import flash.display.BitmapData;
Class {
    /**
     * @author nicoptere  http://gamedevblogs.ru/blog/actionscript/1080.html
     */
    class ScaleX {        
                static public function scale2x( bd:BitmapData ):BitmapData{

                        var dest:BitmapData = new BitmapData( bd.width*2, bd.height*2, true );
                        
                        var E:uint;
                        var E0:uint;
                        var E1:uint;
                        var E2:uint;
                        var E3:uint;                        
                        var B:uint;
                        var D:uint;
                        var F:uint;
                        var H:uint;                        
                        var i:int;
                        var j:int;
                        var i2:int;
                        var j2:int;                        
                        var w:int = bd.width;
                        var h:int = bd.height;
                        bd.lock();
                        dest.lock();
                        for ( i = 0; i < w; i+=1 )
                        {
                                for ( j = 0; j < h; j+=1 )
                                {                                        
                                        E = bd.getPixel32( i, j );                                        
                                        //on est sur un bord
                                        if( i==0 || j==0 || i == w-1 || j == h-1 )
                                        {                                                
                                                E0 = E;
                                                E1 = E;
                                                E2 = E;
                                                E3 = E;                                                
                                        }else{
                                                B = bd.getPixel32( i, j-1 );
                                                D = bd.getPixel32( i-1, j );
                                                F = bd.getPixel32( i+1, j );
                                                H = bd.getPixel32( i, j+1 );
                                                if (B != H && D != F ) 
                                                {
                                                        E0 = ( D == B ) ? D : E;
                                                        E1 = ( B == F ) ? F : E;
                                                        E2 = ( D == H ) ? D : E;
                                                        E3 = ( H == F ) ? F : E;
                                                }else{
                                                        E0 = E;
                                                        E1 = E;
                                                        E2 = E;
                                                        E3 = E;                                                       
                                                }
                                        }
                                        i2 = i*2;
                                        j2 = j*2;
                                        dest.setPixel32(   i2,   j2, E0 );
                                        dest.setPixel32( i2+1,   j2, E1 );
                                        dest.setPixel32(   i2, j2+1, E2 );
                                        dest.setPixel32( i2+1, j2+1, E3 );
                                }
                        }
                        bd.lock();
                        dest.unlock();
                        return dest;
                }
                static public function scale3x( bd:BitmapData ):BitmapData {
                        var dest:BitmapData = new BitmapData( bd.width*3, bd.height*3, true );                    
                        var E:uint;                      
                        var E0:uint;
                        var E1:uint;
                        var E2:uint;
                        var E3:uint;
                        var E4:uint;
                        var E5:uint;
                        var E6:uint;
                        var E7:uint;
                        var E8:uint;                  
                        var A:uint;
                        var B:uint;
                        var C:uint;
                        var D:uint;
                        var F:uint;
                        var G:uint;
                        var H:uint;
                        var I:uint;      
                        var i:int;
                        var j:int;
                        var i3:int;
                        var j3:int;
                        var w:int = bd.width;
                        var h:int = bd.height;
                        bd.lock();
                        dest.lock();
                        for ( i = 0; i < w; i+=1 )
                        {
                                for ( j = 0; j < h; j+=1 )
                                {     
                                        E = bd.getPixel32( i, j );                                   
                                        //on est sur un bord
                                        if( i==0 || j==0 || i == w-1 || j == h-1 )
                                        {                                           
                                                E0 = E;
                                                E1 = E;
                                                E2 = E;
                                                E3 = E;
                                                E4 = E;
                                                E5 = E;
                                                E6 = E;
                                                E7 = E;
                                                E8 = E;                                           
                                        }else{
                                                A = bd.getPixel32( i-1, j-1 );
                                                B = bd.getPixel32(   i, j-1 );
                                                C = bd.getPixel32(   i, j+1 );
                                                D = bd.getPixel32( i-1, j );
                                                F = bd.getPixel32( i+1, j );
                                                G = bd.getPixel32( i-1, j+1 );
                                                H = bd.getPixel32(   i, j+1 );
                                                I = bd.getPixel32( i+1, j+1 );                                           
                                                if ( B != H && D != F ) 
                                                {                                                  
                                                        E0 = ( D == B ) ? D : E;
                                                        E1 = ( ( D == B && E != C ) || ( B == F && E != A ) ) ? B : E;
                                                        E2 = ( B == F )? F : E;
                                                        E3 = ( ( D == B && E != G ) || ( D == H && E != A ) ) ? D : E;
                                                        E4 = E;
                                                        E5 = ( ( B == F && E != I ) || ( H == F && E != C ) ) ? F : E;
                                                        E6 = ( D == H ) ? D : E;
                                                        E7 = ( ( D == H && E != I ) || ( H == F && E != G ) ) ? H : E;
                                                        E8 = ( H == F ) ? F : E;                                                  
                                                } else {                                                
                                                        E0 = E;
                                                        E1 = E;
                                                        E2 = E;
                                                        E3 = E;
                                                        E4 = E;
                                                        E5 = E;
                                                        E6 = E;
                                                        E7 = E;
                                                        E8 = E;                                          
                                                }
                                        }
                                        i3 = i*3;
                                        j3 = j*3;                                  
                                        dest.setPixel32(   i3, j3, E0 );
                                        dest.setPixel32( i3+1, j3, E1 );
                                        dest.setPixel32( i3+2, j3, E2 );                                  
                                        dest.setPixel32(   i3, j3+1, E3 );
                                        dest.setPixel32( i3+1, j3+1, E4 );
                                        dest.setPixel32( i3+2, j3+1, E5 );                            
                                        dest.setPixel32(   i3, j3+2, E6 );
                                        dest.setPixel32( i3+1, j3+2, E7 );
                                        dest.setPixel32( i3+2, j3+2, E8 );                            
                                }
                        }
                        bd.unlock();
                        dest.unlock();
                        return dest;
                }
        }
}


Class{
    class TileClip extends Bitmap
    {
        public var demoMode:Boolean = false;
        public var randomDelay:Boolean = false;
        public var delays:Array = [];
        
        private var currentDelay:uint = 0;
        
        private var widthFrame:Number;
        private var heightFrame:Number;
        private var bitData:BitmapData;
        
        private var currFrame:uint = 0;
        private var totalFrame:uint = 0;
        private var currState:uint = 0;
        private var totalState:uint = 0;
        
        private var matrix:Matrix;
        
        private var hq3x:Boolean = false;
        
        // Create TileClip from bitmap Data
        public function TileClip(widthFrame:Number, heightFrame:Number, bitData:BitmapData, scale:Number = 1)
        {
            this.widthFrame = widthFrame;
            this.heightFrame = heightFrame;
            this.bitData = bitData;            // Safe data to draw
            matrix = new Matrix();        // Init Matrix transform
            totalFrame = uint(bitData.width / widthFrame);    // Calculate frames
            totalState = uint(bitData.height / heightFrame);    // Calculate states
            this.bitmapData = new BitmapData(widthFrame, heightFrame, true, 0);    // This is 'wiew window' of my clip
            super();
            currentFrame = 0;
            if(scale == 3){
                this.widthFrame *= 3;
                this.heightFrame *= 3;
                this.bitmapData = new BitmapData(widthFrame*3, heightFrame*3, true, 0);
                this.bitData = ScaleX.scale3x(bitData);
                play();
            } else {
                this.width = widthFrame * scale;
                this.height = heightFrame * scale;
                play();
            }
        }
        public function set currentFrame(num:uint):void
        {
            if (num < totalFrame)    // Elementary update as looped video "currentFrame+=1"
            {
                this.currFrame = num;
            } else {
                this.currFrame = 0;
                if(demoMode){currentState++;}
            }
            setCurrentFrame();
        }
        public function get currentFrame():uint
        {
            return this.currFrame;
        }
        public function set currentState(num:uint):void
        {
            if (num < totalState)
            {
                this.currState = num;
            } else {
                this.currState = 0;
            }
            setCurrentFrame();
        }
        public function get currentState():uint
        {
            return this.currState;
        }
        public function play():void
        {
            this.addEventListener(Event.ENTER_FRAME, update);
        }
        public function stop():void
        {
            this.removeEventListener(Event.ENTER_FRAME, update);
        }
        public function update(e:Event):void
        {
            //currentFrame++;    // Maybe i must add delays to each frame?
            /* How can I add delays to frames... Delay can be a good idea becouse my sheep slightly twitch.
                I like a meditative thing ... */
            if(currentDelay <= 0){
               currentFrame++;
               currentDelay = (randomDelay) ? uint(delays[currentFrame]*Math.random()) : uint(delays[currentFrame]);
            //   I like random and it make my animation not so repetitive...
            //    FlashTest.myConsole.clear();
            //    FlashTest.myConsole.log('next frame delay '+currentDelay);
            } else {
                currentDelay--;
            }
        }
        
        private function setCurrentFrame():void    // DRY    (don't repeat yourself)
        {
            matrix.tx = -this.currFrame * widthFrame;    // positioning data
            matrix.ty = -this.currState * heightFrame;
            this.bitmapData.fillRect(this.bitmapData.rect, 0);    // clear 'wiew window'
            this.bitmapData.draw(bitData, matrix);
        }
    }
}


Class{
    class Observer {
        private var subscribers:Array = [];
        public function Observer(stage:Stage) {
            stage.addEventListener(Event.ENTER_FRAME, updateAll);
        }
        public function updateAll(e:Event):void {
            for each(var sub:ISubscr in subscribers){
                sub.update();
            }
        }
        public function addSubscr(sub:ISubscr):void{
            subscribers.push(sub);
        }
        public function removeSubscr(sub:ISubscr):void{
            for(var i:int=0; i<subscribers.length; i++){
                if(subscribers[i] == sub){
                    subscribers.slice(i, 1);
                }
            }
        }
        public function removeAll():void{
            for(var i:int=0; i<subscribers.length; i++){
                subscribers[i].destroy();
                subscribers[i] = null;
            }
            subscribers = [];
        }
        public function get numSubscr():Number {
            return subscribers.length;
        }
    }
}

Class {
    class Particle extends Sprite implements ISubscr {
        private var dx:Number;
        private var dy:Number;
        private var rad:Number;
        private var center:Point;
        public function Particle(x:Number, y:Number, stage:Stage, parent:Sprite){
            this.x = x;
            this.y = y;
            center = new Point(stage.stageWidth/2, stage.stageHeight/2);
            this.graphics.beginFill(0xffffff);
            this.graphics.drawCircle(0,0,2*Math.random()*Math.random());
            parent.addChild(this);
        }
        public function update():void{
            dx = center.x - this.x;
            dy = center.y - this.y;
            rad = Math.atan2(dy,dx)+1.4835298642;    // Collapse to center 
            this.x += Math.cos(rad);
            this.y += Math.sin(rad);
        }
        public function destroy():void{
            parent.removeChild(this);
        }
    }
}


Class {
    interface ISubscr {
        function update():void;
        function destroy():void;
    }
}


Class
{
    class Console extends Sprite {
        private var consoleField:TextField = new TextField();
        
        private var descript:Array = ['help', 'clear console'];
        
        private var diction:Dictionary = new Dictionary();
        
        public function Console(stage:Stage) {
            consoleField.background = true;
            consoleField.type = TextFieldType.INPUT; 
            consoleField.backgroundColor = 0x333333;
            consoleField.alpha = .6;
            consoleField.textColor = 0xf2f9ff;
            consoleField.width = stage.stageWidth;
            consoleField.scaleX = consoleField.scaleY = 1.4;
            stage.addChild(consoleField);
            consoleField.addEventListener(FocusEvent.FOCUS_IN, clear);
            consoleField.addEventListener(KeyboardEvent.KEY_UP, upKey);
            diction['-h'] = {func: help, descript: 'help function trace'};
            diction['-c'] = {func: clear, descript: 'clear console zone'};
        }
        public function log(str:Object):void {
            if(!str is String){
                str.toString();
            }
            consoleField.appendText(str+'\n');
        }
        
        public function addComand(comand:String, toCall:Function, desc:String="no descript"):void{
            diction[comand] = {func: toCall, descript: desc};
        }

        private function upKey(e:KeyboardEvent):void{
            if(e.keyCode == Keyboard.ENTER){
                // parse
                var key:String = '';
                for(var i:int = 1; i<=4; i++){
                    key = consoleField.text.charAt(consoleField.text.length-i)+key;
                    if(diction[key] != null){
                        (diction[key].func as Function).call();
                        return;
                    }
                }
            }
        }
        
        public function clear(event:FocusEvent = null):void{
            consoleField.text = '';
        }
        
        public function help():void {
            log('This is help - default');
            for (var key:Object in diction) 
            { 
                log(key +"\t is "+ diction[key].descript); 
            } 

        }

    }

}