Showing posts with label triggers. Show all posts
Showing posts with label triggers. Show all posts

Sunday, July 26, 2009

Sounds

After a year-and-a-half of taking part in Metaplace during alpha and beta, I've finally added sounds to one of my worlds (I don't count the crwth_effects world, as the sounds are only played when the "player" tries them out, and not as part of the world itself.) I'd say the biggest reason is that I rarely finish a world, and something like sound is a finishing touch.

I'm not really sure what made me do it, since the world I've added them to, my Ultima Online workspace world, is nowhere near done (being a lab world, it'll never be done as such). For some reason this past week, I got to thinking about the music of UO, or the sounds of UO... I'm not sure, but I decided to figure out how to pull all of the UO sounds from the datafiles. Once I had those, I browsed through them, playing them to bring back memories (which is silly, since my UO accounts only just expired) and to see the large portion of them that never appeared in the game. Some of the sounds include the player's footsteps on a variety of terrain, and I was thus compelled to add them into the UO world.

The funny thing is that right now, my UO world doesn't have the UO avatars for the players, but the Metaplace ones instead -- the only non-UO thing in the world gets the only UO sounds! For each terrain type (grass, pavement, sand, etc.) there are two sound files, allowing you to alternate the foot falls per-foot; they could have taken the approach of a sound file that played a two-step sound, but it wouldn't match up if you took a single step with your avatar.

This poses a challenge right off the bat, since there's no way in Metaplace to say "play these two sounds in a loop"; all sounds, whether to an individual or the whole Place, or whether always-on or based on distance, are on their own. Because we want to play a different sound right after one finishes -- to give the clip-clop walking effect, we have one of two tools available to us: we can either ask to be informed when a sound ends (and then act to start up the next one), or we can try to time playing the next sound based on the length of the current one.

Trigger sound_done

As part of the PlaySound*() series of API functions (but not exhaustively documented), you may provide an object pointer as a callback object, telling the system that once this sound finishes, this callback object will have a "sound_done" Trigger fire at it. This lets you play the next sound at the right time -- in theory. Of course, being an online world, you have the latency of the internet to contend with, which means that once the sound finishes, your client tells the server (after X milliseconds), the server acts upon this information by firing the sound_done trigger at the specified object, the object decides to play a new sound, and the client is told, again after X milliseconds. All told, these milliseconds can add up, between the latency and the script logic to determine that another sound should be played. This delay is probably fine for playing background music (which I also added to the UO world), because a half-second delay between soundtracks is fine. A half-second between footsteps, when you're stepping every quarter-second, is not.

Here are the basics of this method:

Trigger sound_done()
local movesounds={
{"feetpvmta","0:19"},
{"feetpvmtb","0:18"}
}

self.move_number=self.move_number+1
if self.move_number>#movesounds then
self.move_number=1
end
local moverec=movesounds[self.move_number]
self.move_sound=PlaySoundTo(self,moverec[2],255,0,self)
end


SendTo()

While we can't completely eliminate the latency problem, we can at least reduce it by not waiting to react to a message from the client, stating that the current sound has finished playing. Instead, after starting the current sound, we'll fire a delayed Trigger to our sound-playing code to just start playing when it makes sense to do so. This means that we need to know how long our sounds are to know how long to wait (for playing a series of background tracks), or we have to know that a given delay will be plenty of time for each of the sounds to play and finish (such as short footstep sounds).

Trigger movesound()
local movesounds={
{"feetpvmta","0:19"},
{"feetpvmtb","0:18"}
}

self.move_number=self.move_number+1
if self.move_number>#movesounds then
self.move_number=1
end
local moverec=movesounds[self.move_number]
self.move_sound=PlaySoundTo(self,moverec[2],255,0)
self.soundtrigger=SendTo(self,"movesound",250)
end

I have to admit, I was prepared to trial-and-error the delay value to see what looked good -- in theory, it should be based off of the framerate of your animation, and the number of frames between each foot lands on the ground in the animation), but I really lucked out with my first attempt at 250ms -- go take a look at the world and see if you agree.

That's right, I've gone with this second approach, for the reasons specified -- I've reduced the effect of latency on my sounds loop by not relying on the client to report when the sounds finish, and I'm able to do this because the clip-clop of walking is very regular. And what about my background music? Well, in the end I used to delayed-Trigger method, there, too:

Trigger playmusic()
local music={
{"britain1","http://pages.cpsc.ucalgary.ca/~crwth/metaplace/uo/music/Britain1.mp3",39},
{"Britainpos","http://pages.cpsc.ucalgary.ca/~crwth/metaplace/uo/music/Britainpos.mp3",53},
{"Stones1","http://pages.cpsc.ucalgary.ca/~crwth/metaplace/uo/music/Stones1.mp3",135},
{"Walking","http://pages.cpsc.ucalgary.ca/~crwth/metaplace/uo/music/Walking.mp3",343},
{"Medieval","http://pages.cpsc.ucalgary.ca/~crwth/metaplace/uo/music/Medieval.mp3",150},
{"Festival","http://pages.cpsc.ucalgary.ca/~crwth/metaplace/uo/music/Festival.mp3",128},
}
self.music_number=self.music_number+1
if self.music_number>#music then
self.music_number=1
end
local musicrec=music[self.music_number]
self.background_music=PlaySoundRefTo(self,musicrec[2],100,0,self)
SendTo(self,"playmusic",(musicrec[3]+1)*1000)
end


Note the list of tracks also contains the length, needed because they're of variable length, unlike the footsteps. Why use this method instead of the sound_done() Trigger? I think the main reason is because, when trying to handle both the music and the sound effects, I had code that looked like this:

Trigger sound_done(userid,handleid)
if handleid==self.background_music then
SendTo(self,"playmusic",1000)
elseif handleid==self.move_sound then
SendTo(self,"movesound",0)
end
end

I can't imagine all the conditionals when I've got dozens of sound effects, such as spell effects and combat sounds. Sure, I could separate them into different scripts each with their own sound_done() Trigger, but the conditional code would still be the same. One way I see this being a bit more useful is being able to supply not only the callback object, but the callback Trigger as well.

Dynamic footsteps

The other thing I decided to do, because of the variety of footstep sounds available, was to change the sound based on the terrain the player walked upon.

In general, having different events based on the tiletype that a player stands on isn't "easy", because tiles themselves don't support Triggers or events, so you can't just attach a script to a grass tile that sets the player's footstep sound to "feetgrssa" and "feetgrssb". For many cases of tile-based effects, you'd have to have some sort of tick-based Trigger, checking if the tile has changed and then changing the effect in question.

The handy thing about the footsteps firing every 250ms, however, is that this provides its own "tick", and thus every time we're to start a new sound, we can decide if the sound should change.

Trigger movesound()
if self.moving==0 then return end

local tile=GetTileAt(self.x,self.y)
local tilename=stylesheet.places["0:"..GetPlace().placeId].tiles[tile].name
local movesounds={
stone={
{"feetpvmta","0:19"},
{"feetpvmtb","0:18"}
},
grass={
{"feetgrssa","0:21"},
{"feetgrssb","0:20"}
},
dirt={
{"feetgrvla","0:25"},
{"feetgrvlb","0:22"}
},
sand={
{"feetsanda","0:23"},
{"feetsandb","0:24"}
},
water={
{"feet15a","0:27"},
{"feet15b","0:28"},
{"feet15c","0:29"},
{"feet15d","0:26"},
}
}
local tilesounds=movesounds[tilename]
if tilesounds then
self.move_number=self.move_number+1
if self.move_number>#tilesounds then
self.move_number=1
end
local moverec=tilesounds[self.move_number]
self.move_sound=PlaySoundTo(self,moverec[2],255,0,self)
end
self.soundtrigger=SendTo(self,"movesound",250)
end

This assumes that your tiles are nicely named, as mine are (they're computationally-generated from the Ultima Online datafiles, which conveniently provide names), though this is all in the hands of the world builder anyway. The above is the exact function I use for my footsteps.

Of course, this solution wouldn't work for sounds that have a long "tick" -- Ultima Online played different background music depending on your region, so you'd get some spookier music in the jungle or a dungeon, compared to a forest or city. You wouldn't want to wait three minutes for your current cycle of "city" themed music to end before realizing that you're in a dungeon and should be a little more on edge.

When to walk

The only thing missing is knowing when to start and stop the walking sound loop at all. The last snippet gave a hint on how the stopping is done -- using a property called self.walking. It's used to stop the sound-playing loop, above, but how is it set? By patching into the path_begin()/path_not_found()/path_end() series of Triggers that are part of the pathfinding system.

Trigger path_begin()
StopSound(self,self.move_sound)
if self.soundtrigger~=0 then CancelSend(self,self.soundtrigger) end
self.moving=1
SendTo(self,"movesound",0)
end

Trigger path_end()
self.moving=0
StopSound(self,self.move_sound)
end

Trigger path_not_found()
self.moving=0
end

The extra code in the path_begin() Trigger is necessary because of the delayed-Trigger method being used; if someone was walking and then clicked elsewhere, they'd start a new pathfinding session but wouldn't have stopped the last delayed-Trigger, causing two (or three, or four) sound loops to play until the player finally stopped moving. This was an interesting effect, but definitely not desired!

Some readers might be thinking that such a problem could be avoided if I had just used SendToRepeat() instead of a recursive delayed Trigger. Then I could just let the SendToRepeat() continue as it would, but I could really do the same thing with the recursive Trigger. The reason I didn't use the SendToRepeat() is because of the possibility of a variable delay for the sounds; while the footsteps are a regular 250ms apart, I might get sounds that aren't so regular, and would thus want to be able to vary the delay, much as done in the music loop. For this use, I could go either way, but I like to code generally, even if Dorian and Sean would rather I didn't.


I'm happy with how the sound turned out, considering it was really a whim. It makes me want to get more sounds into the world, even without the mechanics that really require them (the sounds of combat, the sounds of crafting, monsters roaring...) I also realized, as writing this post, that the footstep sounds are solely for the ears of the maker -- this is a bit silly, since we have PlaySoundRefRadius() to emanate sound from an object and to get the feature of distance affecting the volume built-in. Perhaps I'll go take a look at that now.

Friday, June 12, 2009

Metascript

The scripting language for Metaplace, Metascript, is strongly based off of Lua, so much so that one might think that it WAS Lua. If you don't know Lua before diving into Metaplace, then that's fine, but if you've got some Lua under your belt, you might hit some hurdles.

This post isn't about learning Metascript, though, or about the differences between it and other programming languages, or how Lua/Metascript sucks compared to your favorite language. Just because you come from a background where arrays are indexed from zero doesn't mean that indexing from one is wrong. And if you want to argue the point, then I'll point out that Lua doesn't have arrays anyway.

Syntactic sugar

One of the things that will strike Lua programmers is the extra set of definitions available in Metascript:

  • Define Properties()

  • Define Commands()

  • Trigger foo()

  • Command bar()

  • WebTrigger baz()


These all start "special" functions in Metascript, and aren't standard Lua. What post-alpha users might not know, though, is that these are just colourful candy coatings for some mundane-looking counterparts:

  • function def_properties()

  • function def_commands()

  • function trg_foo()

  • function cmd_bar()

  • function trg_http_baz()


In fact, way back when we also included the "trg_" prefix in the SendTo() calls. As far as I know, these old methods still work; I assume this because

  1. I still have old worlds that use it (thought I haven't visited them in a while)
  2. We were told that they wouldn't stop working


Kinda takes some of the mystery away, doesn't it? I can see why the change was made: it helps to emphasize the special nature of these functions from others defined with "function XXX()"; and it hides the unfortunate fact that variable prefixes are used to denote semantic meaning. Don't consider them variables? In Lua,

function foo_bar()
...
end

is equivalent to

foo_bar=function()
...
end

Hrm. I'm now curious whether I could write

def_properties=function() foo_bar=0 end

in Metascript and have it work. I'm going to guess not, which I'll talk about shortly.

So, should you use function trg_foo() instead of Trigger foo() ? One reason you might is to do some offline programming, so you have code that compiles under a standard Lua interpreter, but can still be tested (by implementing your own backend library that knows how to handle Triggers and Commands). I've used this in the past to do some rapid development and to avoid some editor idiosyncrasies.

Define Properties() and Define Commands() (or function def_properties()...)

I've made no secret my dislike for these "functions". Define Properties() is where you define your script properties (where they might collide with others on the object), include scripts (similar to Lua's dofile()), expose properties and export functions.

Define Commands() is where you define your MakeInput()s and your MakeCommand()s. (There used to be a separate function def_inputs() -- I wonder if that still works.)


These functions are handled "specially"; they're actually executed at compile time, which can reveal bugs earlier than runtime, such as attempting to access functions that aren't available (which is almost all of them). That means no Debug(), no AlertToPlace() - no pairs() or ipairs().

They're actually code, though; you can have for loops in here, if there's anything worth looping over, and conditionals, if there's anything to compare. But generally, these functions act as definition blocks, and might better be implemented as such, extending the Metascript further from standard Lua. Then we could have some alternate notation for defining properties, such as

float value;

instead of relying on

float=0.0

to work. Which it won't. This is because behind-the-scenes, any local variables defined in this block are being specially processed into member variables on a C++ object on the server (all supposition -- I'm not actually privy to the source code). Being C++, types need to be known and once defined, permanent. This means that, unlike Lua, Metascript won't let you redefine the type of a property once it has been set (and this is a reason why I advocate table properties). Not only that, but it means that certain Lua types - ones that aren't available in C++ - aren't allowed as properties, such as booleans and functions. I would expect that supporting table properties had to require a bit of work, having the Lua form of the table being converted into something that C++ understands, and can hold, so why not a Lua function? Why not the lowly boolean? Also, this desire to define property type using Lua notation, instead of just creating a custom definition block, leads to ugliness such as

child="_object_"

to define a property as an object. Ouch.

As for Define Commands(), I'll just re-iterate from my previous post that I don't understand why MakeInput() and MakeCommand() cannot be used outside of Define Commands(). Sure, some compile-time checking is nice, but you're not saving me from all sorts of other scripting bugs, so why this? Also, these definitions check whether a Command specified in MakeCommand() is actually defined. Why? What's so bad about a Command being sent that doesn't have a handler? Triggers allow this (and allow multiple handlers), yet Commands must have specifically 1.

And because I just can't let it go: why are these two scripts run in such a tight sandbox? Fine, it might make no sense to call SendTo() while defining properties, or perhaps not even Debug() while defining an input, but no pairs()/ipairs()? Am I really the first person to write "code" in these blocks, instead of just a handful of definitions and pre-structured function calls?

Scope

In Lua, everything is a global variable unless you define it as "local". In Metascript, too, your definitions have a global scope within a script -- this probably bites me in the ass once a week, since I tend to write a lot of recursive functions. The "within a script" is important, though. When first looking at Metascript, and Metaplace, and the idea that multiple scripts are attached to an object, you might want to think that these are all loaded into a shared environment as far as the object is concerned. However, this isn't true, and rightfully so.

Remember how

Trigger foo()

is the same as

function trg_foo()

is the same as

trg_foo=function() ...

? Well this would be problematic if all scripts shared the same scope, because it would mean that an object couldn't have definitions for a Trigger function more than once, as the latter ones would overwrite the former, and having multiple definitions for the same Trigger is a key, powerful part of Metaplace. This scoping is unfortunate, however, because this means if we use IncludeScript() to import a set of functions, we have to do it for every script that needs them, instead of just having it imported once for the object. This makes it awkward to have a library that's used throughout a set of scripts.

Also, the scope affects the idea of "self". Commands and Triggers, usually the largest portion of a script, have an inherent sense of self. But functions do not. Why? Well, they actually used to, I believe before we had IncludeScript(), so there wasn't a question of the context in which a function was being run. Not being privy to the way the Lua sandbox is being run, I'm not exactly sure why "self" can't still be defined in the environment of a function call, but it is no longer supported - you must now pass it in explicitly.

Userdata

Stock Lua also has a userdata type -- it's basically a C++ object -- so this doesn't make Metascript different in that regard. However, because every object in Metaplace is represented by a userdata object, how they interact in script is important.

Knowing the structure of the userdata is usually required, because there's no reflection or introspection by default; you can access self.foo if you know it's there, but if you don't, you have no way to ask (not exactly true, see below). Why is this important? If I don't know that self.foo is there, should I really be using it?

Well, yes, sometimes there are cases where iterating over everything is a good idea. One case is the set of stylesheet API functions that Metaplace provides. These let us look at the stylesheet (basically, the static portion of a world), to peruse the templates, places, sprites, scripts and modules. To do this without any prior knowledge, we need to be able to iterate over them all, much the same way that pairs() and ipairs() allow us to iterate through a table. In some cases, we have a special ._all_ property on the userdata, which returns a table which can indeed be iterated over with ipairs(). But why not all the time?

For instance, if I want to browse the Places in my world, I can access a userdata object with stylesheet.places, and if I know the name of one, I can index into this userdata, such as stylesheet.places["0:1"]. Alternately, I can use stylesheet.places._all_ and loop through them all, finding the one I want. And once I have a specific Place, I can get another userdata from it with someplace.tiles. Not knowing anything about how many tiles there might be, I don't know what to ask for specifically, so I try someplace.tiles._all_, and get back ... nothing. It turns out that instead of a nice table to iterate through, I have to basically guess the indexes of the tiles, with something like

t=0
while someplace.tiles[t] do
...
t=t+1
end

And worse, there are other objects, such as the Place itself, that neither have a way to iterate (with ._all_) nor to enumerate (with a 0->n loop), but that you just have to guess/know the properties of, hoping that the wiki documentation is up-to-date. Again, this isn't something specific to Metascript -- Lua userdata can have this problem too -- but it would be nice if we had the ._all_ table available on all accessible userdata objects. Alternately, all userdata objects could act as tables for purposes of using pairs() or ipairs(), if they really wanted to.

Metatables

Metatables (the "meta" being unrelated to Metaplace) of Lua are a very powerful feature, one that, in my opinion, turns Lua from a simple toy language into a powerful full-featured one. Metatables allow us to redefine our environment, creating a sandbox where a limited set of functions might be available. Metatables allow tables to take on new functionality, such as addition of two tables, or different handling of accessing values that don't exist. And metatables ... aren't available in Metascript.

My only guess is that the current sandboxing provided to the Metaplace scripts makes further access to metatables ... hard? Unwise? Dangerous? Confusing? I'm not sure, but it's a real shame that we don't have them. Granted, they're an advanced feature, and it's quite likely that very few Metaplace users will notice their absence, but heavier coders like myself certainly do, and working around them can be difficult, awkward, or near impossible.

Case in point: I'm writing a vector/matrix library for Metaplace, to help implement a new physics engine that I'm writing. Such a library must exist for Lua somewhere, right? Sure, there are some out there, but most (all?) wisely take advantage of metatables to overwrite the built-in operators, since it makes for much nicer and cleaner usage of such a library if I can say

newvector=v1+v2

instead of

newvector=v1.sum(v2)

which I have to do now. Even something as simple as making the vectors printable:

Debug(newvector)

is a lot nicer than

Debug(newvector.tostring())

Small things? Yes, but these only touch on what metatables can allow. Frankly, I'd like to stop there because I don't want to realize what other powerful things I cannot do in Metascript because of their absence.

Verdict?

All that being said, Metascript isn't a bad language. It's Lua at its heart, with a few surgeries to make it tick a little differently, some of which might have been required, or some only elective. This customized version of Lua hasn't itself prevented me from doing anything in Metaplace, apart from quickly porting in pure-Lua code from the internet; any walls I've hit have been with the Metaplace platform itself, and not the scripting language.

Monday, June 8, 2009

Namespaces

Metaplace's biggest strength has to be the Marketplace, where the community can contribute their own modules to everyone else, either free or for a cost of Metacoins, the current virtual currency being tested during Open Beta. This biggest strength, however, is going to become a problem if something isn't done to deal with the ever-crowding realm of namespaces.

In case you're not aware, a "namespace" is all of the available possibilities for naming something in a certain context. The names of the Metaplace worlds make up a namespace -- no two people can have the same "cleanname" world name (so, for instance, you cannot make a world called "MPCentralLive", or "UO", or any of the tens of thousands of other worlds that are made.) On the other hand, the display names are probably not strictly a namespace; I've not tried, but I do wonder if I can have the same display name on my world as someone else's.

The world names aren't TOO big of a deal. Sure, there might eventually be issues with copyright, or "prior art" in the case of names: if Metaplace is going to take over the world, then I'm sure worlds named "McDonald's", "Microsoft" and the like are going to be fought over, in the same way that domain names (mcdonalds.com, microsoft.com) were when the internet started growing. But the more pressing namespaces are from the scripting point-of-view, as more and more content becomes available, and the likelihood of problems increase.

Properties

Metaplace objects are all about their properties. Objects have a set of default ones, and different ones can be available if an object is a Physical object, or a Place, or a World. All of these built-in properties tend to be set upon creation of the object (such as "id"), or as they operate inside the Metaplace environment ("x", "y", "z"). These properties are accessed by having a reference to the object and then using dot- or bracket-notation to access it:


self.id
self["spriteId"]
GetObjectById(10003).vx
etc.


Attributes, which can be thought of as properties that are configurable for a template (from which objects are created), are also accessed with this same notation. This means, then, that you cannot add an attribute to your templates called "id", or "name", or "speed". But you could have your RPG game where all of the objects need to have a damage value, so after checking the Properties pages on the wiki, you can have that:


self.damage
monster[4].damage


Also, scripts attached to an object can also add properties. A module might define these in one of its scripts to allow passing of values between all of its component scripts. It might also use them to persist values, such as an RPG module that provides the ability scores such as "strength" and "dexterity". These are added in with the Define Properties() block, typically found at the top of a script.


Define Properties()
strength=10
intelligence=10
dexterity=10
constitution=10
wisdom=10
charisma=10
PersistProperty("strength") -- etc.
end



self.strength=self.strength+1


We're okay unless our RPG game has ability scores for "speed" or "lifetime" or a "type" feature.


As you can see we've already got concerns, so if you don't read the wiki property pages daily, you might, say, want to write your own physics library, and try to make script properties called "physics" or "speed" -- like I did. Or, you might want to write your own containment library, and feel that objects should each keep track of where their "container" and what they "contained" -- like I did.

Now I believe they've helped the issue a bit by having the compiler generate errors if you try to define script properties that already exist as template properties, and perhaps even attributes? I can't remember, because you'd think that once you'd made this mistake twice, and have wasted countless minutes, perhaps hours, debugging it. But while the script compiler can save you from attempting to use built-in property names, it can do nothing to prevent you from using properties that someone else is also using.


And this fact is actually taken advantage of, in a way I don't much care for. The Behavior Tool, in its latest form, recommends that any behaviour should have, in its script (and that's really all behaviours are -- scripts), a handful of properties defining that they are indeed a behaviour, name, description, and a few other future properties. But... wouldn't this be a problem once you have more than one behaviour?

It would, if these properties were used for anything other than identification. It's possible to pull out the values of these from the original script, even if these values get lost on the actual object due to being overwritten by other properties of the same name. In fact, these values are retrievable without the script actually being attached to an object, quite different from accessing properties via the dot- or bracket-notation.

I don't care for this "trick" to get values about the module. I think other methods should be used, such as labels, instead of this series of faux properties. I suppose it works, but I think it only fosters misuse of properties. Especially for those that are meant to take on per-object values.

Commands and Triggers

Properties aren't the only namespace to worry about - as was emphasized today, in fact. Newcomer tester Karkacabra was hitting a strange error, which quickly revealed itself to be a namespace collision -- with one of my own modules, no less. He had defined a Command called "close", which collided with the one that I had used in my languagewindows module. Admittedly, (especially since I'm writing this blogpost,) I should have used a better name, such as "languagewindow_close". And in my defense, Karkacabra should have also. *:^) In fact, we should ALL be doing so; the content from the Metaplace team is actually pretty good at this, prefixing Commands and Triggers with a something meaningful and hopefully less likely to collide.

Triggers are actually more of a problem for collision, because technically they DON'T collide -- it is perfectly valid for multiple scripts to define the same Trigger name, and they will each get called, with the order based on their attachment order. This is intended, and a very useful function -- but ONLY if it's intended. If I write a "use" Trigger on one of my objects, I had better hope that I had intended it for use with the Smart Object system in Metaplace, or else I'm going to see some odd behaviour -- not the wrong behaviour, as you're likely to see with colliding Command names, but additional behaviour, as all of the like-named Triggers get fired.

Workarounds

So, we know that if we start using verbose prefixes on our Command and Trigger names, we're going to help reduce the collision in their namespaces; the namespace is rather large, what with 50-60 or so characters per position in the name, and more length from a prefix just means more possibilities. But what about the properties?

Of course, the prefix system works just fine there, too, and I believe the Content Team uses it there. But I prefer a different method, which works, in my opinion, better.

Instead of defining each of the various or numerous properties individually, I define a single table as a property, with a suitably namespace-safe name, and then insert all of my properties within. Here are some of the benefits:


  • automatically grouped together by name, using foobar.propname instead of foobar_propname
  • requires only one PersistRuntimeProperty() call to keep all of the properties persistent (which also means none are accidentally forgotten
  • the property types do not need to be specified in the Define Properties() block
  • the table method allows easy deletion of properties, instead of setting to a "nonce" value
  • all properties for a module are easily iterated through
  • properties can be booleans, or functions
  • two modules, if they both try to define the same table property, won't fatally collide unless those tables predefine the properties (which is only necesary for default values)


The only drawbacks that come to mind are:


  • reading the script's Define Properties() doesn't tell you the properties used
  • reliance on the PersistRuntimeProperty() of a table, which has had a history with a few problems



I've been lightly pushing people in Metaplace to use the table property approach, only because I think it's nicer. What I will start pushing harder for, however, is the namespace consideration -- and I'll be the first to admit that I'm quite the culprit. In my defense, a lot of my code started off as "for me", so I would be aware of my own namespace usage, but of course as soon as I decide to publish it, or I start using others' modules, I need to be responsible.

Thursday, June 4, 2009

User inputs

I had mentioned previously that players have two inputs to their computer, and thus to Metaplace -- the keyboard and the mouse. Fellow beta tester KStarfire pointed out that I missed the joystick/gamepad. Does Flash support a joystick? I'm not sure, but I'll concede the point to him.

Metaplace uses a single method, the MakeInput() function, to define all of the inputs that a world understands. These are parsed at compile time to ensure they're valid, and passed to the client as a bunch of tags to tell it which inputs it should bother to send to the server. Here's its definition:

MakeInput(input description, input code, input event, input modifier, command string)

Where input description is something like "press I to open the inventory", the input code is "i", the input event is "down", the input modifier is "control" and the command string is "inventory".

Keyboard

Whether you're going old-school RPG with arrow keys or WASD movement, or just need a few keys to support inventory and status windows, the keyboard is a must. MakeInput() lets us define an event - that is, send a Command - upon a specific key press (up or down) with a modifier (shift, alt, none) for every need we have. Some of the keys have bigger "codes" than the letter they represent, such as "left" for the left-arrow key. This means we can do one-step-at-a-time walking, by just listening for "down" events for our arrow keys, or we can do walk-until-I-let-go walking, where we start walking on "down" event, and stop on "up". This sounds like everything we could want, but there are some limitations.

There are a bunch of keys that aren't supported. I won't spell them out here, but there's a bug filed (by me) in the Metaplace forums for certain punctuation keys that you just aren't able to listen for. This is problematic for me in my Ultima Online world, where I want to emulate the speech system of UO, where there's no chat box in which you click to start typing. This means that my current implementation (which you can try out) lets you type letters, numbers and a space, but none of your punctuation comes through, which makes you type like a ... well, like most of the people on the internet.

My UO world also points out another issue: to get this working, I had to make 26 lines of MakeInput() to handle each letter; another 26 for when I press shift (to get a capital version); 10 more for the digits; space, enter... that's 64 right there. If the punctuation was working, I'd have even more. And what if I wanted to catch every keypress possible? UO allowed you to map keypresses to macros, such as "control-e" for the allnames macro (which happens to work in my UO world, if you want to try it.) This means four modifiers (none, shift, control, alt), two events (down and up), and ... 100+ keys? That's 800 MakeInput() lines! In my UO world, I only have half of them (I wasn't interested in key-up events). Rest assured that I wrote a program to write those all out for me. The problem that this points out: there's no way to say "any" for the "input code", to say "for any keypress, send this command" or "for any shift-keyrelease, send this command".

Another problem that arises is that a given code/event/modifier combination can only have one possible Command that it will send -- you can't have "i" both bring up your inventory and cast the Invisibility spell. If you define a MakeInput() more than once for the same combination, it used to be the case that the client used a random one. Now it looks like the last-defined one -- the one in the script loaded last -- is the one that wins.

For a user creating their world completely from scratch, this shouldn't be a problem - they know what they want each key to do, and aren't likely to re-define the same combination again for another purpose (though I'll come back to this). The problem is more likely to appear when the Marketplace becomes involved, when a world-builder buys off-the-shelf modules that define MakeInput()s. As more and more content becomes available, the chances of these modules colliding is going to grow.

This has already occurred. KStarfire had a world where the spacebar was the "throw" command; after he had created that functionality, the avatar module -- probably the most ubiquitous module in Metaplace -- added a jump action to the avatars. And what key did they choose for that? That's right, the spacebar.

KStarfire, at that point, had two choices: either edit the avatar module, change the MakeInput() line where the jump was defined, and have to do this every time the module updated; or change his own code. But what if the "throw" command was one that he had purchased, instead of written himself? Another solution would be to allow the keys for every module to be defined by the user or world-builder, to have the MakeInput() commands pull their values from a user or template property. Unfortunately, the MakeInput() command doesn't allow this (future blog post).

So is there a solution? I think so. I think that a module needs to be developed that defines every single combination in MakeInput() and sends a single command from the client to the server when it happens. This Command would then fire a Trigger to the the user object, and at that point, any interested parties could listen for the Trigger, and based on configuration, decide if that matters to them. So the avatar system could allow the user, or world admin, to say that "control-spacebar is jump" and "spacebar is throw", and each module would handle things the way they should. Additionally, modules could, if they wished, share the same keypress.

I believe in this solution so much, in fact, that I've implemented it. Also, I was able to work around the limited environment of the Define Commands() block to come up with this little gem to save myself from typing an enormous list of MakeInput()s:


keys={"numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9",
"f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12",
"backspace","tab","return","pause","capslock","escape","space","pageup","pagedown",
"end","home","left","up","right","down","print","printscrn","insert","delete","help","numlock","scroll",
'-','=','\\','.','/','0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
"shift","control","alt","lshift","rshift","lcontrol","rcontrol"}
states={"down","up"}
modifiers={"none","shift","control","alt"}

for x=1,#keys do
key=keys[x]
for y=1,#states do
state=states[y]
for z=1,#modifiers do
modifier=modifiers[z]
MakeInput('keypress '..modifier..'-'..key..' '..state,key,state,modifier,(state=='up' and 'un' or '')..'key '..modifier..' '..key)
end
end
end


This generates every possible MakeInput() that Metaplace supports right now (with all of the missing punctation). It fires a Trigger key(modifier,code) for key down, and unkey(modifier,code) for key up. Now I can have code such as


Trigger key(modifier,code)
if code==self.jumpkey and code==self.jumpmodifier then
SendTo(self,"jump")
end
end


or even have a way to encode the modifier and code into a single value so there aren't two values to store and compare, and have a comparison function:


Trigger key(modifier,code)
if self.jumpkey==keypair(modifier,code) then
SendTo(self,"jump")
end
end


I really think that this approach is going to be inevitable, because the colliding modules is going to happen more and more, and the need for customizable keypresses, either to prevent collisions or to allow flexible worldbuilding (not to mention, to be able to support key macros) is going to be in demand. And, as I hinted at before, we might want to change the meaning of a key halfway through gameplay; for instance, I might want "i" to open the inventory in a non-combat mode, but when I'm in combat mode, "i" might cast the Invisibility spell. This could be one Trigger that handles the keypress, that understands both modes, or two separate Triggers (in different modules) that each handle a specific case, unaware (and uncaring) that the other exists.

I have one last thing that I'd like to see support for -- held-down keys generating repeated key-presses, much as we're used to seeing on computers when we hold down a key in our word processor. Some world might need this functionality (such as my UO speech), but others probably won't; once I add this as an option, I'll publish the above code as a small module for universal key handling.

One last thing about the keyboard: even with the Flash client in focus, some browsers out there rudely capture keypresses instead of passing them on to Metaplace. Specifically, the "control-c" in UO is meant to refresh your mouse cursor (there's a bug there I have yet to file), but in Internet Explorer 8, this brings up a menu or something. I've seen this on some of the other browsers, with certain keypresses, whether it toggles bookmarks or who-knows-what. This is an unfortunate issue that world- and module-builders will have to keep in mind -- the browser compatibility issues reach further than the web page!

Mouse

The mouse is a must in today's computing, giving us near-instant pointing and selection. Very few worlds are likely to get by without its use, largely in part to the graphical nature of the worlds (plain worlds such as Plain Old Chat.)

Unlike the keyboard, there are only a few different input codes available for the mouse:


  • mouse-terrain -- clicking on the ground (on a tile)
  • mouse-object -- clicking on an object


"click" and "double-click" are the only two events supported. Embarrassingly, I've never tried the "double-click" event, since the only one of my worlds that needs it (UO) was created before this event was added, and I ended up writing my own (in a similar manner to how I'll write the repeating key code). All of the modifiers are supported (none, shift, control, alt).

There are lots of things missing here. There's no way to distinguish where the mouse-click went down, and where it was released (I believe the location of release is what is sent to the server). This is one that I think could add some extensibility to a world's interface, and wouldn't increase the traffic at all.

Having the mouse location, either while holding down the mouse button or not, would of course be valuable. This would let us have draggind-and-dropping, of handling mouse-over/hover (future blog post) very easily, and to have the mouse cursor itself act as an agent in the game, as the avatar itself. We're told that the traffic between the client and server would be too large to allow this feature. I can certainly see that there *could* be a lot of traffic, depending on how often you sent the mouse data. But I propose that this is a setting we should be able to send to the client,

SetMouseLocationUpdateTime()

as well as provide a way to enable and disable the flow of this data, so worlds that need it can request it:

StartMouseLocationUpdates()
StopMouseLocationUpdates()

And of course, the client could have a hardcoded maximum of tags being sent in.


And last but not least, there's the fact that all mouse events currently represent the left-mouse-button only. No right click (nor middle click, nor sideclick?). This is a Flash problem, as I mentioned in the post on movement, but indeed a problem. As I had said, Ultima Online used right-mouse-hold (or right-mouse-doubleclick) for movement, and everyone associates right-clicking with a context menu. Other clients (a future blog post) could implement this support, of course, but I think it unlikely that we're going to see support in the Flash client. And, of course, even if other clients COULD support it, there's no way for the world to state that it's interested, because it's not an option in MakeInput().

So for now, workarounds need to be made. Luckily (perhaps oddly), double-left-click on terrain had no meaning in Ultima Online, so I've used that as my walk-to command (I use single-left-click as a "look" command.) As for workarounds for other missing things, I use ctrl-left-click as pickup/drop (instead of drag-and-drop). Though I also have a little hack for this, too, which I'll mention ... in a future post. Shift-left-click is, I believe, used to bring up the Behavior Tool, which acts in place of a right-click for a context menu, and the current avatar behaviour seems to go with single-left-click for bringing up a context menu on other avatars (for meeping, sending friend requests, offering gameplay, etc.)

I can also see a need for a mouse equivalent to the "every key" module I mentioned above, letting world owners define the mouse meaning they desire to various actions: if I want single click to be "look", and double click to be use, I should be able to set that instead of be forced to use whatever the module-writer decided.


Overall, I'm a bit disappointed with the mouse support, because it's really the primary interface for many. The modifiers can help us for now, but I really hope that, once all of the bigger pieces of Metaplace get done, the mouse support can be revisited.

Joystick?

Is this so far-fetched? Not really; I have no idea if Flash can support joysticks, or gamepads, but custom clients sure can, but we still hit the problem of having no support for them in the MakeInput() call. And this brings up something that has stuck in craw for a bit: the special nature of MakeInput().

I had planned on talking about this in a future post, but I really don't understand why MakeInput() must be in the Define Commands() block. Or at least, why it must ONLY be in that block. I can see a desire to precompile this, to ensure that the definition is done correctly. Or can I? Every other API call checks this at runtime, not at compile time, and lets the world owner know in the Debug or Log window, and lets the user know by just not working. Why can't MakeInput do the same thing? Why can't I call MakeInput() later in my script, after asking the user to define some keys, of after the user's preferences have loaded? Why can't we call DeleteInput() -- there's a tag ([W_DELINPUT]) that exists for when a script is unloaded, which removes a defined input, so doing so after the world is running, and a user is connected, is certainly possible. Why can't we add inputs after we're up and running?

Maybe there's a good reason, maybe it goes against the design of the system, or maybe this was just oversight. Some day I hope to know! Until then, though, I hope my module will be a viable workaround, or that the collision of inputs doesn't become too big of a problem, too soon.

Tuesday, June 2, 2009

Movement

I would say that, apart from "seeing", movement in a game or virtual world is the most important feature. While I can come up with a few games (Boggle) or worlds (chat room) that don't require the idea of player movement, they're the exception and not the rule. Given this, you would expect that movement would be a solid, ironed-out subsystem of virtual worlds in general, and Metaplace specifically.

Unfortunately, as recent discussion on the forums has shown, that's not quite the case. Sure, your starting world in Metaplace has a nice click-to pathfinding script attached, but that doesn't provide a solution for everyone.

Inputs

Not counting voice control or some telepathic USB device I don't know about, computers have two methods of user input: the keyboard and the mouse. Metaplace gives us access to both, for the most part, which means we have a choice on how we get instructions to our game world, and thus have a choice on how one might move around in our world.


The mouse

The mouse is probably the most common input method, since at a glance we can see our world, where we want to go, and can deftly move our mouse cursor there and simply click. Getting this click event is easy enough to do in Metaplace. But what about other mouse-based movement? In Ultima Online (you'll eventually get used to me using it as a reference) you did not "walk to" with the mouse, but rather "walked toward", by using the right-mouse-button on the screen and holding it down; the distance that the mouse cursor was from the player also let you decide between walking and running.

Unfortunately, this isn't possible in Metaplace, for two reasons: we don't have access to a right-click event (this brings up a Flash menu in the client; there are apparently hacks out there to allow right-clicking in Flash, but they aren't used for the Metaplace client); and we don't have access to mouse-up versus mouse-down events (and mouse-location), just mouse-clicked. This isn't a Flash limitation, from what I understand, but more a consideration of the bandwidth involved with sending the mouse location so-many times per second.

Still, we've got the click event, which lets us get our intentions across pretty well; we're also able to modify that with keys, such as ctrl-click to run there, or shift-click to sneak there.

The keyboard

The keyboard typically has two forms of movement: a "step-based" method and a "continuous-walk" method. There are also games where you control a cursor with the keyboard, but I suggest that that's only used when a mouse isn't available; and I suppose that you could have "direct" movement to waypoints using letters or numbers, but I'm going to happily ignore that idea for now.

In the step-based movement, players will press their arrow keys or WASD keys once for each "step" they wish to take; this would likely be in a tile-based game, where a discrete step is perhaps something visible in the world, and it represents the smallest unit of movement in the world. The continuous-walk movement instead listens for key-down events and key-up events, so holding down the arrow key will keep you walking in that direction until you release it (or until the game decides you can go no further, due to movement "points" running out, obstacles, or consumption by monsters.

The continuous-walk method is really just a shorthand way of doing the step-based movement, allowing the player to hold down the key to represent repetitive, consistently-spaced key presses. This means that continuous-walk also has the idea of a "step", but it's more likely that these steps are smaller: it's no big deal to quickly walk across a 64-"step" tile by holding down an arrow key, but you certainly wouldn't want to have to press the arrow 64 times for the same effect! The hold-and-release of a key allows the player to stop whenever they want, but there might also be the need to support the larger steps anyway, where releasing the arrow key still has the player continue to move until they reach the next full tile. It all comes down to the needs of the game world.

Movement

Once we know where we want to go (or at least, which direction we should start heading), how do we actually move? We could instantly appear there, we could slide across the screen in a direct line, or we could follow some sort of path around obstacles. Each of these methods has their place, depending on the world or game. Metaplace provides four ways to get you around.

MoveObject

The MoveObject() function is an instant teleport. No delay, no motion, just here one instant, and there the next. This might be used by simple board games, moving pieces around, though you may want the movement to be animated (if only for your opponent(s) to better see what your move was). It could be used in a simple RPG, stepping from tile to tile, but again, it might look better to have them slide along instead. Teleportation! There's one that surely needs to use MoveObject. The nice thing about MoveObject is that there's no issue of collision detection, because we're not moving through anything; however, it if there's something already at that location, MoveObject won't stop you from piling objects on top of each other, so if that's a problem, it needs to be handled in the code. MoveObject doesn't allow you to move to a blocking tile, however. And there's no issue about timing or animation, because it's an instantaneous event.

SlideObject

SlideObject gives that nice bit of animation to the game or world, allowing you to move your objects from here to there in a specified amount of time. Of course, you might still want to animate the sprite to make it look like it's walking, rolling or otherwise ambulating, but the movement there is nicely handled for you.

There are a few things to note: as far as the server is concerned, the object is instantaneously teleported. The client is told about the sliding, and does the job of moving the sprite along the right path at the right speed. However, the object's location along that path is always accessible, correctly, from the server. So what, then, does it mean that "as far as the server is concerned, the object is instantaneously teleported"? I believe this means that, for any subsequent requests by other objects, that location is considered occupied, such as if another object wanted to MoveObject there. I've admittedly not tested this out, yet, but that's the only meaning I can imagine.

Also, SlideObject will allow you to slide onto tiles that are blocking. This can be a good or bad thing. In the new Rocking the Metaverse world, the bouncers get you up to the VIP section by sliding you there, past all of the blocking tiles on the stairs. On the other hand, a movement system using SlideObject would have to look for blocking tiles manually to prevent the player from wandering over them. Also, SlideObject will allow the physics system (below) to trigger hit() and hit_by() events, if a collision takes place during the slide. If the blocking-tile behaviour of SlideObject is acceptable to you, this is a good way to go.

Physics

The Metaplace engine has a built-in physics system. Instead of specifying specific a location to move to or slide to, instead we can define a facing (direction) and a speed, and let our player keep going until we change these values. Physical objects are affected by quite a few things: they will fire the hit() and hit_by() Triggers when they hit objects, allowing you to decide what should happen; blocking tiles will fire a bounce_tile() Trigger, and also reverses your direction for you; and the world edges fire a bounce_border() Trigger, and again automatically applies the "bounce" off of it. There's also a facing() Trigger fired whenever the direction changes; this is useful for changing your sprite to rotate to another direction.

This automatic bounce effect can be a problem, though, if that's not the behaviour you want. It works well for a space maze game, like Uberspace, or an Arkanoid/Breakout game, but for other uses we might wish that movement in the direction of the blocking object was dampened down to zero, just stopping movement in that direction. Of course, that's what you can do with the bounce_tile() and bounce_border() Triggers, but I would almost expect the two methods of handling it to be swapped -- the bounce to be coded, and the stopping to be standard. Or perhaps a flag?

Alas, these aren't the only concerns with the physics system. Objects tend to "drift", where the client's representation isn't quite the same as the server's, which can lead to inexplicable collisions (the server sees the collision, but the player's view in the client doesn't match or make sense) and to sudden lurching movements (when the player changes the direction or speed, and the server suddenly updates the client with some out-of-sync location information). Additionally, detecting collisions between blocking tiles or the corners of the world boundary don't quite work, allowing objects to escape into the unknown.

Still, if you have good control over your physical objects, and use the physics system for short, immediate movements, it can provide more flexibility than SlideObject. The fine-tune control over direction, speed and even acceleration might be easier to do with physics than it is using SlideObject, where you might have to convert angles and slide times or perform multiple slides to get a nice effect.

pathfinding

The pathfinding system is what you get with most of the worlds that you create in Metaplace, generally tied to the mouse click. This system uses an algorithm called A* (a-star) to try to find the best path from where you are now to where you want to go, avoiding blocking tiles and tiles with blocking objects on them.

Whether or not a path is found, a Trigger is fired, either path_begin() or path_not_found(), so you can either start animating your walk, or give a loud BZZZ if the player cannot get somewhere. Upon reaching the end, a path_end() Trigger is also fired, to allow the walk animation to be turned off, or to allow some NPC to pathfind to its next location (perhaps because it's walking a circuit, patrolling).

The pathfinding system uses the physics system, which means that on the way, you can receive hit() and hit_by() Triggers, as well as get facing() calls. In theory, you shouldn't receive any bounce_border() or bounce_tile() Triggers, since the path has walked around those for you. Finally, you can also specify a "mode", which tells the pathfinding system that it can or cannot walk across diagonals; this is useful if you want to avoid the appearance of a collision when there isn't really one (a future post) -- you can see some good diagrams on the PathToLocation() wiki page.

The best solution?

From the four, it sounds like the pathfinding is the best way to go for most uses, especially if you need to avoid blocking tiles, if you care about collisions, and if you want the player to be able to single-click their way around. It can also be tied to an key-press movement system, where with each press, the system attempts to pathfind one tile left/right/up/down. A key-holding continuous system is a little trickier; based on the speed at which the pathfinding gets the player from tile to tile, you could have your movement code continuously calling the pathfinding system again, from within path_end(), if the key is still being held down. This would mean that the animation should not be stopped, if it exists, which might cause some collisions between multiple modules trying to handle the path_end() Trigger. Attention would have to be paid to the smoothness of the motion, to see if multiple pathfind calls, chained together like this, would appear as a jerky, stop-and-start motion.

Pathfinding, because of its adherence to blocking objects, isn't useful in worlds where you can ignore these features, such as when you can fly over terrain. As mentioned before, the bouncer in the Rocking the Metaverse world has to SlideObject you into the VIP room, because pathfinding will NOT get you there (as you can see for yourself if you click up top). And, if you're looking for the instant-move effect, pathfinding might be able to fake it with a high enough speed, perhaps... I haven't tried!

I think the marketplace needs a handful of movement systems available, so those who know what they want can piece it together. Whether it's mouse-clicks, key-presses or key-holds, and moving, sliding or physics, there's no reason we can mix-and-match these together, or even have a single module that allows the world administrator to select their world's manner of movement. Unfortunately, over the span of the alpha and beta testing, there have been a variety of keyboard and mouse movement systems, using move, slide, physics and pathfinding, each at one point being the "standard" movement script provided with your new world. It would a shame if the click/pathfinding system being used by the avatars, quite obviously the most popular method now, becomes the only way people know how to interact with their worlds.

Friday, May 29, 2009

Commands

A "Command" in Metaplace is like an instruction or action from the user. Clicking on the ground in a Metaplace world sends a Command ("walk_to"), pressing a key sends a Command ("inventory open") and clicking a button in a pop-up window sends a Command ("purchase confirm"). These are all examples of "user-defined" Commands, where each of these, "walk_to", "inventory", "purchase" would have to be defined in a script attached to the user's "object" in the world.

There are also "system" Commands, which for the most part, can be thought of as "meta" commands -- "meta" means "above" or "beyond", and is typically used in the sense of something thinking or acting "outside of the box" or interacting with its own reality (in Dungeons & Dragons, the term "meta-knowledge" is often used to refer to knowledge the player's character has that it shouldn't, but does because the player has it, such as the fact that that dragon is immune to fire, even though the character should know nothing about dragons). The system Commands, then, usually don't deal with the world content itself - walking around, opening inventory or confirming events - but modify things external to the gameplay, such as add new graphics to the world or restarting the server. These commands are built-in, not written by users, and are distinguished by their leading slash, such as "/create_sprite" or "/restart_server", and are generally not (knowingly) sent by the user, but rather are sent, for the most part, by the world-building tools.


The idea that Commands are instructions from the user, then, means that, in theory, they're not something that non-users should need to send. This is emphasized by the fact that Commands are defined in scripts attached to the user template, and can't exist in the script attached to this monster or that rock. Monsters and rocks don't give Commands, only users!

Since the Metaplace client is the user's interface into a Metaplace world, it seems to make sense that the client is the only thing that would need to send a Command (on behalf of the user's actions of clicking and typing. However, during alpha and beta testing, some scripters found that there were some cases where calling these same Commands from withing a script seemed reasonable: if the player walks up to an NPC shopkeeper and says that he or she would like to buy or sell some goods, it was nice for the "shopkeeper" script to automatically pop up the user's inventory for him or her. Since we already had a Command set up for this (for when the user pressed "i" on their client), we could use a built-in function called DoCommand(), which would tell the system to execute the Command just as if the user had asked to.

The DoCommand() was also able to issue system commands. This meant that we could have code that could automatically create sprites, or remove them; that could re-configure object templates; or that could enhance the build environment with extra tools.

Unfortunately, we lost access to DoCommand(). The reasoning makes sense: with more modules available on the Marketplace and more users arriving all the time, it's just a matter of time before malicious code comes along.


Malicious modules are going to happen. I think it must fall under some sort of law of averages or something, but eventually there will be someone that comes along and writes a Metaplace script that does something different (or in addition) to what it claims. I, myself, think along these lines, perhaps because my line of work involves security, or perhaps because I have a "hacker" mindset at times, and admittedly like to "cheat" at times. But the majority of malicious code that can exist can, at most, just affect the world's operation, removing monsters, clearing highscores, or providing superuser rights. I say "just", even though these can be devastating to a world, because I don't think these compare to the damage that could be caused if someone had access to system Commands in a world. Even with peer review, a rating system, and distrust of closed-source modules, there are still ways to sneak in some nasty code (a future post).

While script access to the slash commands through DoCommand() provided the ability to make all sorts of interesting modules, I can definitely understand why it had to be removed. It's one thing to delete all of the trees you painstaking placed in your forest realm, but it's another if I remove the template completely, or export your code without your permission, or include even more modules... it doesn't take long to come up with some evil.

And access to the user Commands from script has also been removed. I believe the motivation behind this is because there now exist modules that interact with the user in a "meta" fashion -- things such as in-game purchases using the metacoins, or accepting friend requests, or meeping another Metaplace user -- are now possible. These aren't actions that are world-specific, such as popping up the inventory or buying a sword, but affect your global Metaplace self. And if a malicious script could automatically buy 1000 balloons for someone, or friend every user, or flood-meep everyone, without the user's permission... well, again, it'd be one thing if it was something just in-world (it made you automatically sell all of your equipment to the shopkeeper), but it's something completely different to affect the user at that extra-world level.


So I understand why DoCommand() was removed. But are there legitimate uses for it?

Luckily, there's an easy solution for the user Commands: turn them all into Triggers (so scripts can easily call them), and have the Command that is called by the user (via the client) also call the Trigger. The numerous DoCommand()s I had in my UO scripts were all changed over to this method in less than five minutes.

And what about system Commands? Well, there's now a DoSlashCommand() function, but it's restricted to "privileged" scripts, which means specially-marked Metaplace-written scripts. What about the rest of us? I have three main reasons to have scriptable access to system Commands -- slash-only Commands, batch Commands, and in-world tools.


Slash-only Commands means Commands that don't have a world-builder equivalent. While many/most of the system commands can be activated by some part of the build tools, there are some that cannot (and worse, some that used to be under the old, beloved, "JS tools" from the alpha days). Things such as parallax and data templates (future blog posts) can only be done using slash commands (not precisely true -- some of the parallax and data templates stuff can be done from scripting as well, but not from the build tools). The command-line interface to Metaplace isn't friendly, so being able to script these operations instead of typing them by hand would be handy, especially if you need to do large batches...

Entering batches of Commands isn't really possible with the command-line, because it only takes one line at a time, and means that you'd have to cut-and-paste each line in. Slow, error-prone... not fun. The creation of my UO test worlds is done through a lot of automation, and involves a lot of system commands that upload sprites, configure them, set up tiles, place objects... this is hundreds of commands that can no longer be done from a script. Another example is the avatar system...

The character customization system (future blog post) is not very user-friendly at all. Not only does it require a lot of slash-commands to be entered manually through the command-line, but even the scripting portion, and the data template portion, can be error-prone and difficult. Having an in-world tool, an avatar wizard, could help people create their avatar module by letting them provide the easy stuff (images and animations), and having the wizard automate all of the error-prone work.


So how do we trade off script security and scripting flexibility? Is there a solution? I think there is, and I think it's relatively easy: allow local scripts to use DoSlashCommand(). This means that imported modules don't have access to it, so the only malicious code is something the world owner adds. It allows users to write a script to do slash-only and batch Commands. The only thing that it wouldn't fix is buying an in-world wizard for things like the avatar builder. Something like that would have to be cut-and-pasted into a local script and run from there, which wouldn't be a good practice to get into, but at least it's a workaround.

I don't know if this is being considered as a solution, or if another one is coming. We're told that DoCommand() was "deprecated", but that usually implies that one method is being phased out because a new method is being brought in. I'm still waiting for the new method!