Flash AS3 loading best practices - actionscript-3

I am creating an interactive flash application where I need to use many sound files and images. I am currently loading resources (both images and sound files) as I need them. When I run it on my computer everything works fine and I see no delay. Running it on an offsite computer shows pauses and delays. I know this is due to the time it takes to load the resources.
I want to know what the best practice for loading resources is. Should I preload everything in the beginning (which will create a considerable pause)? Is it better to have a short pause multiple times throughout when a new resource is needed? Or is there a better solution (I hope this is the case)?
I have been programming in AS3 for about 3 months so I am relatively new. I'm sorry if this question is really noob, but I do need to figure out what to do about the delays.

It depends on what kind of application it is:
If you expect a user to go through your whole application anyway (like a game for example) you should do preload the resources. If your application is more like a media player or an image gallery where most users will only see a few resources, you should load resources on demand.
It also depends on how large the resources are. You shouldn't let users wait to long or create to much traffic. On the other hand it may be easier to do a single preload than loading each tiny resources in a single request. Maybe you coulddefine larger sets to in a single step to avoid this. You may even combine both methods: preload some common resources and load some other stuff in the background.

I agree with #kapep that you should pre-load commonly used resources at the beginning. If there are large resources that the user may not need you could load those on demand.
If this test is sequential you could load "test question 2" material right after "test question 1" starts. You can load asynchronously so the application is still interactive (user can interact with test question 1) while more material is being loaded (test question 2 resources).

For preloading the resources I strongly recommend using Greensock library. Actually by using LoaderMax you can queue the content to be loaded and then attach the loaded content to the containers (movieclips, sprites etc.)
Here is a sample code for loading multiple resources:
var queue:LoaderMax = new LoaderMaxVars()
.maxConnections(1)
.onProgress(onContentProgress)
.onIOError(onIOErrorHandler)
.onComplete(onContentLoaded));
queue.append(new SWFLoader(contentTobeLoaded,new SWFLoaderVars().name(loaderName)));
....
private function onEmployeeContentLoaded(event:LoaderEvent):void {
var loadedContent:Array = (event.target as LoaderMax).content;
....

Related

dynamically changing the playback speed of a sound in as3 without altering pitch

I'm making a game based on simple song creation, and I'm planning on having a feature where players can listen to the songs they've created with the game. the rhythm of the melody is controlled with a system of timers, but this will not work for the backing track presets I am planning on implementing, as each mp3 file in the backing tracks represents one bar instead of one note.
while it would be possible to use my timer system for playing the backing tracks, this would require several more audio files, much more coding and would push the project far behind schedule. therefore, i need to manipulate the playback speeds of the files I already have. I've commonly seen two examples of how to do this, here: http://2008.kelvinluck.com/2008/11/first-steps-with-flash-10-audio-programming/ and here: http://blog.andre-michelle.com/2009/pitch-mp3/
the problem with both of these is that they also alter the pitch as well. this is a problem for me, as I would very much like players to be able to alter the pitch and tempo of their songs separately. I think the code I need is similar to the examples above, but I'm having trouble understanding those since I haven't had much experience with bytearrays and such. I'd like to be able to understand the examples i included so that I can figure out what I need to do in order to get my game working the way it should, but help of any sort is appreciated. thank you =)
You can try https://github.com/also/soundtouch-as3
there is an early (alpha) demo at http://static.ryanberdeen.com/projects/soundtouch-as3/demo/player/stretch.swf
quality is "acceptable" if you are using 1.0x-1.5x factor (less than 1.0 gives very artificial distortion)
You could also try :
http://iq12.com/old_blog/2009/08/25/real-time-pitch-shifting/
test : Online demo
Their online demo didn't load a track for me (deleted MP3?), so I put a recompiled SWF on my server just for testing. It loads this MP3 audio clip, if you wanna compare results to original sound.
It aims to preserve audio length (time scale) whilst adjusting pitch (deeper when slow or higher when faster). You could possibly combine this with Kelvin Luck's Second Steps.... Thereby having example codes for speed and pitch.
It was inspired by some C# code ported from this C code as found at (with concept explanation) : http://blogs.zynaptiq.com/bernsee/pitch-shifting-using-the-ft/

Under what circumstances would loading images individually with HTTP/2 be slower than loading all images at once with a sprite a la HTTP/1.1?

HTTP/2 makes it possible to multiplex connections, eliminating the need for more than one connection to a server. Over a single connection, many individual images can be sent down to the client. This obviates the old image sprite pattern of combining many images into one and using CSS to cut it apart.
I'm curious if sprites would still actually be faster in an HTTP/2 world. If so, under what circumstances?
Sprites, as you will know, are used to prevent multiple requests being queued, so with one payload you could get all the sprites for the site.
But with sprites you tend to get lots of additional icons that are used throughout the website that aren't all needed on any single page.
So with http/2 multiplexing, queuing resources is no longer an issue. You get the speed benefit when you only download the files needed for each page.
However you may get better compression by combining some images into a single file, making the overall size of file transfers smaller.
Speed tests run by Benoît Béraud and Alexandre Masselot have given an example of a sprite sheet loading faster than individual sprites. They concluded that sprite sets can still be used to optimise site performance when using http/2 http://blog.octo.com/en/http2-arrives-but-sprite-sets-aint-no-dead/
Extended write up about http/2 by Rachel Andrew can be found here:
https://www.smashingmagazine.com/2016/02/getting-ready-for-http2/
With HTTP/2 multiplexing, the server will be reading a lot of small files instead of reading a single big file. If the server is resource-limited (some Internet-of-Things contraption, for example), then you might be able to find a situation where it's better to have it making the single, big read instead of a lot of small ones, since each read causes the server OS to potentially do a lot of file-access-related operations.
On the client side, the browser will be managing a lot of small files, instead of a big one. I can imagine the code path used for the current sprite workflow being well massaged and optimized, since it's so commonly used. So it might happen that the new case of having a lot of small files could be slower, at least for a time.

making HTML5 AssetLoader, do browsers always cache images?

I am building an asset loader for a simple Object-Oriented game engine in HTML5. Right now I know of two ways to make the asset loader (summarized below) and I prefer the second approach. My question is, is the second way guaranteed to always work for all browsers?
For clarity:
the name of the class in question is AssetLoader,
the method to load all assets is called loadAssets(),
the main class is Game,
and the main game loop is runGameloop().
Approach 1
Create an instance of AssetLoader that will persist throughout the entire game. When loadAssets() is called at game start, it will create a dictionary that will hold key/value pairs of all the assets for the duration of playtime.
When a sprite requires an image, it will query AssetLoader with a given name (ex. "Archer"), and the instance will return the appropriate image for the sprite to use.
Approach 2
Create an instance of AssetLoader that will not persist throughout the game (it will be called once and not be assigned to any instance variables).
The instance's responsibility will be to query the server for each asset which will cause the browser to cache the assets; much like:
function AssetLoader()
{
...
self.loadAssets = function(runGameloop)
{
self.tempImage = new Image();
$(self.tempImage).load(function()
{
self.assetsLoadedSoFar += 1;
if(self.assetsLoadedSoFar === self.totalAssets)
{
self.runGameloop();
}
});
self.tempImage.src = "assets/sprites/archer/archerSpriteSheet.png";
}
...
}
Now whenever a sprite needs an image, that image should now be cached in the browser and it just loads it with a new Image() object without going through AssetLoader.
Why I prefer approach 2
1.) I want to avoid introducing unnecessary layers of abstraction to the engine, I don't want to have to go through AssetLoader everytime I want to load an asset.
2.) If I have alot of assets in the game, I don't want them all to be simultaneously loaded in a single instance of AssetLoader. Perhaps someone can correct me but wouldn't having all those resources loaded at once unnecessarily strain the game?
So right now I have a working version of Approach 2 here and am mostly happy with it but what I need to know is: "is the browser guaranteed to always cache a given image using approach two?" or is that something I can't rely on? Are there certain configurations in which automatic caching might be turned off? (is that even possible?). Do you have any other approaches you think are better? Thanks alot for your time!
I don't think you can rely on the browser cache. It is possible to disable automatic caching and I imagine it is reasonably common for people to do just that.
I've done exactly this in the past for two reasons:
Low disk space on a computer shared by the family (multiple separate accounts)
When developing, in order to ensure that the latest changes are always visible on page refresh
Also, caching is disabled in incognito / private browsing modes of Chrome / Firefox.

Optimising Old AS3 Flash Project

I have an old SWF project file which is a series of png sequence to produce a 3D tour of numerous stadiums (If you can get it to load http://tinyurl.com/7h2zpcb). When I initially created it I never intended it to be published on the web (it was a university project) however I now would quite like to show it on the internet. The structure is of a main timeline with 4 stadiums each with a png sequence, then, when clicking on one of the stadiums, 4 more png sequences. The only problem is that it is all in one file and is over 12mb, plus has no pre-loader.
It is written in AS3 and is rather complicated as I used movie names and trimming to have reusable functions. It does however have global variables already set-up if this could help.
I have 2 questions. First, is there an easy method of separating out the project movies to 5 individual swf files. i.e main timeline, and each individual png sequence? Or will I need to copy and paste and copy assets over to each FLA file?
Secondly, would it just be easier to try using a preloaded and hoping that users wait for the project to download?
If you have any thoughts on this please give them. Is there a way to optimise the project in another way I am unaware of? As a side note there are a lot of pngs and total over 300mb when combined so I think XML is out of the question?
Thank you for your time. Any suggestions are welcome
For completeness' sake.
I did some research and tests and realised the time it would take to change the project to use any other technology would be too great for my needs. I simply just added a pre-loader to the site and saved myself a lot of extra time. When linking to the site I affix a message explaining that is for an offline installation and there may be a long load-time.
Hopefully this will help others in the future.
Thank you to Marty Wallace, shaunhusain and grapefrukt for their time and advice on this.

Starting with HTML5 Game Development - Very confused

I'd like to start developing a "simple" game with HTML5 and I'm quite confused by the many resources I found online. I have a solid background in development, but in completely different environments (ironically, I started programming because I wanted to become a game developer, and it's the only thing I've never done in 13 years...).
The confusion derives from the fact that, although I know JavaScript very well and I have some knowledge of HTML5, I can't figure out how to mix what I know with all this new stuff. For example, here's what I was thinking of:
The game would be an implementation of chess. I have some simple "ready made" AI algorithm that I can reuse for single player; the purpose here is to learn HTML5 game development, so this part is not very important at the moment.
I'd like build a website around the game. For this I'd use a "regular" CMS, as I know many of them already and it would be faster to put it up.
Then I'd have the game itself, which, in its "offline" version, has nothing to do with the website, as, as far as I understand, it would live in a page by itself. This is the first question: how to make the Game aware of User's session? The login would be handled by the CMS (it should be much easier this way, as User Managememt is already implemented).
As a further step, I'd like to move the AI to the server. This is the second question: how do I make the game send player's actions to the Server, and how do I get the answer back?
Later on, I'd like to bring a PVP element to the game, i.e. one-against-one multiplayer (like the good old chess). This is the third question: how to send information from a client to another, and keep the conversation going on. For this, people recommended me to have a look at Node.js, but it's one more element that I can't figure out how to "glue" to the rest.
Here's an example of a single action in a PVP session, which already gives me a headache: Player 1 sends his move to the Server (how does the game talk to Node.js?). I'd need to identify the Game Id (where and how should I store it?), and make sure the player hasn't manually modified it, so it won't interfere with someone else's game (how?).
I'm aware that the whole thing, as I wrote it, is very messy, but that's precisely how I feel at the moment. I can't figure out where to start, therefore any suggestion is extremely welcome.
Too many things and probably in the wrong order.
A lot of the issues don't seem to me to be particularly related to HTML5 in the first instance.
Start with the obvious thing - you want a single page (basically a javascript application) that plays chess, so build that. If you can't build that then the rest is substantially irrelevant, if you can build (and I don't doubt that you can) then the rest is about building on that capability.
So we get to your first question - well at the point at which you load the page you will have the session, its a web page, like any other web page, so that's how you get the session. If you're offline then you've persisted that from when you were online by whatever means - presumably local storage.
You want to move the AI to the server? Ok, so make sure that the front end user interaction talks to an "interface" to record the player moves and retrieve the AI moves. Given this separation you can replaces the AI on the client with an ajax (although I'd expect the x to be json!) call to the server with the same parameters.
This gets better, if you want to do player to player you're just talking about routing through the server from one user/player to another user/player - the front end code doesn't have to change, just what the server does at the far end of the ajax call.
But for all this, take a step back and solve the problems one at a time - if you do that you should arrive where you want to go without driving yourself nuts trying to worry about a bucket full of problems that seem scary that you can probably easily solve one at a time and I'd start by getting your game to run, all on its own, in the browser.
About question one: You could maybe give the user a signed cookie. E.g. create a cookie that contains his userid or so and the SHA2 hash of his userid plus a secret, long salt (e.g. 32 bytes salt or so).
About question two: For exchanging stuff and calling remote functions, I'd use the RPC library dnode.
About question three: Use the same thing for calling methods between clients.
Client code (just an example):
DNode.connect(function (remote) {
this.newPeer = function(peer) {
peer.sendChatMessage("Hello!");
};
});
You don't have to use game IDs if you use dnode - just hand functions to the browser that are bound to the game. If you need IDs for some reason, use a UUID module to create long, random ones - they're unguessable.