Does Flex 3 support threading? If so, are there any examples or links I could look at?
Somewhere, in Adobe, Flash Player does support multithreading... http://www.bytearray.org/?p=3007. It's just not publicly available yet.
Other than that, see Multithreading or green threading in actionscript? There are also a few articles on the internet about using Pixel Bender's multithreading for data processing.
ActionScript 3 is single-threaded.
What you can do is cut the work in slices small enough that the responsiveness is not too affected. For example:
private var _long_process_work_object:LongProcessWorkClass;
private var _long_process_timer:Timer;
private function startSomeLongAndIntensiveWork():void
{
_long_process_work_object = new LongProcessWorkClass();
_long_process_timer = new Timer(10);
_long_process_timer.addEventListener("timer", longProcessTimerHandler);
_long_process_timer.start();
}
private function longProcessTimerHandler(event:TimerEvent):void
{
_long_process_timer.stop();
// do the next slice of work:
// you'll want to calibrate how much work a slice contains to maximize
// performance while not affecting responsiveness excessively
_long_process_work_object.doSomeOfTheWork();
if (!_long_process_work_object.Done) {
// long process is not done, start timer again
_long_process_timer.start();
return;
}
// long process work is done, do whatever comes after
}
As stated by Alex here:
Actionscript is single-threaded, if you spend lots of time doing heavy
computation, the UI cannot be updated while you’re doing that
computation so your application appears stuck or effects don’t run
smoothly.
Similarly, there is no yielding or blocking in Actionscript either. If
the next line of code is supposed to run, you cannot prevent the next
line of code from running. That means that when you call Alert.show(),
the next line of code following that runs right away.
In many other runtimes, the Alert window has to be closed before the
next line of code continues. Threading may be a feature of
Actionscript some day, but until then, you have to live with the fact
that there is no such thing right now.
Flex 3 is based on ActionScript 3. ActionScript 3 does not provide support for multithreading ( you cannot write code aimed for multi-thread execution ).
A compiled flex application runs on the Flash Player platform. Adobe Flash Player 11.4 and up added support for multithreading.
Related
I'm completely new to actionscript (as3, not as2) and am having some problems with some simple functions and variables. Everything is in one .fla using the actions panel.
How do I get functions to execute? Nothing of my shape changes and there is no output.
*I am aware the first change won't be noticeable, I'll add a timer later on.
Here is the code*:
var starBlackWidth = 500;
var starBlackScaleX = 0.5;
function starStretch(){
starBlack.length = starBlackWidth;
trace("Stretched the star.");
}
function starReadjust() {
starBlack.scaleX = starBlackScaleX;
trace("Attempted at readjusting without using the width directly.");
}
As some of the commenters pointed out, yes you need to call the functions you created by adding these two lines of code.
starStretch();
starReadjust();
To expand upon what they said, yes these may be fundamental concepts of programming but if you're new to object oriented programming in as3 and even oop in general this link is extremely helpful at getting you going in as3, its 3 parts and it covers it pretty well!
http://www.untoldentertainment.com/blog/2009/08/25/tutorial-understanding-classes-in-as3-part-1/
I am making a game in Libgdx, in which I want to show and hide a texture for specific interval of time and repeat this process. can I use Timer class for this.
Please give me some example also.
I'm not sure what your trying to do here. You could just have a flag in your rendering loop
Texture texture;
long lastFlip = 0;
long flipTime = 1000;
boolean display = false;
//..In your rendering loop
if(lastFlip+flipTime > System.currentTimeMillis()){
display = !display;
lastFlip = System.currentTimeMillis();
}
if(display){
spriteBatch.draw(texture,0,0);
}
If you want to use the inbuilt actions system in scene2d have a at the following tutorial. Tutorial. The blog is very good and gives you a good idea of how to use a lot of scene2d features. It might be a little bit out of data beacuse of the changes to scene2d but it will give you the idea you need.
I am sure you got the solution now but instead of using System specific time you should use the Gdx graphics delta time which you already have in the render method. Then compare it with the amount of time for which you want to show the textures.
You should definitely use libGDX wrapper function to read time to avoid eventual incompatibility on different platforms. But code it self can be really simple:
if (TimeUtils.millis()%(SHOW_TIME+HIDE_TIME) < SHOW_TIME){
// render it
}
Where SHOW_TIME is number of milliseconds you want your texture displayed and HIDE_TIME is number of milliseconds you want it hidden. No need for extra variables and making it more complicated than this.
I'm testing various performance tweaks for a large website, and I need to quantify how long it takes from initial load to the document elements appearing (i.e. time to paint). Is there a good way to do this using Chrome's dev profiler?
To clarify, I need to know the total time from load to painted page.
You could do one of two things:
1) Use Dan Mayor's method. You can simply use new Date().getTime before and after the painting script and subtract them in order to find out how long the script took to complete. However, this may be subject to lag if the entire code lags. It's not necessarily the most accurate way, but it gets the job done. (However, you could create a separate function that calculates the time independently of the other script. See below:)
function findTime(done){
if (done==false){var time1 = new Date.getTime();}
if (done==true) {var time2 = new Date.getTime(); window.alert(time2-time1);}
}
Where done is a boolean parameter you would add after the script is complete.
2) Chrome has a nice developer's console with a timeline capability. Basically, open your Chrome browser and hit command+Shift+C (control+shift+C for windows), and click the timeline button. Then, click the little dot at the bottom of the console, and it should turn red. Refresh the page, and the timeline will start collecting all kinds of timing data for your scripts. Painting events are shown in green. Unfortunately, this is a third party solution.
In the end, there is no way to directly measure this time, due to different amounts of lag, different internet connectivity speeds, processor speeds, etc. However, these 2 methods come pretty close to the actual answer. You may want to test the scripts on different browsers and computers.
For starters, I would definitely familiarize myself with the "Net panel" in Firebug:
http://getfirebug.com/network
I understand that Chrome has a similar tool: Hit "F12" (or use the "wrench" icon):
https://developers.google.com/chrome-developer-tools/
You might want to look into the "DOMContentLoaded" event, this is what jQuery binds to to provide it's .ready() method. The basic idea is you will want to use Date.getTime() to record millisecond values, the first should be the last line of your document (for html downloaded marker). The second you want to call after onload, DOMContentLoaded, loaded and other DOM ready state events.
Quick example (end of your html output):
<script type="text/javascript">
window.downloadComplete = new Date().getTime();
document.onload = function() { window.domParseComplete = new Date().getTime(); }
window.onload = function { window.renderComplete = new Date().getTime(); }
window.paintTime = window.renderComplete - window.downloadComplete;
</script>
In this example window.downloadComplete will be the millisecond when the DOM has finished downloading, window.domParseComplete is the millisecond when the DOM has been parsed and window.renderComplete is the millisecond when the window reports it's rendering is complete. The window.paintTime is just the number of milliseconds calculated from these millisecond time's.
After many years of using Flash 8, I'm moving to CS3 at work. I know I'll have to learn AS 3.0 so, does anyone have any good references or summaries of the major/most noticeable changes? Also, are there any tips/tricks for the flash environment? After spending a few minutes in CS3, I noticed that you can't directly attach actionscript to a button, which is new to me. Any other such pitfalls to watch over?
I made the total switch just about 3 months ago, here are some things that helped me ramp up rather quickly:
1) Do everything in Class files
A lot of AS3 tutorials out there deal with just code pasted on the timeline (which I can't stand because now you have to hunt for what import you need), but is fine for quick tiny stuff. In the long run it's way better work primarily in Class files. Learning how Classes work opened a huge door for me, it was the same feeling/experience I had when I first discovered Functions in AS2 :)
2) Keep graphics in library and off the workspace
Example, you have a jpg, gif, png file you just imported into your library. Made a movieClip and gave it a class name(MyButton). Now the code below will place the graphic into the workspace for you:
var myButton:MovieClip = new MyButton();
myButton.x = 6;
myButton.y = 22;
myButton.buttonMode = true;
addChild(myButton);
3) Get use to the new button code in AS3
It's something all of us new converts had to deal with painfully, but now it's a piece of cake :)
myButton.addEventListener(MouseEvent.MOUSE_UP, clickThis);
function clickThis(event:MouseEvent):void
{
navigateToURL(new URLRequest("form.html"), "_self");
//navigateToURL(request, '_self');
}
4) Make sure you remove Event Listeners after use
It took me a bit to wrap my around this one... remove em why? Oh they are still running in the background and when I listen again I'll get all kinds of mutated errors.
private function volDown(e:MouseEvent):void
{
masker.width = volControl.mouseX;
userVolume = (masker.width / 100) * 1;
volControl.addEventListener(MouseEvent.MOUSE_MOVE, volMove);
}
private function volUp(e:MouseEvent):void
{
lastVolPoint = masker.width;
setVolume(userVolume);
e.updateAfterEvent();
volControl.removeEventListener(MouseEvent.MOUSE_MOVE, volMove);
}
5) Don't forget to pass Events
I'm not a programmer by trade and this has caused so much grief, I'm glad I'm done with this birthing pain:
myButton.addEventListener(MouseEvent.MOUSE_UP, clickThis);
Since the clickThis function is launched via an Event, you have to pass: event:MouseEvent into it like so:
function clickThis(event:MouseEvent):void
Because the code below will throw the dreaded AS3 "Access of undefined property" error that new AS3 guys will always run into.
function clickThis():void
6) Read and post questions on StackOverflow... a lot!
btw I'm still a noob and originally a designer then AS2 dev, I still don't know why we put :void behind a function name.. if we have similar coding backgrounds I hope all that helps :)
I suggest you to look at the ActionScript language migration page on the Adobe devnet. It offers quite a lot articles about the key changes with ActionScript 3.
To answer your problem with the actions on a button, this no longer works (and was already with ActionScript 2 not the best way to do it). AS3 requires the code to be centralized on the timeline. So for giving a button some action, you'll need to give it an instance name and add an event listener for the CLICK event, like this:
function doSomething ( event:MouseEvent ):void
{
trace( "test" );
}
myButton.addEventListener( MouseEvent.CLICK, doSomething );
Get an Actionscript 3 IDE. Such as Flash Builder, FlashDevlop, or FDT. This will force you to learn really fast.
Recently I took on a rather daunting task of creating an interactive music video for the popular show Ghost Whisperer. I was brought in late in the project and was confronted with a giant authoring file (some 5000+ frames long). The previous programmer (who did everything in AS2) had essentially embedded a two and half minute FLV on the time main time line and at certain frame points would add in clips for interactivity with basic mouse click functionality that would trigger those clips to play other clips with some flash elements and some video elements.
(the final version I created can be viewed here http://www.gwghostmagic.com);
Being a neat freak I decided to rebuild the whole thing in AS3, ditch the time line altogether and rather load in my elements at run time so that instead of 5000 frames I had one frame and to trigger the actions added an Event.ENTER_FRAME event listener to trigger the interactivity when the loaded .swf would reach certain frames. From a programmers stand point it made everything much clearer and easier to manipulate certain actions. The problem was, the thing ran like crap.
The 5000+ frame version loaded faster and ran smoother than my AS3 version. Which brings me to the question, when is it better to embed and run off the time line than run off of an event listener? Is flash better suited for time line functionality?
Initially I decided to build and run off of a streaming .flv but syncing up the actions to the .flv was impossible because the .flv was running at 23.975 fps whereas my flash movie was running at 24 fps. Alas I was forced to compile an .swf with the flv embedded. That .swf was then loaded into my main .swf that contained all the functions and extra clips that would play according to the loaded .swf's frame position.
One thing I've noticed is that the Event.ENTER_FRAME seems to slow the whole damn application down because at every frame it has to run down a list of if statements 200 lines of code long. Wherein if the whole thing was embedded I might only need to insert a keyframe where the interactive clip would be instantiated and then would know immediately what to do, rather than cycle through if else statements.
Did I screw up trying to make things nice and tidy? Is it better to let flash be flash? Should I seek out another career? Any input is greatly appreciated.
I think that having the event trigger every frame as opposed to only triggering actions occasionally accounts for the performance difference. Hopefully you could minimize the amount of code and conditionals that was run through in the event handler.
Here's an idea I haven't tested:
var dispatch:Object = {
f1: function () {textBubble.text = "This is Rush Hour 2";},
f61: function () {textBubble.text = "";},
f111: function () {textBubble.text = "This scene has 50 takes; "
+"Jackie Chan said \"Square Madison\" each time.";},
f171: function () {textBubble.text = "";}
};
addEventListener(Event.ENTER_FRAME, function (e:event) {
if (dispatch["f"+e.target.currentFrame] is Function) {
dispatch["f"+e.target.currentFrame]();
}
});
This uses the Object as an Associative Array as described in the live docs.
You are probably correct - running 200+ lines of code on every frame is slowing you down. Instead of a huge list of statements, split your frame functions up and only call the ones you need - this is an expansion on dlamblin's idea - this way you are running the smallest amount of code necessary for each frame:
function doThisOnFrame20():void
{
//do stuff...
}
function doThisOnFrame50():void
{
//do stuff...
}
var frameFunctions:Array = new Array();
frameFunctions[20] = doThisOnFrame20;
frameFunctions[50] = doThisOnFrame50;
function enterFrameListener(event:Event):void
{
if(frameFunctions[swfWithFLV.currentFrame] is Function)
{
frameFunctions[swfWithFLV.currentFrame]();
}
}
addEventListener(Event.ENTER_FRAME,enterFrameListener);