Stroep

Just a collection of random works – Mark Knol

Archive by Author

Generative art: mixup (0)

December 11th, 2011, under Generative art.

Tagged with .

JSFL dialog (2)

December 1st, 2011, under Code snippets, JSFL.

JSFL DialogWhile playing with JSFL and trying to create a faster interface for my name it right.jsfl I stumbled across a very interesting function inside JSFL. There is a powerful function called fl.getDocumentDOM().xmlPanel which shows dialogs using .xml-files. Actually you could use XUL (XML User Interface Language), which kinda looks like a mix of HTML and Flex. If you need a GUI for your JSFL script, you can open a nice custom dialog using XUL.

Why create tools inside a tool?

Yes, the Flash is a very nice IDE. But with JSFL you can extend it. You can build your own snippets and tools. It could be very helpful to automate some boring things. I think it is very powerful to have the ability to extend your environment for your everyday tasks.

Show a dialog with JSFL

Create a dialog file
This is an example of XUL. Save it as test-dialog.xml in your local commands folder.

<dialog title="JSFL dialog" buttons="accept, cancel">
  <vbox>
    <label control="myTextfield" value="Enter some text"/>  
    <textbox id="myTextfield"/>
    <label control="myColor" value="Choose a nice color"/>  
    <radiogroup id="myColor">  
      <radio label="Orange"/>  
      <radio selected="true" label="Violet"/>  
      <radio label="Yellow"/>  
    </radiogroup>  
  </vbox>
</dialog>
 

Open the dialog with JSFL
Save it as test-dialog.jsfl in the same folder as the .xml file.

// xmlPanel returns an Object with values of the dialog.
var xmlPanelOutput = fl.getDocumentDOM().xmlPanel(fl.configURI + "/Commands/test-dialog.xml");

if (xmlPanelOutput.dismiss == "accept") // user confirms dialog
{
  fl.trace("myTextfield: " + xmlPanelOutput.myTextfield);
  fl.trace("myColor: " + xmlPanelOutput.myColor);
}
else // user canceled dialog
{
 
}
 

Run it by clicking ‘Commands’ > ‘test-dialog’ in Flash; our custom dialog will show up. Nice! :D

Give me more; I want dynamic dialogs

If you check out the documentation of fl.getDocumentDOM().xmlPanel, you see you only can pass a uri to a xml file, but there is no way to pass a XML or Object to it. Adobe if you read this post; that would be nice. But I found a hack to create a dialog from JSFL by dynamically create a XML and save it as temporary file and open that one as xmlDialog. The file will be removed after showing the dialog.

function showXMLPanel(xmlString)
{
  var tempUrl = fl.configURI + "/Commands/temp-dialog-" + parseInt(777 * 777) + ".xml"
  FLfile.write(tempUrl, xmlString);
  var xmlPanelOutput = fl.getDocumentDOM().xmlPanel(tempUrl);
  FLfile.remove(tempUrl);
  return xmlPanelOutput;
}

This function displays a dialog from a (xml) string and returns the values like you would expect from the xmlPanel-function. You could use a XML object for this too, but I think it’s easier to hack some variables into it or make templates with strings.

// create an XUL with JSFL
var dialogXML = ”;
dialogXML += ‘<dialog title="JSFL dynamic dialog" buttons="accept, cancel">’;
dialogXML +=   ‘<hbox>’;
dialogXML +=     ‘<label value="Enter 2x something"/>’;
dialogXML +=     ‘<textbox id="myText1" value=""/>’;
dialogXML +=     ‘<textbox id="myText2" value=""/>’;
dialogXML +=   ‘</hbox>’;
dialogXML += ‘</dialog>’;

var xmlPanelOutput = showXMLPanel(dialogXML);
if (xmlPanelOutput.dismiss == "accept") // user confirms dialog
{
  fl.trace("myText1: " + xmlPanelOutput.myText1);
  fl.trace("myText2: " + xmlPanelOutput.myText2);
}
else // user canceled dialog
{
 
}
 

Since you are dealing with strings, you can manipulate and add extra elements. This allows you to pass data from JSFL to your dialog.

So, can you make panels too?

I really hate custom panels, because I never get my workspace right for two screens (moving/closing/opening panels the whole day), so there is no room for other panels. I start loving JSFL-scripts because you can assign a shortcut-key to it, which runs the tool, without having a panel in my workspace.

Conclusion

I like to create handy snippets and will share more in the future. But if you thought (just like me) this is some kind of a new feature: It’s not. :) Let me know if you have some nice references or JSFL scripts to share.

Learn more:

Tagged with , , .

Recently I found an interesting question on FlashFocus.nl, about creating light and shadows in a 2D environment. I started experimenting with this to see how far I could take it. I love to share the results and some insides about this fun project.

How to get started

The initial code that the topic starter used a loop through all objects, and used hitTestPoint-function to detect if the light hits a wall. Therefore he used a loop with 360 steps, used for all directions. In the innerloop it tries if it hits the wall, otherwise goes away from the light (using the direction of the outerloop), tries if it hits the wall. That loop goes on till it does hit a wall. It is a bit of trial and error, but I think it is very clever. At the end of each loop a lineTo is used to draw the light, so in the end it will be a shape with 360 vector points.

Speed of light

Now, that screams for optimization and speed. It’s a fun project to mix some things you have seen and want to try out for a long time. The first thing that I tried to make it faster, draw all objects into an BitmapData, and use the getPixel function instead of hitTestPoint, which is notable faster if you don’t move objects. I used that BitmapData object only too check if the light hits the objects; no one actually sees it. To use hitTestPoint, you must loop through all objects and detect if they hit. With a lot of objects, it would be slower. With BitmapData, you don’t need that loop, and you are free to use unlimited objects with even custom shapes. Less looping == faster, unlimited objects == awesome :)

More realism

I also wanted to make it look more realistic. Having light only is not close enough to realism. It needs shadows. I created an inverted shape of the light-shape and filled it with black (a). This creates a nice shadow, however has very hard bounds, which is ugly. So then I took the shape again and drawed with a nice transparent to black gradient (b). Those 2 layers have the BlendMode ALPHA. The holder of those has a solid shape fill (as big as the stage) with BlendMode LAYER. This creates a nice ‘hole’ which I think works very well as shadow if you make it half-transparent. Oh, the colored light-layer (c) is a gradient too, with the same shape as b, only with BlendMode ADD.

Re-using shape data

Another optimization I used was to use graphics data API. In this case I have 1 shape which could be reused 3 times. So before even drawing, I collect all points and commands in an Vector. When I have all data collected, it draws the light-layer and shadow-layer at first, then it pushes some extra points to the Array to make the outer shadow-layer. So with 1 Array of (manipulated) data I could draw multiple shapes. That’s a good case of using the graphics data, I guess.

Optimized trig functions

I also used the TrigLUT-class (Trigonometry LookUp Table) from jacksondunstan.com, since the loop heavily uses Math.sin and Math.cos. I could use the valNormalizedPositive() function from that class in this case. It’s very fast and for me it was fun to use that class. :D

But it is still too slow..

The most intense about this thing isn’t the calculation, but the rendering itself. The whole ‘canvas’ needs to be updated and redrawed every frame with lots of layers and blendmodes, which is very intense for the CPU. I don’t know if this would be possible with Stage3D, but that would be the last step to render really fast. And when that is possible, I’ll guess I could move the object real-time too, which makes it very interesting for games.

Check out the experiment:
» Lights and shadows

Let me know what you think about it and how does it perform on your computer?

Tagged with , , , .

I have created a JSFL script for those who are using the Flash IDE a lot. Renaming movieclips over a timeline with motion-tweens cost a lot of time. Assigning and replacing classes to a certain movieclip could also be done faster, and mostly name of the symbol relates to the names on stage. I have created a 3-step wizard called ‘name it right!’, to speed up your everyday workflow. This command helps you to update a layer name, base class, symbol name and instances on the timeline very fast.

Download/Save the .jsfl file directly:
» Name it right.jsfl
(v1.1)

To indicate what happens when you run the command/script:

First select an instance on stage. Go to ‘Commands’ > ‘Name it right!’.
You’ll get these three questions.

  • 1/3 Rename library symbol name?
    • Enter the new symbol name in the prompt.
    • When you have selected ‘Export voor ActionScript’, it will automatically fill the ‘Class’ according this convention: ‘fileName.SymbolName’.
  • 2/3 The library symbol already has a base class, change it?
    • Enter the new base class in the prompt.
    • If there is no base class defined, it will turn on ‘Export voor ActionScript’ and fill ‘Class’ as mentioned above.
  • 3/3 Rename instance name across timeline?
    • This renames a movieclip instance on the complete timeline. It does not matter if there is a motion-tween on it. You only need to insure there is only one clip on that layer. Otherwise it will give you a note.
    • It will give you a name suggestion based on you Symbol name, like ‘mcSymbolname’
  • Cancel means: do nothing.

    Install / use the JSFL script

    To get it inside the Flash IDE under ‘Commands’, copy the .jsfl file to:

    Windows 7
    C:\Users\{username}\AppData\Local\Adobe\Flash CS5 or CS5.5\en_US\Configuration\Commands

    Windows Vista:
    C:\Users\{username}\Local Settings\Application Data\Adobe\Flash CS5 or CS5.5\en_US\Configuration\Commands

    Windows XP:
    C:\Documents and Settings\{username}\Local Settings\Application Data\Adobe\Flash CS5 or CS5.5\en_US\Configuration\Commands

    Mac OS X:
    C:/Users/{username}/Library/Application Support/Adobe/Flash CS5 or CS5.5/en_US/Configuration/Commands

    Run it by clicking the ‘Name it right!’ under ‘Commands’.

    You could assign a key-combination under ‘Edit’ > ‘Keyboard shortcuts’ and then expand the ‘commands’-folder. I used CTRL-ALT-SHIFT-W for it.

    Hope you could use it, post your feedback/suggestions below.

    Tagged with , , .

    Design pattern – Behaviors (7)

    October 16th, 2011, under actionscript.

    Design pattern - BehaviorsI recently started working at MediaMonks where they are using this interesting pattern of coding; behaviors as a class. I started playing with ‘behaviors’ myself to see how this could work for me. If you use this pattern once, you’ll wonder why you did not use it ever before ;) This post will lead you through some examples and shows some benefits of using it. This post is written with focus on actionscript 3 developers, who can read code and knows already something about object oriented programming. The goal is to learn more and become a better developer.

    What is a behavior?

    Well I guess everybody knows what it means, but in terms of code I would say that a behavior-class is some kind of a simple controller with a target. It does one thing, it controls the target with a specific feature/goal. The idea is to add functionality by assigning a behavior to an object (composition), instead of extending it to get the functionality (inheritance). That sound complicated, so why not check out what it practically means?

    Difference between inheritance and composition

    Let’s say you want to program an object that follows your mouse. How would you create it? I would create a class named MouseFollowingSprite which has all functions to do that. Then I would extend or create an instance of that MouseFollowingSprite-class and BANG I’m done :)

    Typical example of inheritance

    class MouseFollowingSprite extends Sprite

    Okay, lets write down that killer class:

    package nl.stroep.display
    {
        import flash.display.Sprite;
        import flash.events.Event;
       
        /**
         * @author Mark Knol
         */

        public class MouseFollowingSprite extends Sprite
        {
            private var _ease:Number;
           
            public function MouseFollowingSprite()
            {
                init();
            }
           
            private function init():void
            {
                this.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
            }
           
            private function handleEnterFrame(e:Event):void
            {
                update();
            }
           
            private function update():void
            {
                this.x += (this.mouseXthis.x) / _ease;
                this.y += (this.mouseYthis.y) / _ease;
            }
        }
    }
     

    (You see that? It’s nicely done with some eased motion :D )

    I have never seen a problem with extending, but I had troubles with finding a good way to add other kind of functions to this type of classes. In terms of OOP, is a rule to write classes with a single responsibility, and we already passed that one. But imaging you want your mouse following sprite also to scale when you scroll with your mouse wheel. Well that would be easy: Just create a class named ScrollWheelScalingSprite, which extends MouseFollowingSprite. Now it has both functionality, when you would create an instance of it.

    Let’s create our ScrollWheelScalingSprite, it would like this:

    package nl.stroep.display
    {
        import flash.display.DisplayObject;
        import flash.events.Event;
        import flash.events.MouseEvent;
       
        /**
         * …
         * @author Mark Knol
         */

        public class ScrollwheelScaleSprite extends MouseFollowingSprite
        {
            private var _ease:Number;
            private var _targetScale:Number;
            private var _hasListener:Boolean;
            private var _deltaRatio:Number = 0.1;
            private var _minimum:Number = NaN;
            private var _maximum:Number = NaN;
           
            public function ScrollwheelScaleSprite()
            {
                _targetScale = this.scaleX;
               
                init();
            }

            private function init():void
            {
                stage.addEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
                addEnterFrameListener();
            }
           
            private function handleMouseWheel(e:MouseEvent):void
            {
                _targetScale += e.delta * _deltaRatio;
               
                if (!isNaN(_minimum) && _targetScale < _minimum) _targetScale = _minimum;
                else if (!isNaN(_maximum) &&_targetScale > _maximum) _targetScale = _maximum;
               
                addEnterFrameListener();
            }
           
            private function addEnterFrameListener():void
            {
                if (!_hasListener)
                {
                    this.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
                    _hasListener = true;
                }
            }
           
            private function removeEnterFrameListener():void
            {
                this.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
                _hasListener = false;
            }
           
            private function handleEnterFrame(e:Event):void
            {
                update();
            }
           
            private function update():void
            {
                this.scaleX += (_targetScale – this.scaleX ) / _ease;
                this.scaleY = this.scaleX;
               
                if (Math.abs(this.scaleX – _targetScale) < .01)
                {
                    removeEnterFrameListener();
                }
            }
        }
    }
     

    Let’s go some deeper. What if you want a ScrollwheelScaleSprite which should not follow our mouse? That would be a problem, because it already has that functionality. However you could hack around around by adding some protected booleans, to enable the actual functions of the class. Name them like _mouseFollowingEnabled. When your class extend some other classes, you’ll probably need a _scrollWheelScalingEnabled too. In the constructor of the new class you just turn on/off the booleans and your done. But then again, if you want to use this to Bitmap, you have a problem, you cannot extend a Sprite and a Bitmap at the same time.

    I mean, this is how we code, right? All classes have one responsibility, but could this example been done better? While writing, this post reminds me in a way to this older post of Keith Peters; you should read it. It also has a interesting discussion.

    Create behaviors

    As already stated, a behavior class is a controller. It deals with an object (we call it target) to add the actual behavior. Now I don’t think extending is bad, but I think we should use it with care.

    Let’s create an abstract behavior class, which can be extended. (This is not needed, but very helpful for accessing the target and prevent duplicate code)

    package nl.stroep.behaviors
    {
        import flash.display.DisplayObject;
       
        /**
         * @author Mark Knol
         */

        public class AbstractBehavior
        {
            protected var _target: DisplayObject;
           
            public function AbstractBehavior(target: DisplayObject)
            {
                this._target = target;
            }
        }
    }
     

    I think this does not require lots of explanation. We have a class, it saves a target
    that is passed from the constructor. We can do lot’s of stuff inside a behavior from this point.

    Now, let’s convert our MouseFollowingSprite to a MouseFollowingBehavior, which should extends the AbstractBehavior. Most drastic change is to convert ‘this‘, to ‘_target‘ and change the constructor to make it an actual behavior:

    package nl.stroep.behaviors
    {
        import flash.display.DisplayObject;
        import flash.events.Event;
       
        /**
         * @author Mark Knol
         */

        public class MouseFollowBehavior extends AbstractBehavior
        {
            private var _ease:Number;
           
            public function MouseFollowBehavior(target: DisplayObject, ease:Number = 5)
            {
                super(target);
               
                _ease = ease;
               
                init();
            }
           
            private function init():void
            {
                _target.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
            }
           
            private function handleEnterFrame(e:Event):void
            {
                update();
            }
           
            private function update():void
            {
                _target.x += (_target.mouseX_target.x) / _ease;
                _target.y += (_target.mouseY_target.y) / _ease;
            }
        }
    }
     

    This is not magic, but it is very powerful. We can assign this behavior to a Sprite, but also to a Bitmap or Video etc. This would not that easy / possible with inheritance only. The class works standalone and we don’t need booleans to enable or disable the behavior.

    Ok, let’s also create the scroll wheel scale behavior:

    package nl.stroep.art.behaviors
    {
        import flash.display.DisplayObject;
        import flash.events.Event;
        import flash.events.MouseEvent;
       
        /**
         * …
         * @author Mark Knol
         */

        public class ScrollwheelScaleBehavior extends AbstractBehavior
        {
            private var _ease:Number;
            private var _targetScale:Number;
            private var _hasListener:Boolean;
            private var _deltaRatio:Number;
            private var _minimum:Number;
            private var _maximum:Number;
           
            public function ScrollwheelScaleBehavior(target: DisplayObject, ease:Number = 5, deltaRatio:Number = 0.1, minimum:Number = NaN, maximum:Number = NaN)
            {
                super(target);
               
                _ease = ease;
                _deltaRatio = deltaRatio;
                _minimum = minimum;
                _maximum = maximum;
                _targetScale = target.scaleX;
               
                init();
            }
           
            private function init():void
            {
                _target.stage.addEventListener(MouseEvent.MOUSE_WHEEL, handleMouseWheel);
                addEnterFrameListener();
            }
           
            private function handleMouseWheel(e:MouseEvent):void
            {
                _targetScale += e.delta * _deltaRatio;
               
                if (!isNaN(_minimum) && _targetScale < _minimum) _targetScale = _minimum;
                else if (!isNaN(_maximum) &&_targetScale > _maximum) _targetScale = _maximum;
               
                addEnterFrameListener();
            }
           
            private function addEnterFrameListener():void
            {
                if (!_hasListener)
                {
                    _target.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
                    _hasListener = true;
                }
            }
           
            private function removeEnterFrameListener():void
            {
                _target.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
                _hasListener = false;
            }
           
            private function handleEnterFrame(e:Event):void
            {
                update();
            }
           
            private function update():void
            {
                _target.scaleX += (_targetScale – _target.scaleX ) / _ease;
                _target.scaleY = _target.scaleX;
               
                if (Math.abs(_target.scaleX – _targetScale) < .01)
                {
                    removeEnterFrameListener();
                }
            }
        }
    }
     

    Now we can assign a behavior very easy:
    Example of applying the behaviors

    var sprite:Sprite = new Sprite();
    new MouseFollowBehavior(sprite);
    new ScrollwheelScaleBehavior(sprite);

    You are now free to add the behaviors you’ll need, and leave the one you don’t need. It’s like creating little plugins. Fun eh? It’s nice to add parameters to the constructor, to make it less static. The other fun part is that if you build a behavior right, you could copy/paste it to another project or in you library, because it has no dependencies to classes you don’t want or need. Of course, this is not something new, you could have seen this in temple-lib but also the Hype-framework too, and maybe lots of other framework probably use this pattern in a way.

    Now we know the difference:
    Inheritence: “I want a Sprite that follows my mouse”
    Behaviors: “I want something that makes a Sprite follow my mouse”

    Killing the behaviors

    The code examples in this post does not have any function to remove it, but if you want to remove a behavior, it would be wise to assign the behavior to a variable, and create a destruct() or destroy() function inside the behaviors to remove listeners and references to the target etc, and then set it to null.

    // Anywhere in your code:
    var myBehavior:MouseFollowBehavior = new MouseFollowBehavior(myMc);

    // Somewhere in your code where you want to remove the behavior:
    myBehavior.destroy(); // a public function which removes all listeners, references etc
    myBehavior = null;
     

    Conclusion

    Behaviors are a cool and give clean reusable classes and I think we should use it more. It’s probably not new for you and the inheritence-example is not very realistic, but I hope it’s refreshing to look at it again. If you want to learn more design patterns, I also recommend this site.

    If you think back on how you have coded in the past, what would you change now you know this pattern? BTW I want to learn more too, so don’t hesitate to leave some nice feedback below.

    Oh, maybe you haven’t heard, but something unexpected will happen if you hold CTRL and click on the facebook like-button (found that in a YouTube comment; very lame).

    Tagged with , , .

    Finally I have created and finalized my Actionscript 3 Event Generator, which was buggy but now it is very nice :) As stated on twitter, if you are a flashdeveloper and use custom events in actionscript 3, you should use this tool because it helps you create custom event classes very fast.

    Features:
    - Fast variable adding
    - Event type generation (static constants). Just use lower camelCased variables and they will be formatted nicely.
    - Meta data for a event dispatcher class.
    - Automatic clone() function
    - Automatic toString() function

    URL
    » http://projects.stroep.nl/EventGenerator/

    Don’t forget to first fill your name at @author on the right. The package and @author will be saved for next time.

    I have also created a dropdown-menu on the top-right to switch to other tools. Happy coding!

    Tagged with , , , .

    I created a tool to created ‘grouped’ value objects nicely and very fast. It is using private classes. I found it useful enough to share it with you, so maybe if you are in need of such a tool, you are free to use it.

    » Check it out: http://projects.stroep.nl/enumGenerator/

    Oh, if you want to create normal value objects, use the value object generation tool. For creating custom events classes, I have an custom event generator.

    Tagged with , , , .