(AS3) Does setting variables to private help garbage collection? - actionscript-3

Novice programmer here.
I'm currently coding a simple game with the title screen and the main game loop in separate "keyframes" (this is in CS6). Once I transition from the title screen to the game keyframe I'm concerned that the buttons/movieclips/variables are going to stick around and waste memory + clutter the screen.
If I have the variables/functions set to "private" will that help the garbage collector take care of them? How should I go about "clearing the screen" and making sure I'm not being wasteful/leaking memory?
None of the tutorials or books I've been reading to learn AS3 have really covered this topic, if there are any good guides or obvious tips I've missed as far as memory management best practice goes in AS3 I'm interested in seeing them. The only thing I've learned so far is that I should manually set all my event listeners to weak reference.
Bonus question: I'm using a full-screen bitmap and blitting things onto it for my display. If I am blitting dozens of objects onto the screen per frame I don't need to worry about the blitted "sprites" that are being "covered up," do I? I'm hoping that the bitmap is one pixel thick and not just stacking things on top of each other.

Firstly, the only way you will have total control over your resources is if you leave the timeline for what it was intended for, creating and exporting assets in to swc or swf format, which you can embed the former and either embed or load the latter.
What you should be doing is learning how to develop in an Object Oriented manner, starting with a Document class (as you're using CS6) and then building your game using a series of classes which have defined tasks. Using classes promotes re-usability throughout your game. Depending on the complexity, I would consider a framework like PureMVC or Robot legs.
Garbage collection in flash is mark and sweep, which means you have to de-reference all your objects, which usually starts with removing associated listeners, timers and any further references to them, eg. clearing from arrays or objects hashes. Finally you would set the object in question to null which makes it 'elligible' for garbage collection but does not actually guarantee it. Flash will come and clean up as it sees fit.
Personally if you could get hold of Flash Builder, this has a fantastic memory management profiling tool, when you are developing using OOP mentioned above, you can use this tool to see all the instances that exist in your game. Now the good part here is you can do a memory snapshots in time, and compare them to see which objects linger around and are causing memory leaks. There is a garbage collection button which you should invoke between capturing snapshots, this is only available as you are developing, though using Adobe AIR you can force gc calls manually.
Regarding your bonus question, im not sure how you are doing this blitting, if you are adding objects to the stage this is increasing memory, you cannot avoid this. What you describe as 1px thick is what flash renders, you can see what is being redrawn by right clicking on the stage and selecting the redraw regions option, to see a red box showing what flash has to redraw, it will only redraw what it needs to, this is useful to check if your frame rate suffers.
So to summarize:
Consider using Flash CS6 for creating assets.
Learn about Object Oriented programming in Actionscript 3.
Consider developing in Flash Builder (or free Flash Develop).
OOP will help with organisation and de-referencing objects for garbage collection.
I hope this helps and good luck with your game.

Related

Is Starling worth implementing for my AS3 MMO?

For the past year I have been working on an isometric city builder. So far I have not used any framework apart from a loose PureMVC clone.
I have heard of Starling but only recently have I played with it.
From my research, the performance boost is fenomenal, but this forces me to manage my resource a lot tighter.
At the moment, I am exporting building animations one building at a time, in ~16 frames/pngs. These are cropped, resized and exported in Photoshop by a script and then imported in Flash, then exported as a swf, to be loaded / preloaded / postloaded on demand.
The frames are way too big to make a spritesheet with them, per building. I believe its called an atlas.
These pngs are then blited between lock() and unlock(). After the buildings + actors walking around are sorted, that is.
I am unsure if just using starling.Movieclip for the buildings, where instead of loading the pngs, I would build a MovieClip symbol with its frames. So bliting wouldn't even be necessary. Unless adding bliting on top of Starling would improve performance even more. That would allow fatter features such as particles effects, maybe some lighting.
Google isn't offering me a strait answer, thus I am asking here.
Google isn't offering a straight answer because there isn't such. It depends very very much on what you've done, how much knowledge you've got and what are your goals.
Using Starling gives benefits as well as drawbacks. Your idea of resources will change totally. If you really have enormous amount of assets, then putting them into GPU will be really slow process. You must start from there - learn what Starling does, how resources are managed with it and what you need to change in order to make the transition between the two.
If this is not that hard and time consuming task, you will have some performance optimization. BUT again it depends on your current code. Your current code is really important in this situation as if it's perfectly optimized your gain won't be that much (but commonly would still be).
If you need to switch between graphics regularly or you need to have dynamic assets (as images for example) you must keep in mind that uploading to GPU is the slowest part when talking about Starling and Stage3D.
So again, there is not a straight answer. You must think of GPU memory and limit, GPU upload time, as well as assets management. You also need to think of the way your code is built and if you are going to have any impact if you make the switch (if your code heavily depends on the MovieClip like structure, with all that frames and things) - it will be hard for you. One of the toughest things I fought with Stage3D was the UI implementation - there is almost only Feathers UI which will take you a few weeks to get along with.
On the other hand, Starling performs pretty well, especially on mobile devices. I was able to maintain a stable 45fps on a heavy UI app with a lot of dynamic loading content and multiple screens on an old iPhone 4S, which I find great. Latest mobile devices top at 60fps.
It's up to you to decide, but I'll advise you to have some experimental long-lasting project to test with, and then start applying this approach to your regular projects. I've done the dive to use it in a regular very tightened deadline project, and it was a nightmare. Everything worked out great, but I thought I would have a heart attack - the switch is not that easy :)
I would suggest using DMT for rasterizing your vector assets into Straling sprites at runtime, and it'll also keep your DisplayTree! meaning that you'll still have the parent/child relations that you had in your Flash Assets.
DMT will not duplicate assets, and will rasterize the vectors into texture atlases only one time (Cache is saved)
you can find it here: https://github.com/XTDStudios/DMT

WorldRenderer responsibilities

I started learning libgdx lately and, obviously, I've been looking into several sample games and tutorials.
I couldn't help but notice inconsistencies into how authors/developers choose to design their game classes - especially when it comes to the "renderer" classes.
In some examples, I see some authors relying solely on the "renderer" classes to draw using the SpriteBatch. While others tend to send a SpriteBatch reference to game objects to do the rendering themselves.
For example, considering a Bird class, some would associate it with a Texture type, load it and render the bird inside a Bird.render method. Others load the Texture in separate "Renderer" classes (Like WorldRenderer) and draw the bird texture from there by relying on position parameters such as bird.getX() and bird.getY().
I wrote some sample games using XNA in the past and I used to embed the rendering logic into my game classes. My renderer class used to simply loop over all "enabled" game objects and call "GameObject.render()". Is this a bad practice in libgdx?
It is not about bad practice in libgdx, it's a general opinion oriented problem.
Usually, it's always better if you can separate game logic and rendering logic (preferably in different classes). This way, if you want to change look and feel of the game (re-skin it) later, you won't have to touch the code containing game logic (less testing required, no new bugs).
But not everyone follows this (some might think it as overkill for small things). Having renderer class for each and every small thing might seem too much. So you'd see a lot of code having mixed both rendering and game logic.
If you want to build scalable games, I'd suggest you to follow MVC (game codes so large that developers might get lost). But at the same time, you should be pragmatic enough to know when not to use it (small games taking 2 weeks to make).
So it's for you to decide really, since it's about personal preferences.
Hope this helps.
A lot probably depends if the developer has used MVC (Model-View-Controller) before. In an MVC design the "game" objects like bird are part of the model and don't directly have anything to do with the display(view). Sometimes it depends on the technologies being used, for instance the LibGDX Scene2d API warns you that "Scene graphs have the drawback that they couple model and view".
In a worldRenderer you should render all your objects. All your objects belongs to a world so it makes sense. A benefit to add attention to is that you can always keep all gameObjects in separate arrays aswell as in a big array (containing all).
Array: GameObjects
Array: Birds (also in GameObjects)
Array: Cows (also in GameObjects)
Array: Cats (also in GameObjects)
This makes it possible for you to decide on what "z" axis all gameobjects should rely on (render) aswell as just loop through them all right away (update)

Bigger stage vs scrolling background

I'm making a flash game, and I can't decide to use a bigger stage or a smaller one, with scrolling background to make it run smoother. I's going to be some kind of strategy game if it matters.
Thanks
One option is to have a bitmap object the size of your stage for example 800x600, then draw your objects into the bitmapdata of that bitmap using copyPixels this is known as blitting and is pretty fast.
Another option is to just use the flash display list and add every object as sprites onto the stage.
Second method is easier to handle in terms of mouse events and stuff.
My advice is to start with the second option and see if performance is enough, if not go with option 1.
There are many, many variables that determine the performance of your application.
To answer your question, a smaller stage area will make your program run faster. The amount of difference will depend on the way your application deals with display objects. Flash will not render things that are completely outside the stage bounds. So keeping only those objects that are needed at any given time on the stage is a good practice.
using flash player 11's new stage3D features (even for 2D stuff) will likely make your game very smooth. Lots of good frameworks out there that can take care of the low-level stuff if you don't want to get into it. For 2D, starling is very easy to get started with, and seems to be Adobe's favored framework.
At a bare minimum, make sure you use GPU acceleration in your output/compiler options.
There are LOTS of other tips for optimization people could get into, but that is better suited for google searches as Stackoverflow is about specific questions.

Actionscript without display list (update/draw loop)

I've been working with several different programming languages recently, and I've come to the conclusion that I don't really like the display list in Actionscript. I would much rather have an update/draw loop and draw and manage everything manually like in XNA (C#).
What I do like in actionscript is the ease of use of events, movieclips animations and vector graphics.
What are the possibillites for this?
I would really like to be able to use animated movieclips, but I think that would be impossible without the display list, so I could settle with writing my own animation system with spritesheets.
Rewriting the entire event system isn't something I look forward to though.
Are there any (molehill) frameworks that work without the display list?
You can do something similar by creating a Bitmap with the same size as the stage, attaching it to the stage as a child and using it like a "screen", by blitting your graphics on it every frame (on ENTER_FRAME event). I think it's even mentioned somewhere in the official Adobe documentation, as a method of efficiently animating a large number of objects.
I would advise you to muster up the courage and let go of C# when programming in ActionScript. As Bjarne Stroustrup wisely said in his book The C++ Programming Language:
...applying techniques effective in one language to another typically
leads to awkward, poorly performing, and hard-to-maintain code. Such
code is also most frustrating to write because every line of code and
every compiler error message reminds the programmer that the language
used differs from 'the old language.' You can write in the style of
[another language], but doing so is neither pleasant nor economical in a language
with a different philosophy.
I think that applies very well to the question you're asking here.

Avoiding Global State

Currently I'm writing an app. If I want to avoid Singletons, do I have to simply pass references of everything around?
For example,
I have a "main" class.
Class: Main
+---- Screen
+---- Camera
+---- Terrain
+---- Vehicle
+---- PhysicsWorld
It contains my Camera, Terrain, and Vehicle,etc classes. Now, I have issues when I'm creating say, the Terrain object. Terrain wants to access Main classes Screen object so it can add its Terrain Graphics to the screen. It also wants to know about the Camera object for when it is drawing so it knows what scale to draw it. It also wants to know about my PhysicsWorld object so it can add itself to the physics engine.
Do I have to always lug these objects back and forth between constructors? I mean, when I create a Terrain object, do I simply have to pass around my screen object, my physicsWorld, camera, etc?
Another random scenario I have, is now.. inside my Vehicle class I need to call a Restart() method on my Main class. Does this mean I have to pass an instance of main to Vehicle? Really??
It feels cumbersome to constantly have to pass 4-5 things to my classes, especially in my scenario now where almost every in-game object I have needs a screen, physics, camera info, etc.
Any suggestions?
It feels cumbersome to constantly have
to pass 4-5 things to my classes,
especially in my scenario now where
almost every in-game object I have
needs a screen, physics, camera info,
etc.
Then the correct question to ask is "why do I need all 5 objects in all my classes?"
Why on Earth does every in-gmae object need any of the mentioned things? An in-game object needs a position and whatever it needs to process its behavior. Then a separate renderer can, you know, render, the object. Which means that only the renderer needs the camera info and screen.
The physics could go either way. You could have a separate physics entity which updates the game object, or you could pass that physics object to every game object. But even if you do pass that around, we're down to one out of the three objects listed. :)
That's why globals and singletons are often best avoided. They disguise your dependencies so you end up with far more dependencies between your objects than you actually need. And then it becomes almost impossible to remove the globals.
However, if you do stick with globals, do yourself a favor, and at least avoid singletons. You don't need the additional constraints enforced by a singleton.
Terrain wants to access Main classes
Screen object so it can add its
Terrain Graphics to the screen. It
also wants to know about the Camera
object for when it is drawing so it
knows what scale to draw it. It also
wants to know about my PhysicsWorld
object so it can add itself to the
physics engine.
The terrain object needs to know one thing: What is the terrain like. Someone else can take responsibility for rendering it. That someone will need to know about the camera, screen and terrain graphics, sure, which suggests that the same object might plausibly be able to do other tasks involving these objects (such as other rendering tasks).
Why should the terrain care about what scale it's drawn in? It needs to know the scale ingame, but not the scale in camera-space. And why can't someone else add the terrain to the physics engine? The main function might be able to do that, even. Create terrain, create physics engine, register terrain with physics engine, start game.
I don't know ActionScript, but assuming variables are passed by reference, the least you could do is construct a 'Environment' class holding Camera, Screen, Terrain, PhysicsWorld which you pass to the instances.
I have the exact same problem (also in actionscript 3, coincidentally).
I have been working on an RTS for flash and had found myself needing to pass around large numbers of references to each new class (e.g., gameGrid, currentSelection, visibleUnits, etc.).
I eventually realised that what I really should be doing is to have every class maintain it's own properties, and instead pass around references to these classes, (well objects).
But anyway, now what I'm doing is having static variables containing references to commonly used objects such as the main stage, interface, engine and display area inside a class called RTSGlobals. I'm also putting constants such as the screen size in there.
I know this doesn't really answer your question, but I figure sometimes it is worth ignoring a bit of OOP good practice in favour of an efficient solution.
If someone has a does have a good practice solution though, please tell :)
I suggest you take a look at XNA's samples projects (google it). They're well designed and might give you some hints.
Also, since you're using AS3, you could use the event system to dispatch message to other entities. For example, instead of passing your Main to your Vehicle class, make your Main (or whatever else interested) a listener of your Vehicle class. Then, let's say the car crash and you want to restart the game, dispatch an event, for example CAR_CRASHED. The listeners of your car should do something based on this message. If you want to understand the event system, type EventDispatcher, highlight it and hit F1 in your Flash IDE.