replace an swf instantaneously - actionscript-3

Just looking for ideas on something (tried to make this description shorter but didn't succeed):
I want to be able to update an swf instantaneously - by that I mean don't refresh it until the entire new version of it is completely ready and then immediately replace the existing contents in the browser window (as opposed to the existing page being removed, followed by a gray screen, followed by incremental reconstitution of the page).
Actually i have a method to accomplish this now: Everything on the swf is on a canvas, so I create a new canvas behind the scenes, repopulate it with all the new controls, and then when everything's ready, display this new canvas and destroy the old one.
But the strange thing is, it actually takes twice as long to build the new page this way than if I had just put the new version of it in a seperate swf on its own web page and displayed the new web page. (So 2 seconds vs. 1 second). But if the new version is on its own web page, then you get the existing page disappearing, being replaced by a gray screen, followed by an incremental build of the new page(an incremental build only taking a second - but still not the effect I'm going for.)
Basically what I'm looking for is to create a new SWFLoader containing the new version and then say, "when a certain signal is sent by the application in the new SWFLoader, replace the entire existing swf application in the browser window with the content of this new SWFLoader."
Or, if there were even a way that I don't know of currently to do all this with just html (i.e. replace an entire html page in the browser window instantaneously only when the new page is completely ready) then that would be great also.

You seem to be suggesting the use of a shell/preloader, e.g. a minimal SWF handling loading /unloading/transitioning of external SWFs. I think you pretty much explained it your self actually :)
Things to keep in mind (from the top of my mind):
Make sure you have full control over starting/stopping processes and free up memory before unloading the old SWF. A good practice in this case is to share a common interface for your document classes to be accessed consistently by the shell. (e.g. enable / disable / scale)
Be careful using the same, or identically named classes since the ones loaded first won't get overridden.

I came up with a scheme where my app clones itself in a new SWFLoader in the same app. This was noticably faster (i.e. just recreating the entire reconfigured app in a new SWFLoader rather than reconfiguring the already loaded app.) Probably has to do with the fact that FP optimizes the load process for new apps.
Basically the very first time my app runs, it just creates one child SWFLoader that will hold the actual app. Then if that app needs to be reconfigured, a new child SWFLoader is created and added as a child at the top level with 'this.addChildAt(0)'. (So its temporarily obscured by the old SWFLoader.) When the new SWFLoader is finished loading, it removes the previous SWFLoader by caling 'this.parent.parent.parent.parent.removeChildAt(1)'. Removing the old SWFLoader makes the new one visible immediately. I have to string those parents together to acess the top level parent of both SWFLoaders from the actual application runnning in the new SWFLoader. (The application in an SWFLoader is four parents removed from the parent of the SWFLoader). I guess no one understands what I'm talking about but at least I solved my problem.

Related

How to implement Caching while loading SWCs dynamically

I'm loading dynamic loading of all my SWCs in my master SWF, in order to load master swf faster, however now I need to cache all my swcs in local machine to speed up things.
private function loadAssets():void
{
swcObj=new Object();
swcObj.swcPath='assets/swc/1.swc';
swcObj.className="Part_0_1";
swcs.push(swcObj);
swcObj=new Object();
swcObj.swcPath='assets/swc/2.swc';
swcObj.className="0_2";
swcs.push(swcObj);
swcObj=new Object();
swcObj.swcPath='assets/swc/3.swc';
swcObj.className="0_3";
swcs.push(swcObj);
}
Then I'm using this array to use all the classes in my project, but I have no idea how to cache these swcs for faster use, if anyone have idea, please share.
In fact, the browser does this pre-caching for you, you don't need to produce extra efforts. So, just load them normally and don't worry about caching. You can, however, motivate the user to increase their local browser cache in order to potentially lessen time spent on waiting while your assets are loaded, but this won't help should the user watch three tons of YouTube each day.
SWC files are not intended for dynamic loading.
They are static libraries that can be linked in a swf using
-include-libraries and library-path options of mxmlc or - since you seem to be using FlashDevelop - SWC Include Libraries and SWC Libraries in Project>Compiler options
. SWC's may hold code (classes), assets (symbols/bitmaps/sounds...) or combination of the two.
Loading assets dynamically is done through flash.display.Loader
you may use the Loader as a simple DisplayObject instance that you add on stage:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Loader.html#includeExamplesSummary
, or use its ApplicationDomain as a library of Class definitions that will allow you to create instances at will :
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/ApplicationDomain.html#includeExamplesSummary
Caching from the browser will be sufficient in most cases, unless you have VERY specific needs
In the end, there is different ways to optimize loading times, one of which is having a small swf acting as loader/home menu, and loading rest of the content on demand like you seem to try doing, but you can also create a single swf with several frames, which will be "streamed" by flash player, example:
1st frame as small as possible holding just a few kb for a splash screen/logo/loading/whatever you want, to make the initial blank screen as short as possible, then second frame holding the main content. You can event extent this system with for instance
two levels of preloader: a first tiny frame with just a logo, second one with progress bar, and full background if needed
split content like home screen/menus in a frame, gameplay in the another, if you are making a game, so that gameplay continues loading while you are already displaying the menu

Workflow for Large Flash/AS3 Projects

I am currently working on a rather large, UI-heavy Flash game. Our team has been working on this for about 9 months now. None of us had any previous experience with Flash, so we have continually improved our workflows during this time. However, we still feel that what we are doing now is not optimal, especially the interface between coders and artists, so I am wondering how other teams are working.
The ideal workflow should satisfy the following requirements:
1. Reused UI elements are defined only once
This means, if we want to change a font or a button style, we do not want to go trough all of our menus and change them manually. We want them defined in one central place and only referenced from there. Bonus points if the assets are shared not only at edit time but also at runtime, i.e. they are downloaded only once.
2. Everything is loaded on demand
Currently, we have two different loading steps: First, we load the menu libraries. When this is done, the players can already interact with all the menus. Then, we start loading the actual gameplay data. The initial loading time is still too long, though, and causes us to lose many potential players. What we really want to do is to load only the bare minimum required for the main menu and then load everything else only when the player tries to actually open the respective menus. Zuma Blitz does this really well.
3. Artists can perform minor changes without help from coders
If a menu should be re-designed without changing the actual functionality, it should be possible for artists to do that on their own in Flash CS6. This requires a clear interface between art and code, and it should also be possible for artists to test and debug their changes before sending them to the coders.
-
Our current workflow looks like this: The artist build the screens as MovieClips in Flash CS6 and export them as SWFs. On the code side, load the MovieClips from the screen SWFs and use them as the View classes in our PureMVC-based system. The Mediators access the elements like text fields in the Views by their instance names.
This is error-prone because there is no central place to define the interface (i.e. the instance names). A lot of communication overhead between coder and artist is required. Also, it creates a dependency between the code and the internal structure of the movieclip. The artists cannot attach the text field to a different sub-movieclip when they want to apply some effects to it.
We are experimenting with an event-based interface that requires the artist to add a few lines of code to the movieclip. This is less error-prone and interdependent than before, but it still does not completely satisfy (3) unless we write additional tools for testing and debugging. This must be a common problem and I can hardly imagine that there is no easier way.
For (2), we also started building a home-brewed solution but again, this is such a common task, there has to be something out there already that we can use.
So, how do experienced Flash developers manage such large projects?
I have some thoughts, but they are based on my coding style, which is unique to me.
1. Reused UI elements are defined only once
Depending on what you're reusing, this can be as simple as defining a library symbol and just using it. Fonts can be replaced without digging with a search and replace, and you can also simply swap out the font in the Font Embedding menu.
For sharing across xfl's, you can use a Flash Pro Project. Keep in mind that there's a certain amount of time overhead involved in this (files will want to update when you open them or save them, Flash crashes more with Projects, and it can be a bad idea to try to work on two files from the same project at once).
Some people use swcs, but doing so requires that you instantiate things in it in code, which might not work for your workflow. I use them for audio only, and I find that the objects in it have to be compiled on or before the frame you designate as the AS compile frame, or the sound can't be properly instantiated. I suspect this is going to be the case for anything instantiated from a swc.
2. Everything is loaded on demand
One of the best-kept secrets of Flash is that this is trivially easy to accomplish using the timeline and educated use of the complier. Here's how it works:
If your ActionScript compile frame is a frame greater than 1, then here is how things will compile:
Before Frame 1:
Any visual assets and embedded sounds used on frame 1
Your main Document Class, plus any Classes directly referenced from the Document Class (which is a good reason to code to Interfaces)
Before your AS compile frame (N):
Your AS Classes (the code, not necessarily the visual/audio assets)
The visual and audio assets for any library symbols set to Export for AS in frame N (even if they are not used in the swf)
Before the frame where the asset is first used on the timeline:
The visual/audio assets in all library symbols where Export for AS in frame N is not checked.
If you put a spinner loading graphic on frame 1 and you have selected frame 10 as your export frame, then if you just let the movie play until it hits frame 10, here is how it will load:
If you have any heavy assets in your spinner or directly referenced in your main Document Class, users will see a blank screen while this stuff downloads
The spinner will become visible and spin
Once your AS Classes have loaded, along with the Library Symbols set to Export in Frame 10 and the assets that are actually on Frame 10, you'll see those assets, and everything you need to use them will be ready.
The rest of the swf will continue to load in the background, updating framesLoaded.
I actually use a combination of a setter for the object that's on frame 10, plus an ENTER_FRAME handler to check to see if we're on frame 10 yet. There are certain things that I have to do that are easier based on one and others that work better to do the other way.
3. Artists can perform minor changes without help from coders
If the code is all in the Base Class for the library symbol, artists don't need to understand it, as long as they don't remove or change a needed instance name. I try to minimize dependence on instance names by watching ADDED_TO_STAGE (capture phase) and watching for Display Objects by type. Once I have a reference to an object of the appropriate type, it's easy enough to watch for REMOVED_FROM_STAGE on that object to dereference it. This is similar to how frameworks such as RobotLegs and Swiz work.
Further, I use a concept I call "Semantic Flash," where I do a lot based on labels. I have a base Class, FrameLabelCip, which has built-in nextLabel() and previousLabel() functionality, as well as dispatching FRAME_LABEL_CONSTRUCTED events. It's really easy to go from storyboard event name to Flash label name and just build out the graphics bang-bang-bang.
I make heavy use of Graphic Symbols for synchronizing graphics across multiple labels (for example, bulleted lists), instead of relying on code. This animator's trick makes these things both robust and approachable to less-technical teammates.

Limitations of Web Workers

Please bear in mind that I have never used Web Workers before and I'm having some trouble wrapping my head around them.
Here's an explanation of a simplified version of what I'm doing.
My page has links to various files - some are text, some are images, etc. Each file has an image showing a generic file icon.
I want the script to replace each generic icon with a preview of the file's contents.
The script will request the file from the server (thereby adding it to the cache, like a preloader), then create a canvas and draw the preview onto it (a thumbnail for images, an excerpt of text for text files, a more specific icon for media files...) and finally replace the generic icon's source with the canvas using a data URL.
I can do this quite easily. However, I would prefer to have it in the background so that it doesn't interfere with the UI while it's working.
Before I dive right in to this, I need to know: can Workers work with a canvas, and if so how would I create one? I don't think document.createElement('canvas') would work because Workers can't access the DOM, or am I misunderstanding when all the references I've found say they "can't access the DOM"?
You cannot access the DOM from web workers. You cannot load images. You cannot create canvas elements and draw to them from web workers. For now, web workers are pretty much limited to doing ajax calls and doing compute intensive things. See this related question/answer on web workers and canvas objects: Web Workers and Canvas and this article about using webworkers to speed up image manipulation: http://blogs.msdn.com/b/eternalcoding/archive/2012/09/20/using-web-workers-to-improve-performance-of-image-manipulation.aspx
Your simplest bet is to chunk your work into small chunks (without web workers) and do a chunk at a time, do a setTimeout(), then process the next chunk of work. This will allow the UI to be responsive while still getting your work done. If there is any CPU consuming computation to be done (like doing image analysis), this can be farmed out to a web worker and the result can be sent via message back to the main thread to be put into the DOM, but if not, then just do your work in smaller chunks to keep the UI alive.
Parts of the tasks like loading images, fetching data from servers, etc... can also be done asynchronously so it won't interfere with the responsiveness of the UI anyway if done properly.
Here's the general idea of chunking:
function doMyWork() {
// state variables
// initialize state
var x, y, z;
function doChunk() {
// do a chunk of work
// updating state variables to represent how much you've done or what remains
if (more work to do) {
// schedule the next chunk
setTimeout(doChunk, 1);
}
}
// start the whole process
doChunk();
}
Another (frustrating) limitation of Web Workers is that it can't access geolocation on Chrome.
Just my two cents.
So as others have stated, you cannot access the DOM, or do any manipulations on the DOM from a web worker. However, you can outsource some of the more complete calculations on the web worker. Then once you get your return message from the web worker inside of your main JS thread, you can extract the values you need and use them on the DOM there.
This may be unrelated to your question, but you mentioned canvas so i'll share this with you.
if you need to improve the performance of drawling to canvas, I highly recommend having two canvas objects. One that's rendered to the UI, the other hidden. That way you can build everything on the hidden canvas, then draw the hidden canvas on the displayed one. It may not sound like it will do much if anything, but it will increase performance significantly.
See this link for more details about improving canvas performance.

Force SWF (Flash file) to load LAST after rest of webpage

I have a rather complex flash clip that ends up bogging down the loading of the rest of my webpage.
Can I force the flash to wait to load until the rest of the site loads?
If you do not mind to have javascript you may use something like SFWObject 2 library, here is documentation page http://code.google.com/p/swfobject/wiki/documentation there is different methods for using it, so you just need pick up which is more appropriate in your case. Main idea you may trigger swf player initialization with javascript, so you could control time when this happen, and so using it just do that after onload event triggering. But assume problem cold be more complicated than just delaying your clip, so try to test it on different computers and browsers.

symbols placed on the timeline become undefined if stepping backwards

I am using the frames in the timeline of a .swf as pages in a flash app. The user can advance to the next page by clicking a button that takes her to the next frame. Similarly, it is possible to navigate to the previous frame/page as well.
Most of the content is placed on the stage (i.e. created by dragging an instance of a library symbol to the stage) but properties of those instances, such as .visible might be changed via actionscript. Also, some objects are loaded from external flash files and displayed programmatically with addChild / addChildAt.
The problem is, if I am on Frame N+1 and there is an object displayed on the stage programmatically (i.e. with addChild, not by having it placed on the stage) and navigate to Frame N where there is an object that is placed on the stage (i.e. dragged from the library),
then the instance of that object is undefined/null and throws an error if I try to set its properties (like .visible).
The error does not occur if I am moving to the NEXT frame, only if I am moving to the PREVIOUS one. Therefore I assume that some kind of initialization is not getting called while going one frame back.
I was also thinking that the objects would just not "live" to the next timeframe, that is, their value would be lost and re-initialized because of scope, but if there is no dynamically created object on the stage, I can navigate back and forth just fine.
Is there a way to ensure that the objects created on the stage do not disappear while navigating back to the previous frame?
The first, and more useful, part of the answer is this: timeline keyframes and scripts can give conflicting information about display objects - whether they should exist, where they should be, and so on. For example, when you add an item by playing into its frame, and then delete it with script, and then play into its frame again. When this happens, there's no unambiguously correct thing for Flash to do, so it tends to be unpredictable. I believe what generally happens is that once you fiddle with a given object via script, it's considered to no longer pay attention to the timeline - but your mileage will vary.
Having said that, the reason things are different when you play backwards is the second and more arcane part of the answer. Internally Flash functions differently when seeking forward and backwards on the timeline. Flash internally treats keyframes as changes to be applied in the forward direction, so as you play forward, it applies those changes in sequence. When you move backwards, however, from frame N+X to frame N, it doesn't scan through the intervening X frames reversing those changes - it jumps back to frame 1 and fast-forwards along to frame N. Normally, it amounts to the same thing and you don't need to worry about it, but when you get into the twitchy area where scripts and the timeline have a different idea of what should be on the stage, you're liable to see things behave differently depending on which way you jump (as you are now).
The super-short version is, for things to work predictably, try to ensure that any given object gets added, updated, and removed the same way - either all via script, or all via the timeline. When that seems impossible, fiddle with your content structure - usually, the best solution is to change your object into two nested ones, so that the things you want to do with script occur one level higher or lower than the things you want to do with the timeline.
I'm not sure I got your question right, but as3 does not instantiate elements on the timeline as soon as you gotoAndSomething, but later that frame.
That is, you can't
this.gotoAndPlay(10)
this.elementOnTimelineFrame10.DoSomething()
without errors.
I remember using this chunk of code in the past to work around this problem. It uses the Stage.Invalidate() function to wait for an Event.RENDER before trying to access and children, more info (although vague as hell) is here
private function init():void
{
stage.addEventListener(Event.RENDER, stage_renderHandler);
}
private function stage_renderHandler(evt:Event):void
{
// Run your code here
updateChildren();
}
private function enterFrameHandler(evt:Event):void
{
// triggers the RENDER event
stage.invalidate();
}
This also might me very costly (performance wise). I would strongly advise against dynamically adding/removing objects to an existing timeline, is there any way in which you can place an empty Sprite above the timeline animation and use that for all your dynamic content?
Hope this helps