I haven't programmed games for about 10 years (My last experience was DJGPP + Allegro), but I thought I'd check out XNA over the weekend to see how it was shaping up.
I am fairly impressed, however as I continue to piece together a game engine, I have a (probably) basic question.
How much should you rely on C#'s Delegates and Events to drive the game? As an application programmer, I use delegates and events heavily, but I don't know if there is a significant overhead to doing so.
In my game engine, I have designed a "chase cam" of sorts, that can be attached to an object and then recalculates its position relative to the object. When the object moves, there are two ways to update the chase cam.
Have an "UpdateCameras()" method in the main game loop.
Use an event handler, and have the chase cam subscribe to object.OnMoved.
I'm using the latter, because it allows me to chain events together and nicely automate large parts of the engine. Suddenly, what would be huge and complex get dropped down to a handful of 3-5 line event handlers...Its a beauty.
However, if event handlers firing every nanosecond turn out to be a major slowdown, I'll remove it and go with the loop approach.
Ideas?
If you were to think of an event as a subscriber list, in your code all you are doing is registering a subscriber. The number of instructions needed to achieve that is likely to be minimal at the CLR level.
If you want your code to be generic or dynamic, then you're need to check if something is subscribed prior to calling an event. The event/delegate mechanism of C# and .NET provides this to you at very little cost (in terms of CPU).
If you're really concerned about every clock cycle, you'd never write generic/dynamic game logic. It's a trade off between maintainable/configurable code and outright speed.
Written well, I'd favour events/delegates until I could prove it is an issue.
The only way you'll truly know if it is an issue for you is by profiling your code -- which you should do anyway for any game development!
It's important to realize that events in C# are not queued asynchronous events (like, for example the Windows message queue). They are essentially a list of function pointers. So raising an event doesn't have worse performance implications than iterating through a list of function pointers and calling each one.
At the same time, realize that because of this, events are synchronous. If your event listener is slow, you'll slow down the class raising the events.
The main question here seems to be:
"What is the overhead associated with using C# Delegates and Events?"
Events have little significant overhead in comparison to a regular function call.
The use of Delegates can create implicit and thus hidden garbage. Garbage can be a major cause performance problems especially on the XBox360.
The following code generates around 2000 bytes of garbage per second (at 60 fps) in the form of EntityVisitor objects:
private delegate void SpacialItemVisitor(ISpacialItem item);
protected override void Update(GameTime gameTime)
{
m_quadTree.Visit(ref explosionCircle, ApplyExplosionEffects);
}
private void ApplyExplosionEffects(ISpacialItem item)
{
}
As long as you avoid generating garbage, delegates are fast enough for most purposes. Because of the hidden dangers, I prefer to avoid them and use interfaces instead.
In my extra time away from real work, I've been learning XNA too.
IMHO (or not so humble if you ask my coworkers) is that the overhead of the event handles will be overwhelmed by other elements in the game such as rendering. Given the heavy use of events in normal .Net programming I would be the underlying code is well optimized.
To be honest, I think going to an UpdateCameras method might be a premature optimization. The event system probably has more uses other than the camera.
XNA encourages the use of interfaces, events and delegates to drive something written with it. Take a look at the GameComponent related classes which set this up for you.
The answer is, "As much as you feel comfortable with".
To elaborate a little bit, If for example you take and inherit from the gamecomponent class into a cameracontroller class and add it to the Game.Component collection. Then you can create your camera classes and add them to your cameracontroller.
Doing this will cause the cameracontroller to be called regularly and be able to select and activate the proper camera or multiple cameras if that is what you are going for.
Here is an example of this (All of his tutorials are excellent):
ReoCode
As an aside, you might be interested to know that Shawn Hargreaves, original developer of Allegro, is one of the main developers on the XNA team :-)
Before going into what is the impact of an event in terms of performance you must first evaluate whether or not it is needed.
Assuming you are really trying to keep a chase cam updated and its not just an example, what you are looking for is not an event (though events might do the trick just as well), if you are following an avatar likelihood is it will be moving most of the time.
One approach I found extremely effective is to use hierarchic transformations, if you implement this efficiently the camera won't be the only object to benefit from such a system, the goal would be to keep the camera within the coordinate space of the object it is tracking.
That approach is not the best one if you want to apply some elasticity to the speed and ways in which the camera tracks the object, for that, it is best to use an update call, a reference, and some basic acceleration and resistance physics.
Events are more useful for things that only happen from time to time or that affect many different aspects of the application, like a character dying, probably many different systems would like to be aware of such an event, kill statistics, the controlling AI, and so on, in such a case, keeping track of all the objects that would be have to constantly check if this has happened is far less effective than throwing an event and having all the interested objects be notified only when it happens.
Related
Sometimes I see how Unity programmers use one script that inherits MonoBehavior for almost the entire project. The so-called "Update Managers". All scripts are subscribed to the queue for execution, and the manager runs all functions, and after execution removes them from the queue.
Does this really have any effect on optimization?
This was one of the optimization technique I analyzed in my thesis.
The Unity engine has a Messaging system which allows the developers to define methods that will be called by an internal system based on their functionalities. One of the most commonly used Messages is the Update message. Unity is inspecting every MonoBehaviour the first time the type is accessed (independently from the scripting backend (mono, il2cpp)) and checks if any of the Message methods are defined. If a Message method is defined then the engine will cache this information. Then if an instance of this type is instantiated then the engine will add it to the appropriate list and will call the method whenever it should. This is also the key reason why Unity does not care about the visibility of our Message method, and that they are not called in a deterministic order.
public class Example1 : MonoBehaviour
{
private void Update() { }
}
public class Example2: MonoBehaviour
{
public void Update() { }
}
Both of the above achieves the same results but god knows which will be called first.
One of the main problem with this approach is that every time the engine calls a Message method an interop call (a call from c/c++ side to the managed c# side) has to happen. In case of Update luckily no marshaling is needed so this overhead is a bit smaller. However, if our game handles thousand or tens of thousands of objects which all have a script requiring a Message call then this overhead can be significant. A solution to this is to avoid interop calls. A good approach to this is behavior grouping. If we have a MonoBehaviour that is attached to a huge number of GameObjects we can cut the number of interop calls to just one by introducing an update manager. Since the update manager is also a managed object running managed code the only interop call will happen between the update manager’s Update Message and the Unity engine’s internal Message handler. We have to note the fact that this optimization technique is only relevant in large scale projects, and the frame time saved via this technique is more impactful when using the Mono scripting backend. (Remember IL2CPP transpiles to C++).
The above picture illustrates the difference between the two methods.
Let's do a benchmark with Unity's performance tools. The benchmark will spawn 10 000 gameobjects each with a mover script which moves these cubes up and down.
Illustration of the example scene using the traditional method.
Now let's see the results of the bechmarks.
Not surprisingly IL2CPP leading the competition by far however it’s still interesting that the Update Manager is still twice as fast as the traditional way. If we profiled the execution of the Traditional method’s IL2CPP build we would find many Unity specific calls like check if the GameObject exists before invoking a component method etc. and these would explain the longer execution time. We can also make the conclusion that IL2CPP in this case is far faster than Mono, usually around twice as fast. The benchmark ran for one minute prior to a 5 seconds warmup and both scripting backends had the ideal compiler setting.
Based on this article which your link has a link to, having an "update manager" does indeed have a positive impact on performance when compared to using Unity's Update method. The gist is that if you implement Update in one of your classes, Unity has some additional overhead in calling Update; it doesn't run quite as fast as calling a method yourself, such as saying myObject.Update(). So if you're calling Unity's Update on 10,000 game objects per frame, that additional overhead becomes noticeable.
If you explicitly call your update-type methods from a "manager" class -- rather than letting Unity call the "magic" Update methods -- then you can avoid the additional overhead that comes with using "magic" methods.
But keep in mind that the performance penalty of using Update will only be noticeable if you have a lot of game objects in your scene that all implement Update. Game objects in your scene that don't implement Update won't have an effect. It would be good practice to remove the Update method that Unity adds to all new scripts if you're not using it though.
In short, unless you have a huge number of objects in your scene and you are running into performance problems, I wouldn't worry about it.
I'm writing a Mafia (Werewolf)-style game engine in C#. Writing out the logic of an extended mafia game, the model:
A Player (Actor) has one or more Roles, and a Role contains one or more Abilities. Abilities can be Static, Triggered, or Activated (similar to Magic the Gathering) and have an "MAction" with 0 or more targets (in which order can be important) along with other modifiers. Some occur earlier in the Night phase than others, which is represented by a Priority.
MActions are resolved by placing them in a priority queue and resolving the top one, firing its associated event (which can place more actions on the queue, mostly due to Triggered Abilities) and then actually executing a function.
The problem I see with this approach is that there's no way for an MAction to be Cancelled through its event in this mechanism, and I see no clear way to solve it. How should I implement a system so that either MActions can be cancelled or that responses with higher Priorities end up executing first/delaying the initial MAction?
Thanks in advance. I've spent quite some time thinking (and diagramming) this through, can't quite get over this hurdle.
Would it be possible to implement a cancellation stack that is checked by each MAction function and only executes if the MAction you are trying to execute is not in that stack. That way any time an action is popped it would only do something if it wasn't canceled already.
The situation as I understand it:
You have a series of things that happen with complicated rules which decide the order of what happens, and the order of what happens decides the quality/magnitude of the effect.
First things first, in order to make your life easier I'd recommend you limit your players to making all their moves before action resolution takes place. Even if this model is abandoned later it should make it easier for you to debug and resolve the actions. This is especially true if later actions can undo the effects of earlier actions like in the following example:
Dave transforms to a werewolf because he triggers the Full Moon ability. Then with werewolf powers he jumps over a wall and bites Buffy. Before Buffy dies she activates her time reverse ability and kills Dave before he jumps over the wall.
Regardless, your dilemma makes me think that you need to use a rules engine like NRules1, or implement your own. The primary goal of the rules engine will be to order/discard the stuff that happens according to your business logic.
Next you put these actions into a queue/list. The actions are applied against the targets until the business rules tell you to stop (Werewolf Dave died) or there aren't any more actions to apply. Once you stop then the results of the battle/actions are reported to the user.
There are other ways to accomplish your goals but I think this will give you a viable pathway towards your end goal.
1: I've never used this library so I don't know if it is any good.
I'm currently re-drawing polygons in my application each time the polygon is moved somewhere within the PreviewTouchMove method (from WPF). It is proving to be quite repetitive in terms of computational power. So I 'm thinking to just re-draw the polygon whenever it comes to a stop somewhere (that way I won't have to continuously draw it while it's moving).
I want to detect when an object starts moving (by touch) and comes to a stop. There seem to be no built-in methods for this type of calculation (there's just PreviewTouchUp and PreviewTouchDown which aren't related in this case).
Any tips regarding how I can implement my own methods to check for this would be much appreciated. Thank you.
I'm writing an application for a touch table using WPF and C#. (And, I'm not terribly familiar with WPF. At all.) We suspect we're not getting the framerate we're "requesting" from the API so I'm trying to write my own FPS calculator. I'm aware of the math to calculate it based on the internal clock, I just don't know how to access a timer within the Windows/WPF API.
What library/commands do I need to get access to a timer?
Although you could use a DispatcherTimer (which marshalls its ticks onto the ui thread, causing relativity problems), or a System.Threading.Timer (which might throw an exception if you try to touch any UI controls), i'd recommend you just use the WPF profiling tools :)
I think you're looking for the StopWatch. Just initialize it and reset it with each start of your iteration. At the end of an iteration, do your calculation.
First of all, are you aware that Microsoft provides a free diagnostic tool that will tell you the frame rate at which WPF is updating the screen? I guess if you're not convinced you're getting the framerate you're asking for, then perhaps you might not trust it, but I've found it to be a reliable tool. It's called Perforator, and it's part of the WPF Performance Suite, which you can get by following the instructions here: http://msdn.microsoft.com/library/aa969767
That's probably simpler than writing your own.
Also, how exactly are you "requesting" a frame rate? What API are you using? Are you using the Timeline's DesiredFrameRate property? If so, this is more commonly used to reduce the frame rate than increase it. (The docs also talk about increasing the frame rate to avoid tearing, but that doesn't really make sense - tearing is caused by presenting frames out of sync with the monitor, and isn't an artifact of slow frame rates. In any case, on Vista or Windows 7, you won't get tearing with the DWM enabled.) It's only a hint, and WPF does not promise to match the suggested frame rate.
As for the measurement technique, there are a number of ways you could go. If you're just trying to work out whether the frame rate is in the right ballpark, you could just increment a counter once per frame (which you'd typically do in an event handler for CompositionTarget.Rendering), and set up a DispatcherTimer to fire once a second, and have it show the value in the UI, and then reset the counter. It'll be somewhat rough and ready as DispatcherTimer isn't totally accurate, but it'll show you whether you've got 15fps when you were expecting 30fps, for example.
If you're trying to get a more precise view (e.g., you want to try to work out whether frames are being rendered constantly, or if you seem to be getting lost frames from time to time), then that gets a bit more complex. But I'll wait to see if Perforator does the trick for you before making more suggestions.
You want to either wrap the win32 timing calls you'd normally call (such as QueryPerformanceCounter), by using p/Invoke, or use something in .NET that already wraps them.
You could use DateTime.Ticks, but it's probably not high enough resolution. The Stopwatch class uses QueryPerformanceCounter under the covers.
If you want something that's reusable on a lot of systems, rather than a simple diagnostic, be warned about processor related issues w/ QPC and Stopwatch. See this question: Can the .NET Stopwatch class be THIS terrible?
My question is how programmers create, code, and organize subforms in general. By subforms, I mean those groups of controls that make up one UI experience. I'm looking for hints to help me better organize my form codes and to speed up the process of creating such forms. I swear to God, it takes way too long.
I've identified three broad groups of subform elements:
-Subforms have commands to do something.
-Subforms have data elements to carry out those commands.
-Subforms have states used to track things that aren't data.
The approach I use is to focus on what it takes to perform the commands which will determine which data elements are needed and how they should be validated.
Also, do programmers use check lists when creating forms?
p.s. I program as a hobby.
This is incredibly fuzzy. There is however a red flag though, you seem to be talking about UI as a starting point instead of the end result. That's a classic trap in winforms, the designer is rather good and makes it way too easy to endlessly tinker with form layouts. You forever keep adding and removing controls and event handlers as your ideas about how the program is supposed to work evolve.
This is backward and indeed a huge time sink. Effective design demands that you grab a piece of paper and focus on the structure of the program instead. The starting point is the model, the M in the MVC pattern. As you flesh out how the model should behave, it becomes obvious what kind of UI elements are necessary. And what commands should be available to the user.
The V emerges. Instead of jumping into the designer, sketch out what the view should look like. On paper. Make a rough draft of an organized way to present the data. And what operations are available to the user to alter them. Which selects the type of controls and the menus and buttons you'll need. Once that congeals, you can very quickly design the form and add the C. The event handlers that tie the UI to the model.
There's a very interesting tool available from Microsoft that helps you to avoid falling into this trap. I love the idea of it, it intentionally makes the UI design step imperfect. So you don't spend all that time pushing pixels around instead of focusing on the design of your program. It draws UI designs in a paper-and-pencil fashion, there are no straight lines. Incredibly effective not just for the programmer, also a "keep the customer focused and involved" fashion. So that the customer doesn't fall in the same trap either, nagging about a control being off by one pixel. It is called SketchFlow, link is here. It is otherwise the exact same analogue of paper and pencil, but with a 'runs on my machine' flourish.
Try CAB I'm not sure you should use it, but the pattern will help you understand how to write your gui layer in a good way.