Embedded image assets and the memory consumption - actionscript-3

I have a few contradicting misconceptions about how Flash handles image assets. I'm going to write them down here, please correct me where I'm wrong.
I have an embedded image
[Embed(source = "../../lib/images/myImage.png")]
public var embeddedImage:Class;
How do I use it in my app without using unreasonable amounts of operating memory?
I was going to do this:
var bData:BitmapData = (new embeddedImage() as Bitmap).bitmapData;
And from that point on use bData if I ever want to display this picture anywhere, ensuring that there is only one bitmapdata per image.
But what worries me is that embeddedImage still stays, doesn't it? There are basically two copies of this image in the operating memory, right?
What should I do instead? May be I should instantiate new embeddedImage() each time I want to use it? But that looks even worse, now I'm clearly instantiating a bunch of unneeded copies.
If I loaded the image using the Loader class I would end up with only one copy of the bitmapdata if I wanted to, provided GC did a good job clearing the loader after it was done.

The [Embed] block embeds the image into the application. This doesn't use RAM*, it increases the size of the application itself (the .swf or whatever format you export to).
When you use new EmbeddedImage(), you create an instance of the embedded image. This instance is what consumes RAM. Each instance of that image will consume additional RAM.
When you access the bitmapData property of that embedded image, it does not create a new instance or consume additional RAM, it refers to existing data which is already consuming RAM.
Because the BitmapData is the data which represents an image, it is obviously the largest. Knowing this, we look at ways to use a single instance of BitmapData for any graphics we want to display. Depending on the display architecture you've opted to use, there are different ways to go about referring to that BitmapData when drawing multiple instances of the same image.
As an example, we have your instance of EmbeddedImage created:
var embeddedImage:EmbeddedImage = new EmbeddedImage();
And we have a 'canvas', which is a single Bitmap added to the stage:
var canvas:Bitmap = new Bitmap();
canvas.bitmapData = new BitmapData(500, 500, false, 0xFFFFFF);
addChild(canvas);
Using the method copyPixels(), we can copy across a section of data from the embeddedImage, to the canvas without needing to make another instance of BitmapData, which would consume RAM equivalent to the source for each time we want to draw the graphics. Example:
var drawPosition:Point = new Point();
var sourceRect:Rectangle = embeddedImage.bitmapData.rect;
// Draw the embeddedImage 50 times.
canvas.bitmapData.lock();
for(var i:int = 0; i < 50; i++)
{
canvas.bitmapData.copyPixels(embeddedImage.bitmapData, sourceRect, drawPosition);
drawPosition.x += 10;
}
canvas.bitmapData.unlock();

Related

Actionscript 3, reading two files then triggering a function, best practice

I need to read a part of two files, and once both parts of both files are loaded to trigger a function that does some work.
What is the best way to approach this problem.
I am currently triggering the second file load once the first is loaded, however it seems poor coding style, I think this because my OO code starts looking procedural.
EDIT: So its an Air based app so using filestream.
In the end I found I actually needed to read each file in a different way. Because I need the same part of both files, and I dont know the file size, I need to read one file first and once I have fileStream.bytesAvailable and position, I can then look for the same data from the second file. I found I must handle files smaller than my read size and the end of files beyond multiples of my read size.
You don't specified what file and from where you wont to load the file but you can actually load multiples files in parallel.
If you want to read only part of file from local machine you can use AIR's FileStream class - very easy and you don't have to load whole few hundreds MB file:
import flash.filesystem.*;
var file:File = File.documentsDirectory;
file = file.resolvePath("Apollo Test/test.txt");
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var str:String = fileStream.readMultiByte(file.size, File.systemCharset);
trace(str);
fileStream.close();
Another option is to use URLStream and listen for ProgressEvent.PROGRESSevents to read data of partially loaded file.
You may also want to see NetStream class which is used to stream video.
there is many options, using File, FileStream is only available on air applications.
The File class extends the FileReference class. The FileReference
class, which is available in Flash® Player as well as Adobe® AIR®,
represents a pointer to a file, but the File class adds properties and
methods that are not exposed in Flash Player (in a SWF running in a
browser), due to security considerations.
as noted above, if you are creating a non-AIR application, FileReference should be used instead of FileStream and File classes, as you dont tagged AIR in your question.
FileReference does not provide any open("path") to you (due to security considerations), but a browse method will be available and ask's your client's for selecting a file. here is an example, which also explain how to trigger a function when opening is done:
var filereference:FileReference = new FileReference();
filereference.addEventListener(Event.SELECT, onFileSelected);
var text_files:FileFilter = new FileFilter("Text Files","*.txt; *.html;*.htm;*.php");
var all_files:FileFilter = new FileFilter("All Files (*.*)","*.*");
filereference.browse([text_files, all_files]);
// triggered when a file is selected by user
function onFileSelected(e:Event):void {
filereference.removeEventListener(Event.SELECT, onFileSelected);
filereference.addEventListener(Event.COMPLETE, onFileLoaded);
filereference.load();
}
// triggered when file loading is complete
function onFileSelected(e:Event):void {
var data:ByteArray = fileReference["data"];
filereference.removeEventListener(Event.COMPLETE, onFileSelected);
}
two more events to be listened for suddenly error's occurred and displaying a progress bar for loading progress (its sync):
IOErrorEvent.IO_ERROR and ProgressEvent.PROGRESS

patching actionscript without constantly rebuilding swf

How can I patch actionscript without constantly rebuilding sfw?
There is a fairly large actionscript project that I need to modify and resulting swf is used on a live site. The problem I have is that I need to make quick small updates to the swf and it's not acceptable to update the swf on live site ten time a day (I don't control that part, I need to ask another person to put the result on live site).
What options do I have to workaround that issue? I'm a complete noob when it comes to actionscript and all flash related stuff and I'm not even sure what is possible and what isn't. I'm thinking about the following approaches, which ones are possible/acceptable?
Imagine that live site is on www.livesite.com/game.html and this page loads www.livesite.com/flashgame.swf. In that flashgame.swf among many others there is a class com/livesite/Magic.as that gets instantiated and instance of that class has a member variable xxx123 of class com/livesite/MagicWork.as. I only need to modify this MagicWork class. Now, I simply modify it, build and ask to put updated flashgame.swf live. So, I want to avoid that manual step.
All my ideas can be split in two basic approaches: 1) keep flashgame.swf totally unmodified and then load flashgame.mod.swf that contains alternative implementation of that MagicWork class, then using javascript access internals of instance of that Magic class and update its xxx123 member to be an instance of MagicWork class from flashgame.mode.swf. I'd need to modify game.html to load my javascript so that my js file would load flashgame.mod.swf and patch code inside flashgame.swf. By patching I mean javascript-style overwriting of Magic.xxx123 to a new value. flashgame.mode.swf would ideally reside on my own host that I control. Is that kind of stuff possible, if not what's not possible?
2) I could make one-time change in flashgame.swf so that it would effectively load itself my own code at runtime and patch it's xxx123 member. Is that possible?
I had already written a note about loading runtime shared libraries previously. I'll put the most essential parts of the process here, and add a link to the full article at the end.
You need to tag your main application entry point in the following manner.
[Frame(factoryClass="Preloader")]
public class Main extends Sprite
{
}
Then create a class called Preloader.
public class Preloader
{
public function Preloader()
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.loader_completeHandler);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.loader_ioErrorHandler);
var request:URLRequest = new URLRequest("math.swf");
var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
loader.load(request, context);
}
private function loader_completeHandler(event:Event):void
{
var mainClass:Class = getDefinitionByName("Main") as Class;
var mainInstance:Main = new mainClass();
this.addChild(mainInstance);
}
}
The full implementation of the Main class is like this.
[Frame(factoryClass="Preloader")]
public function Main()
{
var integer:IntegerArithmetic = new IntegerArithmetic(); // Type declared in math.swf
var operand1:int = 10;
var operand2:int = 10;
var result:int = integer.add(operand1, operand2);
}
Deploying Runtime Shared Libraries
The confusing bit about using a runtime shared library is realizing that the SWF has to be extracted from the SWC at the time of deploying the application. This was not immediately obvious and I ended up spending days placing a compiled SWC file in various locations and wondering why the application was unable to load it at runtime. An obscure article on the Adobe website made explicit this particular step and set things straight.
The full article along with the same example is available at http://www.notadesigner.com/runtime-shared-libraries-with-plain-actionscript/.

How to share tileSets between different tiledMaps?

If I have several .tmx files using the same tileSet, obviously I'd like to load the tileSet texture only once, but if I use the regular way to do it, the texture is loaded twice...
TmxMapLoader loader = new TmxMapLoader();
TiledMap tiledMap1 = loader.load("map-test.tmx");
TiledMap tiledMap2 = loader.load("map-test.tmx");
Texture texture1 = tiledMap1.getTileSets().getTile(1).getTextureRegion().getTexture();
Texture texture2 = tiledMap2.getTileSets().getTile(1).getTextureRegion().getTexture();
// texture1 is different than texture2
So my question is, is there any way to avoid the map loading the same assets several times?
Probably I'll end writing my own TmxLoader because I don't want it to load images from the Image layer but replace them with actual game objects... but I'd like to know the vanilla way...
Edit:
The solution provided by David Saltares was the one I needed, so I'll left here the proper code:
// supossing that both maps use the same tileset image...
TmxMapLoader loader = new TmxMapLoader();
assetManager.setLoader(TiledMap.class, loader);
assetManager.load("map-test1.tmx", TiledMap.class);
assetManager.load("map-test2.tmx", TiledMap.class);
assetManager.finishLoading();
TiledMap tiledMap1 = assetManager.get("map-test1.tmx");
TiledMap tiledMap2 = assetManager.get("map-test2.tmx");
Texture texture1 = tiledMap1.getTileSets().getTile(1).getTextureRegion().getTexture();
Texture texture2 = tiledMap2.getTileSets().getTile(1).getTextureRegion().getTexture();
// now texture1 == texture2 :)
What I'm wondering is, why this is not the default? I mean, assetManager has lots of loaders by default, but not the tmx one...
Use AssetManager, call its setLoader method passing a new instance of TmxMapLoader.
When loading a map via the asset manager, the tmx loader will try to handle it and tell the asset manager all its dependencies. One of these dependencies will be the texture for the tiles. The asset manager will satisfy the dependencies and then the map will actually get loaded.
All assets under the manager are referenced counted, so calling load() on the same handle, won't actually allocate more memory.
This means that, when the second map gets loaded and the manager tries to satisfy its dependencies, it will find the texture is already loaded. It will simply increment its reference count by one.

Loader.as returning blank bitmap

I have an application which pulls in Bitmap resources from a server - currently I use the Loader class to do this, then, once they're loaded, generate a BitmapData based on the loader dimensions and draw the instance of Loader directly to it (the BitmapData is used for Away3D textures as well as Bitmap instances, so I have no need for the Loader once fetched).
This has always worked for me, but recently I started getting 0x0 Loaders, and invalid BitmapData as a result.
I stopped doing this:
this.imageBitmap = new BitmapData(this.imageLoader.width, this.imageLoader.height, true, 0);
..and started doing this:
this.imageBitmap = new BitmapData(event.target.content.width, event.target.content.height, true, 0);
Where event is the Event.COMPLETE event fired by the loader. This fixed the dimension problem, but the BitmapData is just a plain white bitmap (and it's set to transparent by default, so this is being drawn into it). Frustratingly, this doesn't happen every time, if I refresh the application it works as it should around 25% of the time, otherwise it plays up like this.
I've got a tight deadline and I'm really screwing about this, if anyone could help or suggest a better way of doing it you'd really be saving my neck!
Sounds like you need to adjust the image decoding policy for the loader - to ensure it decodes the image before COMPLETE fires - then the width and height etc should be reliable.
To do it, just add a suitable LoaderContext object to the Loader.load method:
var loaderContext:LoaderContext = new LoaderContext();
//set decode policy
loaderContext.imageDecodingPolicy = ImageDecodingPolicy.ON_LOAD;
//load image
loader.load(yourUrl, loaderContext);
The default decode policy is ImageDecodingPolicy.ON_DEMAND - which doesnt decode the image until it is actually required.
Lang docs: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/ImageDecodingPolicy.html
Fixed it, stupid oversight and bit of an obscure situation but I'll leave an answer in case anyone runs into something similar.
My loader is contained in an Asset class - when another object requires the internal bitmap, it queries this class - if the bitmap's present, it returns it, if not it loads it with a loader and registers a callback for a COMPLETE event which is fired when the Loader has loaded and transferred its contents to a BitmapData instance.
The stupid mistake I'd made was that, if several objects were querying the same (as-yet-unloaded) asset, it would start reloading the asset each time, creating a new Loader as it did so...so when the first Loader was complete, it would fire an event but no reference to it would exist, not only creating a memory leak but causing the Asset class to extract the BitmapData from the most-recently-created Loader, which was not complete! The asynchronous nature of Loader is the reason it worked sometimes, as on occasion the final Loader would be ready in time for BitmapData extraction.
Simple solution was to create an internal boolean, _isLoading, which is set to true the first time load() is called - any subsequent calls are ignored if it's true, but callbacks still registered, works a treat!

Adobe AIR. Get MD5 of a file

I've done it this way, but Adobe Air hangs for several seconds.
private function test():void
{
fileStream = new FileStream();
fileStream.addEventListener(IOErrorEvent.IO_ERROR, fileError);
fileStream.addEventListener(Event.COMPLETE, opened);
fileStream.openAsync(filePath, FileMode.READ);
}
protected function opened(event:Event):void
{
var bytes:ByteArray = new ByteArray();
fileStream.readBytes(bytes);
fileStream.close();
// MD5Stream from package com.adobe.crypto.MD5Stream https://github.com/mikechambers/as3corelib/blob/master/src/com/adobe/crypto/MD5Stream.as
var md5stream:MD5Stream = new MD5Stream;
trace(md5stream.complete(bytes)); // md5
}
How to make the process of getting md5 without hanging?
Try using Bloody's MD5 implementation. It's apparently a lot faster.
While it will speed up the hash calculation, perhaps even adequately, you're not really solving the underlying problem, which is that you want a non-blocking operation in a single threaded application model. In Flash/AIR, this is generally done by breaking the work up into smaller chunks, and doing only one chunk's worth of processing each frame, instead of all at once during one frame. There's even a cool framework to simplify this!
I noticed that the library you're currently using, MD5Stream, is built for incremental updates -- so you can easily feed it little chunks of the file each frame until the entire file is processed. This will allow the frame rate to stay relatively constant while the hash is computed.