Friday, September 4, 2009
It took a few months of part time effort to port SV5 to Silverlight, and now we have SV6. There are some decided advantages to the browser based version:
1) You don't need to to download the latest build, that's taken care of automatically.
2) The graphics performance of the Silverlight sprites outperforms the GDI+ based graphics of SV5.
A Silverlight version also poses some challenges that I still need to overcome. Biggest of these is providing a way for people to run a debug version of the app so they can develop and debug their Scenarios and Brains. Once I crack this I will publish the updated Scenario and Brain API's and promote these to developers.
One of the hallmarks of Silicon Commander Games was the extensibility, and I think we've pushed the envelope by providing robust API's so developers can build their own Scenarios (levels) and Brains (computer AI's) that integrate seamlessly into the game. This will continue with SV6!
Another challenge is to try and rebuild the SCG community and get some active players again. I'm hoping this will come naturally when I continue to build up the supporting documentation of the game with strategy guides, examples, etc. If you're reading this now you can help too by logging in and waiting a little bit in the lobby for other people to show up! I look at the logs and see someone like "Z" for example log in, and then 1 minute later log out. Then 5 minutes later someone else does the same thing. I'm guilty of this too some time, but I will try and hang out in the lobby more to catch other players and hopefully get some games logged!!
I've also begun work on converting some of the class libraries for WinWar II over to Silverlight. This includes my tile-based map logical components, and a new Silverlight based TileBasedGameBoard component that can use my MapSet class to render tiles on the map. I'm hoping to port the WinWarII logic engine I created for V5 pretty easily to Silverlight, then build a new UI, much like I did for SV6.
Monday, July 13, 2009
EasyGrid is a simple enhancement to the basic Grid layout panel in WPF/Silverlight. The sole purpose of EasyGrid is to eliminate the verbose markup that clutters your XAML when you define Grids with many rows and columns.
EasyGrid provides a "mini-language" that lets you create all of the rows and columns of the grid by simply providing a value to the EasyGrid's Data property.
Before getting into the mini-language specifics, lets look at an example. Say we want to define a Grid that contains 4 columns, the first and last a fixed width, and the middle two variable, and 12 rows. You would wind up with markup something like this:
If you're anything like me, looking at markup like this gives you a headache! The EasyGrid version looks like this:
The EasyGrid Mini-Language
The EasyGrid performs its magic via the Data property, which contains a string that represents all of the rows and columns of the grid. The Data property actually has two modes of operation, a simple mode and a verbose(?!?) mode.
In the simple mode, you can create a grid with a number of rows and columns that all have the "*" sizing specifier by using this syntax:
where C represents the number of desired columns and R represents the number of desired rows.
In this mode, you use tokens to specify rows and columns. You can also use the "x" character to represent a number of rows or columns with the same sizing specification.
C - A "C" in the Data string means that the next token(s) will define grid columns.
R - A "R" in the Data string means that the next token(s) will define grid rows.
# - A number token (for example "12" defines a row or column with a fixed size.
#* - A number followed by a * (for example 4*) defines a row or column with a proportional size.
Auto - The "Auto" token defines a row or column with an automatic size.
#x(token) - When there is a #x preceding a token, it means that the row or column will be repeated the specified number of times. For example, C 5x3* creates 5 columns with sizing of 3*.
That's all there is to the EasyGrid. Use it in your projects and "say no to verbose XAML!".
Monday, July 6, 2009
I completed the multiplayer lobby interface for Solar Vengeance 6 in Silverlight. Click the link below to log into the new lobby. You can set your profile, including a Glyph image, and chat with other users in the lobby.
Implementing the lobby in the app was easy once my PrismServer components were ported to Silverlight. The PrismConnection component provides an easy way to connect a Silverlight app to a running PrismServer.
In SV6 I create the PrismConnection component in code, but you could also create it in your XAML since it descends from DependencyObject. You'd just need to be sure to place it within a ContentControl, because Silverlight panels can't take DependencyObjects directly. When defined in XAML, you can set the properties like Host, Port, and SubjectName in your XAML, as well as hook up event handlers.
In my custom application class I declare a private variable to hold the PrismConnection object, and a public property to provide access to it in other pages. In Application StartUp event, I create the instance:
_prism = new PrismConnection("184.108.40.206", 4502, false);
_prism.SubjectName = "SV6";
You'd replace "220.127.116.11" with the host name or IP address where your PrismServer is running.
To connect, call the Connect method, which will eventually fire either the ConnectSuccessful or ConnectFailed events.
In your ConnectSuccessful event handler you can call either Login (for existing users) or LoginNew (for new users). Login takes 2 parameters, a user name and a password. LoginNew takes 1 parameter, an instance of a PrismUser object that represents the user information for the new user.
These methods will eventually fire either the LoginOK or the LoginFailed events, which you can handle accordingly.
The PrismUser class has some helper methods that make it easy to store and retrieve Glyph images for users. The SV6 Lobby lets you select a local image file on your computer to represent you as your Glyph. PrismUser encodes this image into a Base64 string, and saves it in the PrismUser object, in one of the "Detail" fields. PrismUser GetDetail/SetDetail methods let you store arbitrary information with a PrismUser and have it saved on the server.
When a user logs back in, its encoded Glyph string is decoded and converted back into an ImageSource which is then displayed next to them in the Lobby.
I use the PrismUser GetDetail/SetDetail to store other game-specific information about a user, such as their rank and rating.
Handling chat in the Lobby is virtually effortless thanks to PrismConnection doing all of the dirty work. To send a line of chat to other users, simply call the SendChat method. A ChatRecieved event is triggered when an incoming chat message is received. The EventArgs class provides you the PrismUser who sent the chat as well as the line of text itself.
Now that the Lobby is completed I can move onto converting the actual game mechanics!
Solar Vengeance 6 Development Build - with Lobby!
Monday, June 29, 2009
ChatNDraw was created using my PrismServer component suite that I just converted to WPF/Silverlight from WinForms (.NET 2.0). I plan to release the source for PrismServer as soon as I can complete the documentation.
Friday, June 26, 2009
Note - if you create an account here, it will become the eventual account you'll use for all SCG Silverlight games.
I wanted to get this news out to allow for some early testing. I do plan on creating a post describing the new PrismServer in more detail, and possibly a revised CodeProject article. For now, my fingers are falling off of my hands so I need a break from coding ;)
Tuesday, June 23, 2009
Earlier I began porting my object-oriented TurboSprite framework to WPF. This was relatively easy because WPF had the OnRender event and the DrawingContext that corresponds to WinForms Paint/Graphics combo.
When I decided to target Silverlight as the next platform for Silicon Commander Games development, one of the first hurdles was the fact that it did not expose the OnRender/DrawingContext feature of WPF. This forced me to use the animation system(s) built into Silverlight/WPF and abandon further development of TurboSprite.
One of the benefits of encapsulating animation in TurboSprite was its clean, object-oriented design. I could create animatable sprite classes that were self-contained and re-usable.
In Silverlight I am following the same philosphy of design, but using the animation model(s) provided by the framework. Note the plural!
Model 1 - Property Based Animation
This model works by creating Storyboard objects, and then adding animations (like DoubleAnimation, ColorAnimation, etc.) to its Children. You call Begin() to start animating, and can handle the Complete event when the animation is finished. You provide a Duration that controls how long the animation lasts. The Storyboard can have multiple animations in its Children collection. Each animation targets a specific property of a specific object.
I use this method when I need to move an object from one cell to another on the game grid. To simplify the model, I created a base class called SquareGridGameBoard that derives from UserControl. SquareGridGameBoard allows you to set the number of cells that compose the game board, as well as the width and height of each cell. It also provides a visual cell cursor, and a selection band that facilitates selecting a range of cells. SquareGridGameBoard also contains helper methods that make it easy to position, and move, an element on the game board.
The MoveElement helper method encapsulates the plumbing of creating a Storyboard, the animations, and handling the completed event. Here's the code:
//Move an element to another cell
public void MoveElement(UIElement element, int newX, int newY, Duration duration)
//Create Storyboard, and remember the element it references
Storyboard sb = new Storyboard();
sb.Completed += MoveCompleted;
_storyboardTargets[sb] = element;
//Animate X coordinate
DoubleAnimation animX = new DoubleAnimation();
animX.To = newX * CellWidth + _cellWidthHalf;
animX.Duration = duration;
Storyboard.SetTargetProperty(animX, new PropertyPath("(Canvas.Left)"));
//Animate Y coordinate
DoubleAnimation animY = new DoubleAnimation();
animY.To = newY * CellHeight + _cellHeightHalf;
animY.Duration = duration;
Storyboard.SetTargetProperty(animY, new PropertyPath("(Canvas.Top)"));
private void MoveCompleted(object sender, EventArgs e)
//what element was being moved?
Storyboard sb = sender as Storyboard;
UIElement element = _storyboardTargets[sb];
//push values into properties after animation changes them
double x = Canvas.GetLeft(element);
double y = Canvas.GetTop(element);
You can see this in action in the current demo as of Build 7. When you click on a cell of the game map, it creates a random StarShip, but also moves a StarSystem to that location, using the MoveElement method described above.
Model 2 - Frame-Based Animation
Another animation option that Silverlight provides is enabled by creating an event handler for the static CompositionTarget.Rendering event. When you do this, Silverlight calls your handler on each frame of animation. The default frame rate is 60 FPS, but this is adjustable by adding the "maxFramerate" parameter in your HTML.
I use this method to cycle the colors of an array of 10 SolidColorBrushes that draw the Shields around StarSystems. The Ellipse elements that compose the Shields have their Stroke properties set to one of the brushes in this static array. When the color of one of the brushes changes, it impacts all of the Shield Ellipses that used that brush in their Strokes.
You can see the Shield color cycling in action in Build 7 of the demo.
Sometimes it makes sense to use property-based animations, but sometimes frame-rate animations are a more logical choice. There's no need to sacrifice, use both models, and select the one that makes the most sense for each particular animation task in your Silverlight app!
Monday, June 22, 2009
- I call the BuildScenario method of a Scenario-derived class (in this case Classic).
- Classic creates some random Nebula in the SVGame object.
- I create a PngGenerator of 100x100 pixels in size, representing the full number of cells in the map grid.
- For each cell that contains a Nebula, I set the pixel to a bluish color, otherwise set it to black.
- I make the image the source for an Image object and add this to the Canvas of the game board, sizing it to the full dimensions of the board (3,500 x 3,500) and setting its Stretch property to Stretch.
I was expecting to see sharp edges in the blown up image, but was surprised and happy to see the blended edges that Silverlight produced. Another hurlde overcome (this time thanks to Ian) in my quest to port Solar Vengeance to Silverlight.
See the latest demo build here:
Wednesday, June 17, 2009
A Markov Chain is a way of generating a result based on the statistical probabilities in a set of sample data. The MarkovNameGenerator class can generate random words (names) based on a set of sample words that it takes as input.
It works by building "chains" that count the number of occurrences of each letter in the alphabet after each group of "N" letters in the sample name. "N" is called the "Order" of the Markov Chain.
The class generates a new name by first selecting a random group of "N" letters to begin the name. It then goes forward letter by letter, examining the Chains and picking a new letter from the pool of letters that followed the previous "N" letter groups in the sample data.
For example, the words "Sally Sells Seashells" breaks down into the following 2-Order Chains:
Note the Chains in yellow. These represent 2 letter pairs that occurred more than once in the sample words. The Chain contains all of the letters that follow the single pair of letters.
Now, when the generator makes a new random name it follows this sequence:
1 - Pick a starting pair of letters randomly:
2 - Pick a random letter in the Chain following AS. In our example the only one is H.
3 - Continue picking random letters in the chain until we get an end.
Result = Ashells
In this sample, we never encountered the SE pair, but if we had, we would have appended one of the two candidate letters in the chain randomly.
The fun comes when you feed the name generator with a large number of sample names. The generator, particularly when set to an Order of 3, can produce new names that bear a remarkable similarity in style to the sample names, while still being original.
Using the Class
The MarkovNameGenerator class constructor takes 3 arguments:
The first parameter is the collection of sample names. This can be an array or list of strings. Each string can contain one sample name, or a number of samples separated by commas.
The second parameter determines the Order of the Markov Chains, and the last parameter specifies the minimum length of a generated name.
Accessing the NextName property returns a new random name based on the sample data. The class ensures that the same random name is not returned twice.
Call the Reset method to clear out the internal list of previously generated names.
Click here to download the MarkovNameGenerator.cs C# file.
Silverlight Sample App
Monday, June 15, 2009
In Solar Vengeance, I have a set of grayscale images that represent each StarShip type. When a game begins, SV dynamically generates colorized versions of the images for display. This was easy to do in WinForms and System.Drawing. I haven't found a reasonable solution to this in Silverlight. The WriteableBitmap class that's coming in Silverlight 3 might be a solution, but along the way I have found a better way.
The StarShip graphics for SV are very simple representations, and lend themselves well to vector based graphics. I can create custom classes in Silverlight that render the images using a combination of the simple graphics primitives that Silverlight offers, like Rectangle and Ellipse.
By creating a common StarShip visual base class, I can provide a single "Color" property that gets inherited to the customized rendering classes.
In the latest update of my demo app I render some StarShip types in a list box with a vector based version next to the image based. My work in progress is here ...
Sunday, June 14, 2009
Another position was that my fledgling port of the Solar Vengeance logical engine class library ported to Silverlight without any errors or changes needed.
When I develop a game, I always strive to cleanly separate the logical data model from the user interface. I create a .NET Class Library project that contains the logical model of the game, and a separate project for the user interface.
By maintaining this strict seperation it is now much easier for me to port SV to another platform such as WPF and/or Silverlight. I'm also probably going to change how the multiplayer communication works. A beefed up custom PrismServer will use the same SV logical engine to create an instance of the game and serve as the "host" of the game. It will receive the orders from players, process the turn, and send the results back to each client on each Impluse.
I have some challenges ahead if I want to create an SV front end in Silverlight. In particular, Silverlight does not support the DrawingContext and OnRender method which is the basis of my TurboSprite animation system. If I want a Silverlight SV, I will have to leverage its animation model, perhaps building my lightweight framework around Composition.Rendering which lets you get at the animation loop in a WPF/Silverlight app.
For now, here's my first "Hello, World" Silverlight page ...
Saturday, May 30, 2009
My journey into WPF is still in its infancy, but I want to document some of the ups and downs I've discovered working with the framework, ending in a big UP!
I've been googling like mad and absorbing knowledge as I ramp up the WPF learning curve. Some of my early research left me feeling pessimistic about the prospects of writing a game using WPF. First, there was the message group post (I cannot locate the link anymore, but I promise this was for real) where the poor programmer was experiencing poor render performance drawing lines in WPF (more on that later!) The suggestion he finally adopted was to run a WinForms Picture control hosted in his WPF application! Astonishingly, the GDI+ based WinForms outperformed WPF in the line drawing heavy application!
Second was the promosing blog entitled "WPF for Games". The author was literally gushing about WPF in his early blog entries. By the end of the blog, this grim topic appeared - "Throwing in the Towel", where the author is fed up fighting against the WPF framework and decides to write his game in XNA.
I love a good challenge, and this just makes me want to try harder to get a decent game out of WPF ;)
My first concrete project in WPF is a port of my TurboSprite sprite engine. I have debated internally about whether to port TurboSprite to WPF, or to try and use WPF's framework as the basis for my sprite animation. I concluded that porting TurboSprite would save me alot of headaches in the long run. My feeling is that my lightweight sprite engine will allow me to realize the graphics performance I want without pushing this burden onto the WPF framework. My sprites descend from Object - and there's nothing more lightweight than that! I will use the WPF framework to try and make a cool user interface surrounding the main SpriteSurface that contains the game's action.
But how to translate TurboSprite to WPF? The main component of TurboSprite is the SpriteSurface, and for this I derive from FrameworkElement, and drawing in an overridden OnRender method, using the supplied DrawingContext. In my next blog post I plan to go into some of the early technical details of my implementation, but for now I can describe some of the early results.
I've found that rendering images in the DrawingContext using DrawImage is blazingly fast, and perforing rotations using Transforms seems to not impact rendering performance. I was able to create many very large ImageSprites and add them to the SpriteSurface without and degredation in FPS. This is good news for Scenarios that like to use many large background graphics!
Next I tried to tackle porting beat2k's SpiralSprite, which is the basis for black holes in the SV graphics. The code ported easily enough, but when I created a SpiralSprite in my new WPF TurboSprite, the animation rate went down the toilet! Adding 2 or 3 SpiralSprites caused a complete bottleneck and the FPS was down in the single digit range.
But I was determined to find a better solution than hosting a WinForms control for my SpriteSurface!
After some research I discovered that creating a Geometry was the way to go. Apparently, the Geometry can be rendered with graphics acceleration all in one shot, while rendering the individual lines was very time consuming. The problem with this approach is that it sacrificed the ability to color each segment of the spiral, an effect that beat2k implemented in his code. I solved the problem by rendering the SpiralSprite using a RadialGradientBrush, with the end color set to Transparent.
The end result is a new SpiralSprite class that still has the customizability, the rotation (now leveraging the existing Sprite Spin and SpinSpeed properties), and that can be rendered extremely quickly on the SpriteSurface.
The code for the modified SpiralSprite
//SpiralSprite class by Jason Milliser
public class SpiralSprite : Sprite
public SpiralSprite(int arms, float radiusmin, int radiusmax, int armslope, int slopelength, bool isSpinningClockwise, Color CenterColor)
//arm slope is the number of lines drawn to the center of the spiral. Also controls the tightness of teh spiral.
//slopelength is the length of each line segment of each spiral. longer lines can tighten spiral, but quality will go down.
slength = slopelength;
_centerColor = CenterColor;
_direction = isSpinningClockwise;
_radiusMax = radiusmax;
_radiusMin = radiusmin;
_armSlope = armslope;
_arms = arms;
Shape = new Rect(0-_radiusMax, 0-_radiusMax, _radiusMax * 2, _radiusMax * 2);
//calculate points of spiral
protected internal override void Process()
//we now need to create points only once, rotation performed by transformed
if (_points != null)
int theta = 0;
float sinvalue = 0;
float cosvalue = 0;
double altitude = 0;
float faltitude = 0;
double radiusscale = 0;
double dradiusmin = 0;
int rdegrees = 0;
//preliminary math calculations
theta = 360 / _arms;
if (_points == null)
_points = new Point[_arms * _armSlope + 1];
for (int arm = 0; arm < _arms; arm++)
for (int seg = 0; seg < _armSlope; seg++)
if (_direction == true)
rdegrees = (seg * slength) + (arm * theta);
rdegrees = -(seg * slength) - (arm * theta);
while (rdegrees < 0) rdegrees = rdegrees + 360;
while (rdegrees >= 360) rdegrees = rdegrees - 360;
radiusscale = _radiusMax - _radiusMin;
dradiusmin = _armSlope;
altitude = (seg + 1) / dradiusmin;
altitude = radiusscale * altitude;
dradiusmin = _radiusMin;
altitude = dradiusmin + altitude;
faltitude = Convert.ToSingle(altitude);
sinvalue = LookupTables.Sin(rdegrees) * faltitude;
cosvalue = LookupTables.Cos(rdegrees) * faltitude;
_points[(arm * _armSlope) + seg].X = sinvalue;
_points[(arm * _armSlope) + seg].Y = cosvalue;
//Render the sprite
protected internal override void Render(DrawingContext dc)
if (_points != null)
//Create the Geometry if it doesn't yet exist
//this needs to be done on the same thread, so it's done here and not in Process
if (_geom == null)
_geom = new StreamGeometry();
StreamGeometryContext sgc = _geom.Open();
sgc.BeginFigure(_points, false, false);
points = new List ();
for (int i = 1; i < _points.Length; i++)
sgc.PolyLineTo(points, true, true);
//Transform the location to match the sprite's position
Transform t = new TranslateTransform(X - Surface.OffsetX, Y - Surface.OffsetY);
Transform rotate = new RotateTransform(FacingAngle);
//Create gradient brush so spiral fades out
RadialGradientBrush rgb = new RadialGradientBrush(_centerColor, Colors.Transparent);
//Draw the spiral geometry
dc.DrawGeometry(null, new Pen(rgb, 2), _geom);
//Draw the central back hole
dc.DrawEllipse(Brushes.Black, null, new Point(0, 0), 7, 7);
private Point _points;
private int _arms;
private float _radiusMax;
private float _radiusMin;
private int _armSlope;
private Color _centerColor;
private bool _direction;
private int slength;
private StreamGeometry _geom = null;
private Pen _pen = new Pen(Brushes.Yellow, 1);
Friday, May 29, 2009
Wednesday, May 27, 2009
With .NET came a layer of abstraction away from Windows, meaning less fine-grained control and power, but a modern development environment with a clear future.
Since the release of the .NET Framework 3.0 in late 2006, the WPF (Windows Presentation Foundation) framework was the cool new API in the Windows world. Windows Forms became old fashioned and quaint.
I'm about 3 years late to the party, but I have finally begun to update myself in WPF. The compelling reason this time is fear that Windows Forms is becoming a dinosaur framework, and I need to keep current. I have mixed feelings about this move, unlike for example the shift from VB to Delphi which I felt had no negative aspects.
First of all, my feeling is that WPF is currently half baked, without a full RAD development experience in Visual Studio. The idea of using two tools (Visual Studio and Expression Blend) to work on an application is not appealing to me. The direction of promoting XAML as a form markup language that a developer needs to code in leaves a very bad taste in my mouth. In my mind, the form markup language should remain in the background without having to be seen, much less edited. Also, much of the WPF API seems to have the flavor of the old Win32 APIs, with function calls with loads of obscure parameters in favor of a cleaner and more well thought out framework.
On the positive side, preliminary conversion of TurboSprite to pure WPF is showing promising results, with an animation frame rate of 3000+ FPS in my basic testing with no sprites added yet to an animated surface. All of my research indicates that GDI+ suffered badly in terms of performance when rendering images. WPF makes better use of graphics accelerators, so in general rendering should be much faster, as my early tests support.
Hopefully this will translate to an eventual SV6 and future games where graphics updates are no longer an issue! This transition also opens the door to create a companion SV6 client in Silverlight that will run in the web browser (in Windows or Macs) and allow multiplayer play through PrismServer. You may not remember, but once upon a time there was a Java applet version of SV that ran in the browser. Having a browser based, full fledged SV client is another compelling reason in favor of shifting development to WPF.
Sunday, April 12, 2009
I completed two more features in WinWar II 5.0. Firstly, the Technological Research component is in place. To have your Nation conduct research, all you need to do is build Labs in one or more of your Zones. The Labs generate tech points behind the scenes, and you get periodical improvements during the game. If you place a Spy in another Nation's Zone that contains a Lab, you can also steal some of their tech points as they are generated.
There are Conventional Technology Levels for Land, Air, and Sea. When you advance a Level, the units you build for the particular Unit Class (land/air/sea) are 10% stronger in their attack and defense (and bombing if applicable) levels.
Special Technologies include:
Allows you to build Radar installations in Zones that extend visibility.
Gives you a chance of eavesdropping on private communications between other Players.
Lets you build Rocket Launchers that can conduct Strategic Bombing in a target Zone in their range.
Lets you build "Atomic" units such as an Atomic Bomber. Atomic attacks will devastate a Zone, reducing its Value, and possibly destroying Bases, Factories, Labs, etc. in the Zone, in addition to taking a large chunk out of the Funds of the Nation attacked.
I also completed the Strategic Bombing concept for the game. Certain Unit Types can be given the "Bombing" attribute which gives them Strategic Bombing capability. When these units are in an enemy Zone they will automatically conduct Strategic Bombing attacks periodically. The damage done is subtracted from the Funds of the Nation being attacked. Attacking high value Zones obviously does more damage.
Monday, March 30, 2009
I've completed the Diplomacy system for WinWar II 5.0. Each Nation in the game has a Stance against each other Nation in the game, even Minor Powers to Minor Powers. Actions that occur in the game can impact the Stances of Nations toward one another. Stances can more directly be affected by executing a Diplomatic Action.
Each Major Power can take a Diplomatic Action when it's available. After an Action is taken, another Action isn't possible until an internal counter counts back down to zero. The length of time between Actions is determined by the last Action taken (some are more costly than others), the Political Strength of the Nation's Head of State, and a randomizer.
Below are the Diploamtic Actions available in WinWar II 5.0:
Conduct Summit - If successful the Stance of the target Nation is improved. There is a small chance that the Summit will backfire, reducing Stance. This chance is based roughly on the current Stance between the two Nations, the lower the Stance the greater that chance that the Summit will backfire. Note - if you raise the Stance of a Minor Power to 100, that Nation comes under your control!
Denounce - Available only to Nations that are not flagged as "Imperial". This reduces the Stance between your Nation and the target Nation, and also impact the Stances of other Nations friendly to you toward the Target. A non-Imperial Major Power can only attack another Nation when they are At War (Stance = -100) so Denounce will be an important the Allied Powers.
Declare War - Imperial Powers will have a Declare War Diplomatic Action instead of Denounce. An Imperial Power could Declare War automatically by just invading a Nation, but they might want to issue this Action if they want to attack an enemy navy without having to invade a Land Zone.
Exert Pressure - If the target Nation succumbs to the pressure, it comes under your control immediately. If not, the Stance between the two Nations suffers. The Action has a greater chance of success if forces are massed along the target's border.
Incite Coup - If successful, a new Government is formed in the target Nation, having a set of roughly opposing stances, with some randomization involved here.
Another nuance of the Diplomatic System: taking hostile Diplomatic Actions has the effect of making the target Nation's neighbors nervous, and reducing your Stance with them. Also, Diplomatic Stances are dynamic, and can shift during the game spontaneously, sometimes with interesting results. For example, in one game, early on, Spain spontaneously allied with the UK. That would surely shake up the strategies in the early phases of play!
A scolling ticker informs you of various events on the bottom of the screen, allowing you to keep up to date without providing too much of a distraction. Game event history is also available in a dedicated window if desired.
Friday, March 20, 2009
When I first switched from the Delphi programming language to C#, PrismServer was the first serious development effort I undertook. I always like to have a concrete project to work through when I learn a new language.
Looking back at my original effort, I discovered some flaws in my work that experience with C# helped me recognize now. These flaws manifested themselves as sporadic crashes in the server piece of the PrismServer package.
I have spent some time over the past few weeks nailing down and correcting these problems. The problems revolved mostly around multi-threading issues. I was not properly locking variables that could be access from different thread. The problems most frequently occurred when using a foreach loop, and then having the List<> that the loop was enumerating change by a call from another thread.
For example, when PrismServer is trying to send information to all of the players in a specific room, it uses a foreach to enumerate the players in the room. If a player entered or exited a room during this loop, PrismServer.exe would crash hard.
After identifying all of the appropriate places to put lock statements, another problem manifested. When a player would drop from the game, there would be noticable lag of about 30 seconds that stalled all traffic in the server. This sounded like a locking issue; i.e. one method waiting for a lock to be released that was set in another method.
Sure enough, I discovered that the method that writes information to the players' sockets was locking the list of connected Guests in that subject. When one of the players dropped, this caused a delay as the socket timed out, and the lock was still set until the socket timeout completed. This caused a bad cascade that eventually brought the whole server to its knees until the socket timeout completed.
I corrected this by creating a new thread to handle outgoing communication. When PrismServer wants to send something out on a socket, it now adds the string to a Queue
After stress testing, I'm happy with the performance and stability of PrismServer, and look forward to seeing how long the new build can run before it needs to be restarted.
Below is the relevant section of code that resulted in the most bang for the buck improvement (from PrismNetworkStream.cs)
//This thread keeps executing and writing information to the client
private void WriteThreadExecute()
bool written = true;
written = false;
string s = null;
if (_outgoing.Count > 0)
s = _outgoing.Dequeue();
if (s != null)
written = true;
Sunday, March 15, 2009
Today I released the beta version of Solar Vengeance 5.1. It includes some interesting new features that have never been seen in the SV line before:
DynamicEvents Programming Model
I re-organized how Dynamic Scenarios can be programmed for SV by creating an interface called IDynamicEvents. This interface contains a number of methods that you can call in a Scenario to cause dynamic behavior in the Scenario's ProcessImpulse method. The interface is exposed in the Scenario class via the DynamicEvents property.
This change is largely cosmetic from the previous "DS_Method" model of SV5, but I like the fact that the dynamic methods are now cleanly separated into their own interface.
UDOs - User-Defined Objects
Scenarios can now include UDOs that can represent anything you want in the game. You can assign a static or animated image to a UDO of any size, and you can control how they move via UDO related DynamicEvents methods. UDOs can also be "picked up" and carried by StarShips, making "capture the flag" style Scenarios easy to create.
SV5.1 includes a new Scenario, CollectTheScientists, that relies on UDOs. You have to find the Scientists that are scattered in the middle of a supernova remnant and bring them back to a safe zone next to your Capital.
Scenarios can now render directly to the game map during the animation cycle. The PaintHook methods pass you the .NET Graphics object that represents the map, and you are free to render to it to your heart's content.
Transport Order Overhauled
After much demand, the Transport order can now pick up Resources from any number of friendly StarSystems or BattleStations, and deposit them to any friendly StarSystem or BattleStation.
Download SV5.1 beta now and help me put these new features through their paces!