Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Canceling Xna

After a year of not using XNA creator's club and being generally morally opposed to the whole concept I decided to cancel it. Long story short this requires contacting xbox support (weeee). The only truly annoying part is how hard it is to find out this is what you must do and what the phone number is you must call.

It seems borderline unethical to not have a mechanism for canceling your account that is as easy as signing up.

jQuery bounding region plugin

While working on some javascript network visualization software I am coding for work I came up with a jQuery plugin function that calculates the bounding box around the query using offset() and width() and height() returning an object that has left,top,bottom, and right members.
(function() {
   jQuery.fn['bounds'] = function () {
     var bounds = {  left: Number.POSITIVE_INFINITY, 
                      top: Number.POSITIVE_INFINITY,
                    right: Number.NEGATIVE_INFINITY, 
                   bottom: Number.NEGATIVE_INFINITY};

     this.each(function (i,el) {
                 var elQ = $(el);
                 var off = elQ.offset();
                 off.right = off.left + $(elQ).width();
                 off.bottom = off.top + $(elQ).height();

                 if (off.left < bounds.left)
                   bounds.left = off.left;

                 if (off.top < bounds.top)
                   bounds.top = off.top;

                 if (off.right > bounds.right)
                   bounds.right = off.right;

                 if (off.bottom > bounds.bottom)
                   bounds.bottom = off.bottom;

               });
     return bounds;
   }
 })();

Building internal webapps

I couple months ago I picked up Enterprise Integration Patterns. It was a lot better then I thought it would be considering it contained the word enterprise in the title. The premise of the book is that using message queues/buses allows for easier integration of applications even spanning organizational boundaries.

This got me thinking about web services exposed through REST/http. One of the nice benefits of http is that it has clients in almost every language and environment. While exposing services and tools with a http interface can solve more than the immediate problem of feeding your ajax app it can also allow a larger set of people to leverage your service.

It seems like the smartest thing any organization that has lots of internal services could do would be to make a directory of such services maybe even use RDF. Of course the problem is the reliability of these services may vary depending on the needs of the original author and the maintainer. Requiring the author of every web service to make sure their service is up 24/7 might not be appropriate.

Rotations and lame network cards

It occurred to me while debugging my 3d camera that rotations are far to rotatey. R^T = R^-1 = R(-a) which means if you have a bug it can be confusing and potentially work to some degree even though really your code is completely crazy. In this case I was uploading rotations into opengl that were row major when it is in fact column major. Another amusing thing is if your rotation is several rotations such as R = r(a)r(b)r(c) then R^-1 = r(c)^-1 * r(b)^-1 * r(a)^-1 which means your rotations are now going to be done in a different order in the opposite directions.

I would also like to thank my marvell yukon network card for failing at life. It was trying to offload checksum calcs in vista but doing a worse job than my CPU. So much so that it was causing team fortess 2 to be inoperable. Luckily these things can be adjusted.

Programming languages! Programming languages!

ANTLRWorks is like crack. I am trying to build a bastard child of ml and ruby and maybe a little scheme mixed back in for good measure. One of my favorite features from haskell is the pattern matching which seems like a no brainer for adding to a scripting language.

I have also been picking up ruby lately and its surprising how good it is. Some people compare it to being similar to python. This is not the case--it has a lot more delicious features. Succulent indeed.

Then there is groovy which is subtly disappointing but sure as shit beats writing actual java but not by enough. At least java makes sense in its own crippled and ridiculous way.

Try passing a function as a value in groovy from inside it self. Sure it has whatever hack is needed for recursion but apparently it is only half-baked. Very disappointing. How am I supposed to use recursion in conjunction with higher order functions? I may post something somewhere so it can some how get fixed. Its kind of embarrassing to bring up so it seems more sensible just to make my own language (yup I am crazy).

Wont someone please think of the functions!

Anyways ANTLR is awesome and I am sleepy. I will probably post more of whatever language I cook up if it ever amounts to anything.

Embedding IronPython

I am trying my luck with embedded IronPython 2 using the DLR so I thought I would share some of the steps to make that happen.

Prereqs:

  • Microsoft.Scripting.dll
  • IronPython.dll
  • IronPython.Modules.dll

These all come from the IronPython2 beta 1 release--and yes you need all of them. Failing to add IronPython.Modules.dll as a reference results in strange errors when trying to get the scripting engine which can be confusing.

The interface to IronPython and presumably other DLR languages is through the Microsoft.Scripting.Hosting.ScriptEngine class. There seems to be about a billion ways to get the engine here is what worked for me:

ScriptEngine engine; engine = PythonEngine.CurrentEngine;

This gets/creates the ScriptEngine for IronPython. Next we create a Microsoft.Scripting.Hosting.ScriptScope which allows for variables to be bound on the embedder's end before the script is run. It also can be inspected after the script is run.

ScriptScope scope = engine.CreateScope();

Now all that is left is to load the script woooo. Doing this creates a Microsoft.Scripting.Hosting.ScriptSource object which can have fun things done to it.

ScriptSource source = engine.CreateScriptSourceFromFile("myScript.py"); source.Execute(scope);

This loads a script and then executes it using the scope that was created. The contents of the scope can be examined afterwards like I said which can be useful if you want to create factories that return an extended C#/CLR class that can then be used like normal.

TacticsGame game = scope.GetVariable("game");

This gets the global "game" form the script. In order for this to work right you need to add the assembly references to your script. This can be done in two ways. First you can do it the normal way from inside the script:

import clr clr.AddReference("MyAssembly.dll")

This works but its kind of annoying if MyAssembly.dll is actually the same assembly that the script is being hosted in or some other assembly that is known. Another way is to call engine.Runtime.LoadAssembly and feed it assemblies it should know about. See System.Reflection.Assembly for some ways of getting these assemblies.

Hopefully this works a bit better than boo did!

Embedding example
An informative but trying on the eyes tutorial.
IronPython Website
In all of its official and incompletely documented glory.

XNA ContentManager.RootDirectory Considered Annoying as Hell ( XCCAH)

Beware of older XNA code using code created by the new project templates! The newer code sets the root directory of Content to "Content/" which breaks all my old code and was very confusing. Which leaves me wondering if they are going to include that as the default why not change it in the class! Blargg. Now any "game libraries" which have content that gets loaded have to worry about what the RootDirectory setting is at unless they use their own ContentManager.

ContentManager.RootDirectory Property <-- boo

Time to put patches down.

When you are coding what we might call language X and you ever think "yay it actually lets me do this non-stupid thing" such as map, filter or anything really a sane person might need when constructing software then you know you have a problem.

I am looking at you perl 5.

*glare*

Ruby,anything from ml,python,scheme,lisp... I can't count the number of better languages suited for most jobs perl gets used for still. I normally not a language zealot but jebus! If I see another perl hash with elements whose values are "1" because perl has not set data type I am going to vomit.

Perl is not regression in programming languages as much as it is a scripting language that is on life support. Its an old man clinging to life after a long and fulfilling life. Its time to pull the plug and let gramps die in peace.

OK I lied it probably was but lets just let it die in dignity. Perl was one of my first scripting languages so well I hate it slightly less than I should but still...

You know its bad when you would rather be writing java than perl. Actually its not too bad with anonymous classes. Why the hell they don't add anonymous functions I don't know. I guess they don't want to ruin the master piece that is java.

mmm rant tastic. I need to record my insane ramblings so that whatever future society goes through my blog (cause you know they will) gets the record straight. I am one of those scary computer scientist Larry Wall warns you about in programming perl--and I hate sunshine puppies and probably a lot other things. Especially kittens. I also eat metal scraps and speak in binary. In fact I often eat kittens for desert while speaking in binary.

Java Restlet api rocks

I have been using the java Restlet api for network topology stuff and it is quite nice. Seldom do you come across cleanly designed APIs these days it seems. It avoids a lot of the common pit falls java apis seem to enjoy:

Factory diarrhea == teh sux
Everyone who has used java has probably experienced this. If you are writing api realize that most people don't give a crap about a configurable factory. Give people concrete instances of things that default to a particular implementation. Configurablity is good but I should not need to enter a deep philosophical debate with my compiler just to determine how it should parse XML.
Fixed verbosity
Most libraries have a fixed way something must be done. More than likely the level of verbosity required to do it inappropriate for what the user is doing. Design your classes so they can function with out extra functions calls and other pointless boiler plate code if you can. When the user needs more control they can specify it when needed. People can learn your library faster and programming with it will be much more pleasurable.
Documentation
People seem to have strange ideas about what appropriate levels of documentation is. Hint: you need more than just javadocs/doxygen output. Your software should be the sum of its parts. Documenting the individual pieces in isolation with out providing more detail makes learning how to use your code orders of magnitude more difficult.
Use standard abstractions
If the language provides a standard library with things like iterators and structures use them! If programs are essentially language recognition and translation (which they are) then using common concepts is essential. If you don't do this you are failing at communicating with the people reading your code and also doing a poor job communicating with the machine which you are instructing.
There is a billion more tips but these are the major ones.

Rolling your own CSS

Having an easily data driven method for customizing style information can be invaluable for building nice user interfaces. For special purpose user interfaces like games it is even more important. Designers need to be able to easily skin and customize different UI elements with out having to alter source code.

UI Elements as Properties

To control the look of user interface elements a simple flat set of properties can be used such as "background-color" or "font". A style sheet is simply a class that you can get and set properties from: class Style { public object GetValue(IStyleable target, string propertyName); public void SetValue(StyleSelecter selecter, string propertyName, object value); } Just like in CSS a common way to refer to elements is needed. I used StyleID, a set of Classes and a Type to replicate the familiar id,class,elementType trio. This is formulated in a simple interface: interface IStyleable { string StyleID { get; } ICollection<string> { get; } string StyleType { get; } } A predicate for if a certain property definition applies is needed: abstract class StyleSelector { public abstract bool Matches(IStyleable target); }

Finding a Property

Every selector must at the very least support the ability to find a property by an O(n) search--this is what the Matches method is all about. Finding a property consists of a search over a list property definitions (StyleSelector,name,value). If a definition's name matches and StyleSelector.Matches is true then the search is terminated and value is returned as the value for that property.

In order for the cascading part to make any sense an ordering of property definitions needs to be defined. CSS solves this problem with the notion of specificity. Properties with more stringent criteria for being applied are allowed to float to the top and are used over the more generic definitions.

For my purposes I organize things simply by id > classes > type > *. So selectors that specify the id of its target are examined first. This conveniently allows for property searches to be culled to smaller sets that must be visited. Hashtables for each of these categories can be constructed to speed up search times so that for example (id,name) is indexed. This reduces linear searching only to custom and other miscellaneous selectors.

Combining Selectors

Aggregated selectors can be formulated based the AND logical operator. Since AND is commutative the selector can be rummaged through for any sub-selectors that are indexable. This can then be used as criteria for which index the aggregation should be inserted into. For example #myButton:hover can be inserted into the id indexing table since it contains an id selector.

I will probably post the code to this and the rest of my GUI toolkit when I am done / bored with it.

Game Rules 1

I mentioned I would talk about a domain specific language for game rules so I will but first a rant on why the term DSL is silly and some discussion on what a game rule itself will be.

The term DSL is kind of stupid

Like any good acronym one day you wake up and it is as if while you were sleeping everyone got together and decided to surprise you the next day. Suddenly people realized they could make their own languages to solve specific problems and that this was now the neatest thing since sliced bread and other suitably neat cliches.

It is not that I am opposed to them. I just find it appallingly annoying how computer science and the software industry is often reduced to fads. It is as if all the people who slept through their compilers courses (really when else are you going to get a nap?) suddenly realized that this information was actually useful. DSLs don't solve all of your problems--but being smart and knowing the theory behind them will transform them into useful tools. I suggest picking up the dragon book and books on automata and language theory.

What is a game rule?

When playing games generally there is a set of rules to play by. These usually follow as consequences for some action the player does. These rules can also be the consequences of actions by other rules. Such as a player moves his piece on a board game and receives 5 points. He already has 10 and it only takes 15 to win lets say. The rule for winning was based off an action from another rule (gaining 5 points).

A game rule is action and then a consequence or more formally a predicate and some function that changes the course of game play somehow. R = (P(s),F(s)) So to apply a rule P(s) must be satisfied. Then s := F(s). Of course fashioning this into an actual usable system will require more work which I will save for next time.

Game rule DSL maybe?

I am cooking up an idea for a game rule DSL and will probably post more when I actually start working on it. I am also kind of sleepy right now but think of something db triggers except not awful and crazy.

Design Pattern Soup

While designing the class that manages my game objects the other night on a project I came across an interesting pattern. Using the visitor pattern with a mediator to add objects.

interface IRenderable { public void DrawMe(); } class Renderer { public void Add(IRenderable renderable); public void Remove(IRenderable renderable); }

This is normal looking code for most applications. The power of being able to add random things that can be drawn is very useful. There are several problems with this first it can be important what order things are rendered when drawing 2d and 3d graphics. Also for the purposes of batching it may be very important to group like objects together.

These two problems can make things somewhat messy. Its possible to overcome them naturally. For instance we could include an integer that describes the order which renderables are to be drawn and sort them that way. For batching each renderable could queue it self up for rendering and then after a certain number of objects are in the queue or if it needs to be flushed for example if we are done rendering. Of course the batcher would have to somehow register it self with the renderer also since presumably only the renderer knows when its done drawing and any retained style buffers need to be flushed.

There is a simpler way which at first may seem silly and that is to have the objects register themselves at the request of the renderer--basically the visitor pattern.

interface IRenderable { public void DrawMe(); public void Add(Renderer renderer); public void Remove(Renderer renderer); } class Renderer { public void AddSpecialDohicky(Dohicky dohicky); public void RemoveSpecialDohicky(Dohicky dohicky); public void Add(IRenderable renderable) { renderable.Add(this); } public void Remove(IRenderable renderable) { renderable.Remove(this); } }

This allows for all sorts of interesting behavior. Also IRenderable could still support a basic one size fits all DrawMe() call if needed. Another side effect of this is that the Dohickys don't have to actually to be implementers of IRenderable which leaves things wide open for using composition instead of inheritance.

Naturally the draw back is that the Renderer is coupled with Dohickies but it makes it much easier to add optimizations to your renderer since it for example can cross coordinate with other objects being rendered so you do not have a bunch of objects operating in a vacuum simply for the sake of proper OO design. Like everything its all a matter of trade offs.

A relational model for REST

For awhile I have had the desire to create some sort of fantastic contraption that combines relational databases and REST services that allows for people for example to mash up distributed data in a nice formal and hopefully automated way.

I do not know much about database theory but the main difference is that with a REST service it is usually impossible to enumerate a given set of relations. This is something a query planner/relational calculus could easily work around I would imagine. Naturally some types of queries would be impossible!

The other half of the solution would be a common registry of adapters and relations since such software would need to have definitions as to what nouns are compatible and how to convert between similar data but with different interfaces. This would make work writing software that uses distributed services much simpler. Imagine being able to do use SQL joins to mash data up!

Maybe I will try hacking such a system up when I am not playing one of the bazzilions games that just came out (Mario Galaxy is awesome!). Hopefully it wont be to hard to create a proof of concept.