It just occurred to me that I don't know what base.Update(gameTime) is supposed to do in the end of each XNA game project's protected override void Update(GameTime gameTime) method.
I tried removing it and nothing broke. My guess is it may be used to update GameService stuff, which I don't use anyway. But what's it really for? Can removing it save some resources?
There is also base.Draw(gameTime) in the end of protected override void Draw(GameTime gameTime). I wonder if these two are used for when the Game class inherits another Game class.
They are used for when you register a GameComponent.
A registered component will have its draw, update, and initialize methods called from the Game.Initialize, Game.Update, and Game.Draw methods.
Related
In the bad old days in my codebase we relied quite heavily on event requeuing, which I suspect worked due to implementation details in ICEfaces or MyFaces rather than standard-specified behavior. One thing we used to do frequently was this kind of thing:
<ice:inputText value="#{bb.frequency}" valueChangeListener="#{bb.valueChanged}"/>
The goal is to arrange for retune to be called after setFrequency whenever the frequency changes.
Then we had some fairly disgusting code in the backing bean which would requeue the event. It usually looked something like this:
class BB {
// this happens first, thanks to UPDATE_MODEL_VALUES
public void setFrequency(Frequency f) {
this.model.f = f;
}
public void valueChanged(ValueChangeEvent event) {
if (event.getOldValue().equals(event.getNewValue())
return; // nothing changed, so leave
if (FacesContext.getCurrentInstance().getPhaseId() != INVOKE_APPLICATION) {
OurMagicEventUtils.requeueEvent(event, INVOKE_APPLICATION);
}
else {
// do the post-setter work here (the setter happened recently during
// UPDATE_MODEL_VALUES so we're up-to-date by here
this.model.retune();
}
}
}
This isn't a good way to live. I haven't found a reliable way to requeue events for later phases and it clearly isn't the kind of thing people do. I see two solutions:
Move the retune intelligence to the BB#setFrequency method.
I can't get away with this in many cases because I'm directly addressing a lower-level model class and I don't want to disturb its behavior for other clients.
Create a custom component and move the logic into the setFoo method there.
I don't love this because there are a lot of issues with Mojarra and custom components when embedded in other containers. It also seems like overkill for what I need to do—I literally just need to call retune after setting some properties.
Create backing beans for everything. Delegate most methods directly to the inner thing, but catch setFoo and perform the retune there. This is very similar to what we used to do, and it means a lot of boilerplate, wrappers, and glue code, so I don't love it.
In my mind I imagine something like this:
<ice:inputText value="#{bb.frequency}" afterChange=#{bb.retune}"/>
but that obviously doesn't work, nor would attaching an <f:actionListener> since that requires a class name but has no association to whatever you're currently doing, and besides it can only be set on UICommands which UIInputs are not.
What's the elegant/correct way to solve this dilemma?
As you're using JSF2 already, just use <f:ajax>.
<ice:inputText value="#{bb.frequency}">
<f:ajax listener="#{bb.retune}"/>
</ice:inputText>
with
public void retune(AjaxBehaviorEvent event) { // Note: the argument is optional.
// ...
}
This will be invoked during invoke action phase when the HTML DOM change event has occured.
I am developing an XNA game. This is time I am careful about the architecture. Til today, I have always implemented my own draw method in this way:
public void Draw(SpriteBatch sb, GameTime gameTime)
{
sb.Begin();
// ... to draw ...
sb.End();
}
I was digging the DrawableGameComponent and saw the Draw method comes in this way:
public void Draw(GameTime gameTime)
{
// ...
}
First of all, I know that SpriteBatch can collect many Texture2D between Begin and End, so that it can be useful to sort them, or draw with same Effects.
My question is about the performance and the cost of passing the SpriteBatch. At DrawableGameComponent it is possible to call spritebatch of game object if its spritebatch is public.
What is suggested, what should a xna-game programmer do?
Thanks in advice.
One of the serious disadvantages of DrawableGameComponent is that you're locked into its provided method signature. While there's nothing "wrong", per se, with DrawableGameComponent, do not think of it as the "one true architecture". You're better off thinking of it as an example of a possible architecture.
If you find yourself needing to pass a SpriteBatch (or anything else) to the draw method of a "game component" - the best way is to pass it as an argument. Anything else is convoluted.
Obviously this means that you can't use XNA's provided GameComponent system, and you have to make your own alternative. But this is almost trivial: At its most basic level, it's just a list of some base type that has appropriate virtual methods.
Of course, if you must use GameComponent - or your game is so simple (eg: a prototype) that you don't really care about the architecture - then you can use basically any method you like to get a SpriteBatch to your draw method. They all have disadvantages.
Probably the next-most architecturally robust method is to pass your SpriteBatch instance into the constructor of each of your components. This keeps your components decoupled from your game class.
On the other hand, if you're throwing architecture to the wind, I'd suggest making your MyGame.spriteBatch field public static. This is the simplest way to allow it to be accessed anywhere. It's easy to implement and easy to clean up later when/if you need to.
To answer your question about performance: Anything to do with passing a SpriteBatch around will have almost negligible effect on performance (providing the order of calls to Draw/Begin/End stays the same). Don't worry about it.
(If you see SpriteBatch whatever in code, that represents a reference. A reference is a 32-bit value (in a 32-bit program, which all XNA games are). That's the same size as an int or a float. It's very small and very cheap to pass around/access/etc.)
If you stumbled upon this question you were probably looking at a nice and generic solution. I would suggest you have a look at this:
https://gamedev.stackexchange.com/questions/14217/several-classes-need-to-access-the-same-data-where-should-the-data-be-declared/14232#14232
I felt the need to correct this question because "the best way is to pass it as an argument. Anything else is convoluted." is simply not correct.
Personally i am now doing it this way in my GameBase class:
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
SpriteBatch = new SpriteBatch(GraphicsDevice);
this.Services.AddService(typeof(SpriteBatch), SpriteBatch);
}
Now, since you're adding DrawableGameComponents in the Initialize Method of your Game class you will be able to call
this.Game.Services.GetService(typeof(SpriteBatch))
I'd say that's the cleanest approach to solve the problem.
If the DrawableGameComponent should be part of the parent's SpriteBatch, then just pass it in via the constructor and store it in a private member (or expose it as a property if you wish).
You could also expose the SpriteBatch as a property of your Game class if you wanted, like you suggested, but every time you referenced this.Game, you would need to cast it to your specific Game class type.
((MyGame)this.Game).SpriteBatch.Draw(...)
Or you can just have the DrawableGameComponent create a new SpriteBatch. There's nothing wrong with that (as far as I've ever seen). I suppose it depends how many DrawableGameComponents you'll be creating and how often.
Also browse through the results for a search for DrawableGameComponent - there's a lot of good advice there.
Trying to integrate Ninject with XNA however I am having a bit of pain trying to get it all hooked up.
The problem is I am trying to do it as I think it should done, so I am decoupling things as much as possible to make it more modular, and Xna isn't happy with me doing this... an example of this is where the Game object news up a lot of things internally, and a lot of those things could do with being passed around to my objects. So I decided to add these as constructor arguments to the Game class, so I can setup all the dependencies then use Ninject to give me the Game instance with all its dependencies resolved.
Unfortunately In this example normally XNA doesn't new up its SpriteBatch until it has gotten to the Initilize stage, which I assume is because it needs the GraphicsDeviceManager to get the window handle to create the GraphicsDevice before it can be exposed for anything to use...
So because of this they cannot be injected into the game because it needs to do its stuff first, and I cannot really push them in after the game is made, because I need other things like the World component to be injected with things as well and pushed into the game.
At this point I thought maybe I could create my own GraphicsDevice, but as I need the handle I would need to make my own window too, which I later realised XNA would dispose and recreate anyway. So it leaves me with a horrible taste in my mouth... as I dont fancy re-writing the Game and GraphicsDeviceManager classes, which would require me to re-write lots of other functionality as they are all internal to the XNA assembly...
So has anyone managed to setup their dependency injection without having to re-write large chunks of XNA?
Here is an example of my current module:
public class XnaModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IServiceProvider>().To<NinjectServiceProvider>().InSingletonScope();
Kernel.Bind<IGraphicsDeviceService>().To<GraphicsDeviceManager>().InSingletonScope();
Kernel.Bind<ContentManager>().ToSelf().InSingletonScope();
Kernel.Bind<SpriteBatch>().ToSelf().InSingletonScope();
var contentManager = new ContentManager(Kernel.Get<IServiceProvider>());
contentManager.RootDirectory = "Content";
Kernel.Bind<ContentManager>().ToConstant(contentManager).InSingletonScope();
var game = new MyGame(Kernel.Get<IGraphicsDeviceService>() as GraphicsDeviceManager,
Kernel.Get<SpriteBatch>(), contentManager);
Kernel.Bind<Game>().ToConstant(game).InSingletonScope();
}
}
Then the game constructor:
public class MyGame : Game
{
public SpriteBatch SpriteBatch { get; private set; }
public GraphicsDeviceManager Graphics { get; private set; }
public MyGame(GraphicsDeviceManager graphics, SpriteBatch spriteBatch, ContentManager contentManager)
{
Graphics = graphics;
SpriteBatch = spriteBatch;
Content = contentManager;
}
// Other stuffs
}
Both are just examples so you can see the sort of approach I am taking, the module bypasses the circular dependency issue as I new the game up myself. And I have excluded the GameModule, which would contain the dependencies for my actual Game objects, i.e factories, gui components etc, and the problem is they ultimately need to be injected into the Game too, and we then we have a catch22.
As they cannot be injected until the dependencies are resolved, but you cannot resolve the dependencies until you have started the game... it seems a lose/lose situation. So can anyone tell me how they got round this issue?
I did find http://steveproxna01di.codeplex.com/ but was looking if there are any more examples as this is more of a service locator approach, rather than an Injection approach.
As no one has answered this, I will put in that I basically turned my Game instance into a wrapper and bootstrapper for a custom IGame instance which is the root injection point. This way I am able to inject whatever I want.
Android requires that all Activity sub-classes invoke super methods from their lifecycle methods. An exception is thrown if the super method is not invoked. Why does Android use a RuntimeException mechanism to force super methods to be called. Why does it not use the 'Template' design pattern so that super methods get executed automatically before the child methods. For example onDestroy() can be handled as follows :-
Class Activity{
public void onDestroyFrmwork()
{
//do whatever the super onDestroy() method has to do
onDestroy();//this will invoke the subclass method.
}
public void onDestroy()
{
//empty. will get overridden by subclasses.
}
}
I know I am answering this question 11 months after it was asked. I guess the reason is that the order of calling the super method cannot be determined in advance. For example, I might want to do my clean up before calling super.onDestroy(), after super.onDestroy() or even mix it up like follows:
#Override
protected void onDestroy() {
// Do some initial clean-up
preDestroy();
//Then call super
super.onDestroy();
//In the end do some final clean-up
postDestroy();
}
This example is for the sake of argument; but I'm sure you would come across real world examples if you look hard enough.
This kind of mixed ordering would be hard to achieve using Template design pattern.
Your application won't work correctly if you don't call the superclass methods, so the API throws a RuntimeException to make sure you don't forget to do so.
Everytime I ask anyone what the Spring Framework is or what it does, they simply say to me, you remember that Hollywood principle right "Don't call me, I will call you", that's exactly what Spring Framework does.
What should I make out of this?
It means that a class doesn't manually instantiate the components that it depends on -- something (such as Spring's IoC context) gives the class an instance of each component that it needs. This is usually done either via setters for each component, or a constructor that takes all those components.
Basically instead of a class doing manual instantiation by itself:
public class Foo {
private Bar bar;
public void doStuff() {
bar = new BarImplementation();
bar.doMoreStuff();
}
}
IoC injects the dependency Bar into Foo, so that when you get a Foo object from the context, you know it's ready to use.
public class Foo {
private Bar bar;
public void setBar(Bar bar) { this.bar = bar; }
public void doStuff() {
// bar's already been set by the time this is called!
bar.doMoreStuff();
}
}
You didn't manually instantiate Bar, instead your configuration files (such as Spring XML) set it for you. Additionally, Foo is no longer tied to BarImplementation. Using interfaces allows you to insert different implementations, including mocks used for testing.
Sometimes callback models are more efficient, especially with anything to do with parsing
if you imagine the hollywood situation, its way more efficient for the "casting agent" to call everyone once they know who they are going to cast (or even not call) rather than having to keep taking calls from every applicant wanting an update.
Callbacks. :P That's what that means for me. Callbacks are functions that wait to be called.
See http://en.wikipedia.org/wiki/Inversion_of_Control
Spring does other things too but IoC/Dependency injection seems to be the most noted feature. It can help to make a system less coupled and more flexible.