Wednesday, June 22, 2016

Behavior Trees

One of the readers here (at least I hope you're still reading ;) ) hinted me quite a while ago about "Behavior Trees". No, that is not a tree where you learn your dog how to behave by punishing every time he lifts his paw. Although you could program such a scenario within a Behavior Tree. Like State-Machines, it's sort of a modelling method + programming guidance. Yet, quite difference than State-Machines. It wasn't until now I learned more about Behavior Trees -or "BT's" for short-, but I didn't forget about your advice, Sander!


I won't be telling how to code them in full defail, as there is enough detailed stuff out there:
I'll just show a simple but practical example, and have a chat about it. If you heard about BLT sandwiches, but never about BT's (like me), this may trigger you into reading the link I just posted. No pesky difficult algorithms, but fun stuff! All righty.

Artificial Fuzz

Let me begin explaining some pitfalls when trying to program A.I. in an ordinary, “on the fly” way. The way you would probably try the first 10 times, concluding things turned into a big mess as the IF's and BUT's stacked up. A.I. is complicated, even when your foes aren't supposed to be rocket scientists. A.I. is mostly about decision making, and executing those decisions in a “human way” (or Alien way, Horse way, whatever the character). Clear enough, but when to decide what? Depends on a lot of input signals and context.

Usually it starts pretty simple. A guy with a shotgun. He should shoot when he sees you, reload when out of ammo, and die when he gots hit. No fancy state machines or whatsoever required, right? Yeah, in that case... but this makes a boring enemy. How about walking? How about smoking cigarettes if there is nobody in sight? How about NOT cheating by killing you instantly as soon as he spots you? How about gently saying "AARH @SS F#CK SON OF A B!TCH!" when getting shot in the groin?

And we can keep on going. Getting hit by a BB-gun or flamethrower should result into different “behaviour”, and also picking positions to move over depends on a lot of context. When trying to attack, a foe should try find a partially covered spot with sight on the target. When trying to reload, a fully covered spot suits better, unless it's too far away maybe. And when trying to take a dump, a room with a toilet is probably an excellent good idea.

And now I'm only talking about simple shooter combatants. Imagine you're making The Sims. Or pedestrians that should act realistically (read not randomly crossing roads & ran over by a truck) in a GTA world. AI usually goes wrong -also in AAA titles- when a NPC (Non-Playable-Character) makes weird choices based on bad parameters, or keeps persistently trying to accomplish an impossible or totally unimportant goal. You must have seen guys running into a wall endlessly, or foes refusing to stop taking that dump even when a T-Rex is knocking on the door.
Priorities...

BT's (Behavior Trees) won't fix these issues by nature, but being a modelling method, sort of, you can at least clearly visualize the whole decision-making process - and see where they took a wrong turn, or ended up clueless. And more importantly, it's fairly easy to re-route the logic, or add branches/additional choices or conditions. In contrary to common code, that turns into a gigantic mess quickly as the exceptional cases, IF's and BUT's pile up relentlessly.

One more problem with regular code, is the actual execution. It takes a moment to prone, walk from A to B, to reload a weapon, or to take that dump (I'm sorry, can't resist). Timing man! Sequential code just tries to run everything ASAP by default, so you have to smear your execution over multiple cycles. Using (lot's of) timer variables, signal flags, waiters, and so on. Waiting X seconds before performing the next action isn't hard to code, but again the magnitude of things can become a problem quickly. Dozens of timers, eventually shared amongst multiple actions to make things worse. It's too easy to make mistakes, do 2 things at the same time, or screw up sequences with bad timing. Making your guy act as if he gets electrocuted all the time.

Usually you would make a list with tasks, and execute them one by one. But, now the real difficulty comes: our situation is Dynamic. As a computer foe, life is never certain. One moment you’re carrying cement bags, the next moment you’re fighting giant scorptions. Some tasks need to overrule other, but then again be careful not to mess up. You still need to walk –no run- over to the Player before you can slap him. 


Behavior Trees

BT's are there to help. Throw away all that messy A.I. code, and start modelling buddy. And no, I’m not talking about doodling some behaviour patterns on paper to code them later. The model(file) will actually replace the code! Doesn’t mean you don’t have to code anything anymore, but it will be limited to running the BT plus making small “building blocks” to construct that BT. I’ll explain.

Model made with this online tool: http://behavior3js.guineashots.com/editor/#

Look at that picture, and tell yourself what happens here. It’s sort of a decision flow, starting at the left (although if you google BT's, they often to top-down). Probably you already figured, but basically it checks if it's hungry or tired, and if so, it executes a sequence of actions. Being placed higher, hungry gets priority over being tired. For starters, we can separate a BT in four types of nodes:

·         Composites (see the blue ones)
Elementary blocks to control the flow. They can run actions parallel or in a sequence, prioritize, or pick a random sub-node to execute. Composites do not actually actuate your NPC, but regulate the flow.

·         Conditions (see the green ones)
Basically the IF’s. Targer reached? Hunger more than 50%? Do we have the SkullKey item? Is Jack an asshole? That kind of questions. These (leaf)nodes are used to help prioritizing, or to interrupt a sequence at some point.

·         Actions (see the orange ones)
These (leaf)nodes actually actuate your NPC. Move over to X. Rotate, jump, salto-kick. Play a sound, do an animation, squeeze a fart.

·         Decorators (not visible in picture)
Used in combination with Conditions. Inverters (IF NOT x) or Delays to suspend actions.

Node that I just explained the very basic blocks. It’s up to you to add extra Composites, Conditions, Actions or Decorators, eventually with a list of parameters. For example, an action like “FindFridge” may require a maximum radius or zone, so we don’t loot the neighbors fridge. Now this where you programming skills shine; your engine/game/program has to offer a box of Lego bricks. A Shooter game would typically offer movement, aim, shoot and cover nodes, while The Sims is more about, ehm, looting fridges and making out in the bubble bath.

So, when implementing BT's, there are basically three components to deal with:
1.       The BT itself
Using a modeller program or even better –your own build-in editor-, producing BT files. Could be saved as XML for example.

2.       Set of Nodes provided by your engine
As explained above, you’ll need to code each type of node. In the end, you still need code to animate that robot, or to find a path through your maze.

3.       Engine that has to load BT & Run BT’s
Load a BT, and let your NPC’s make use of it. That involved logic that traverses the tree every cycle (sometimes referred as "Ticks"), executing the nodes that come accorss. Since a lot of actions may also rely on variable data, BT's are often accomponied by "Blackboards"; a (per entity, or global) storage space for custom values.




Johny Five routines

Now that BT is too simple, as usual with demo-models. A real game BT would have a lot more branches and nodes. So many, that you’re still having a hard time to comprehend. But that’s ok. Unless you’re a Jellyfish, you won’t able to model your own brain on a single paper, now would you? Still, using BT’s has a bunch of advantages.

First of all, the blocks you make are robust. Unlike on the fly/messy A.I. coding where you quickly end up taking dozens of scenario’s into account, smudging the “core business”, these Condition and Action nodes are really focussed on a single, simple task. A node that says “fart” just does that. Nothing more nothing less. It doesn’t check if your girlfriend is around, or if you had beans for diner. No! You –the A.I. designer- should do that prior to the action “Fart”, with other elementary nodes. That makes it fairly easy to code robust, proven, nodes. A simple node doesn’t do much, it’s all in making combo’s with others.

Although, nothing stops you from making more advanced nodes of course. Navigation and picking targets is a good example. It all sounds pretty simple, but there is a lot of logic behind that stroll from A to B. Why pick B? Can we reach it? What’s the shortest or best-quality route? And once the Nav-System has been set up, we still have to actually move our ass. Animate, rotate, climb stairs, and so on. We could spread that over many different micro-nodes, so we have FULL control over the entire procedure. But… it would be tedious. Instead we could compress all that action into a single, or fewer nodes, and use some additional parameters. For example, when picking a target, we could define parameters like “maximum distance”, or “what kind of target are we looking for?”. A fridge? A bed? Toilet? Human flesh maybe? And when we call “MoveToTarget”, we could define a speed, or pattern. Should we rush, sneak, or just chill out, not caring about a thing? Again, your engine decides what kind of parameters there are.

Long story short, lesser advanced blocks makes it easier and quicker to model behaviour, but limits your freedom. It’s up to you. Bear in mind though that Behavior Trees aren’t just limited to gunslingers and Johny-Five. Behavior Trees lend themselves well for robots, animated machinery, or puzzles. Check this door:
Yeah, even doors have a "Behavior". Of course we could hard-code all that stuff into the engine, but there will always be an exception. Especially if you're making weird puzzles, or want artists to use your engine to make their own stuff. And talking about artists, your art is to provide a toolset that is flexible, yet not too complicated. So, if well done, Behavior Trees allow non-programmers to create crazy scenario's without having to dive into the bits and bytes.


One last node I should make, is that you're not restricted to use a single HUGE BT. Of course different characters can load different BT files, but you could also chop it up into smaller modules. For example, a "Idle", "Walking", "Combat - weapons" and "Combat - fists" module. Monsters may use the same melee combat melee than people, but lack the Weapon module, and have different "Idle" behaviour. Where humans smoke cigarettes, chatter, scratch balls and take a dump, monsters eat flesh, fight each other, scratch balls, and also take dumps but without moving to a bathroom first. Apologies. Likely, a "combat" module can be split further into sections like weapon handling, finding cover, throwing grenades, and so on.



Seat-2D2 demo

Well, let's finish showing another model. Geared towards Engine22 this time. Disclaimer – I must admit I just started, so don’t expect rock solid awesomeness here. But as you can see in the little movie, it works J Without programming ANYTHING. Well, except for all the lower level engine stuff + a toolset of nodes to pick of course, but I mean nothing was programmed to make that “seat” chase me & make R2D2 sounds.
All these "PlaySound", "Rotate" and "Move" nodes have been implemented in Engine22, each with a bunch of parameters eventually.

So, what happened here? Every cycle the seat checks if it can see me(“Player”), by shooting a ray towards me. If the ray is interrupted or out of range, the seat will fall back to idle behavior, which results into either waiting, making noise, or moving short distances into a random direction. If it sees me –with a slight time delay, meaning it needs to see me at least a few seconds in a row- it will rotate towards me, then move forward, eventually correcting its angle a bit more as it slides. It keeps a minimum distance of 2 meters of me. It wants to move to me, not INSIDE me. And then it makes a cute sound.

Results? Here you go. Although Engine22 still lacks a tool to create and debug / visualize these trees (I imported the file export from http://behavior3js.guineashots.com/editor/# ) it was quite easy to make this. It required a brain-reset to jump over from traditional programming to modeling, but once you're at it, it's fun to do.


As you may notice, the graphics aren't exactly what they used to be, compared to previous video's. That is partially because Engine22 has been re-programmed (thus a lot of shaders / effects / content is missing), and partially because these rooms simply didn't get a lot of love yet. Instead of pimping the graphics, I really try to focus more on making an actual playable game this time - hence the "working" player-physics and "A.I." you just saw. Of course, chasing seats won't make a thrilling game, but it's a start! 

And-yes-of-course, we will improve these rooms. But that requires artists, and last five years I learned it's very hard to find or keep artists if you're still far away from anything solid - a playable thing. Unfortunately, making a more robust engine, editors for the artist, pathfinding routines, or better physics to avoid falling through floors isn't the kind of stuff that generates awesome screenshots to show here. Which explains the lack of material lately here. But trust me, a lot of coding is going on. Hope you understand!



Sunday, April 24, 2016

Walk the line

Most programming-time on this project, disappears into improving graphics, making the editor a better man, or fixing bugs. Although engines, programming techniques and strategies get better and more robust every time you try, stuff still feels like a Jenga brick tower sometimes. Shove a new shader in here, and crap falls out at the other side - without you noticing until a week later, then wondering what the hell happened.

But I shouldn't forget, that we're making a game here. Or trying to at least. Making something you and me can *play*. So, once in a while, I step away from graphics and dive into game mechanics. A whole different area, I must say. Whatever game you're planning, the fun part is probably making your foes even smarter, designing puzzles, tweaking guns, testing what happens if you drive that race-car into garbage cans, et cetera. But... you're too far ahead maybe. Because a game begins with decent controls & basic physics.


Sure thing doc. But you know what? Making them Right, is pretty damn hard! Even if you have a proper physics library. Certainly because game-control-mechanics often have to cheat, overruling standard physics, collision and gravity rules, rather than using them. Getting a box tumbling down the stairs isn’t too hard. But getting a 200 pound guy moving upstairs is. It will bump, get stuck, rocket-jump into the sky, or more likely; stick on the ground like an Easter Island head.




Shoe laces thight
I take good controls for granted, 99% of the games have them right more or less, nowadays. Though the foul memoires of broken games haven’t faded completely. How many platform games fucked up, 30 years ago? Games didn't have too many problems stealing the ideas and visuals of Mario Bros. But copying the controls and mechanics was a whole different league. The player character being too fast, as if feeding an ADHD kid 200 red M&M's, six cola, and a line of speed before going to mcDonalds. Controls too slippery, as if ice-skating on olive oil the whole time. Too stiff, as if moving a 1 ton statue with the friction of a Thwomp. Too artificial, as if moving a rectangular sprite in horizontal or vertical patterns over the screen. Too sluggish, as in having a jump-button, but Arnold Schwarzenegger being too old to jump over a 30 cm obstacle, making it useless. Too unrealistic, as in total absence of any physical rules. Too realistic, as in having no control at all once you're airborne, realising you miscalculated the jump and heading into the abyss imminent.

Many old platform games failed miserably, because of unbalanced controls, or a level-design with impossible jumps. Or both. And not to mention the weird bugs. One thing I hated, was sprite-physics-anorexia. What I mean is that, even though the player sprite is 1 meter wide, its collision hull (an invisible shape used to test if it hits another shape) seems to be much thinner. Your feet would land on the edge of a platform, yet you would still fall down because the hitbox of your player missed the jump. It sucked, it seemed relative easy to fix, yet dozens of games screwed up. Also the opposite happened. A bumblebee would fly one feet over your head, yet still kill the player instantly because its oversized hitbox caught it.
               
Why L ?!! Well, I can tell you why. Again, because making physics is hard-core stuff, even for a platform game. I can tell, because I had the same weird shit in my 2D-hobby-games, where players would end up in the middle of the wall, raising upwards, straight out of the television. Detecting a "hit" isn't too bad (in 2D), but deciding what to do next, and making a 100% waterproof system is. Velocities, bouncing off, material frictions, taking the angles into account properly, and a big dose of magic numbers. 
Having a built-in jump-tester in the level editors would have saved dozens of broken joysticks and frustrated crying kids. But probably a lot of those shitty games didn't even have visual editors back then.


3D Crapdoll physics
The big transfer to 3D didn't really help either. Although a game like -of course- Mario 64 did remarkably well for one of the first serious 3D platform games with advanced moves, I couldn't count the number of awkward stunts on a hundred hands. Soldiers would drop through the deck of a moving boat, sink like a brick to the ocean bottom, then warp high into the sky to fall down to their deaths eventually (yes, I'm talking about Hidden & Dangerous here). Ragdolls would start spinning up to hyper speed, tearing their limbs apart, because they got hit by a closing door. Dead guys float in the air until I touch them with a fingertip, as they finally drop peacefully straight down (Fallout 4 + plenty of other modern games). Wrecked cars being launched to the moon after hitting that wall at the G-spot (GTA). Getting your head stuck through a wall, horrible clunky vehicle steering, flying in Limbo, …

Should I go on? Yeah, why not.  Giant dinosaurs worming through a 2 meter radius cave portal. Player not being able to proceed because required object used as a step-up fell through
the floor. Tough action hero’s that would drown instantly once being in 40 centimetres deep water. Cannot reach key of dead guard as his ass lays half inside a concrete wall. Being able to disable gravity and collisions by taking a wrong step somewhere in the corner of a map. Not able to get off the sofa after jumping on it because the ceiling is too low (Tower22). The list is endless, and if you look on Youtube, you quickly waste another few hours on watching this kind of stuff. Sometimes it works out well, like the Quake1 Rocket-jump ability, or having fun with flying cars in GTA. But most of the time it’s just, well... stupid.


That looks... painful. I think.

And at this point, T22 is still tormented with the same kind of bugs as well. But not the funny type of glitches. More the types where you want to smack the keyboard through a door, and decide to become a garbage man instead of a game-programmer for the rest of your life.  As you may know, Engine22/Tower22 uses "Newton" (not the guy, the code library) physics as a base layer. I'm not too sure about recent trends -to me it seems physics engines are a bit out of development last years-, but it’s free, and Newton was said to be quite accurate. Accurate my ass, when that stupid ball falls right through the floor again. Probably my fault somehow, though I often really can't explain the quirks. It works, works, works, then it suddenly goes wrong.




Role of a physics engine
Tower22 won't be a Prince of Persia game where you can climb walls upside down, take long jumps, or have to balance on ropes while riding the back of a tiger. But for starters, it would be nice if you can just walk in a straight line, rather than a drunk hobo who gets stuck behind doorsill.

Problem with game-physics, is that it's sort of a hack. Like with graphics, we'd like to found our physics on, well, real physics laws instead of (much simpler) programming abracadabra. Which is a good thing, but also complicates the situation at the same time. Rotating and moving an object forward with pure vector math is easy peasy. But the physics engine won't agree to do so, as your (player)object has friction with the floor, wants to spin like a vertical rolling-pin while sliding along a wall, get stuck in narrow passages, bounces you back when hitting an object, et cetera. Which is terribly annoying, because you're the MAN with the Controls. IF I say LEFT, go LEFT dammit.

But, if physics engines are so realistic... what exactly is the problem then? I mean, unless being on ice or having an epileptic seizure, you're in control. You stop when you want to stop, you can manoeuvre through a crowd without bouncing in the air, you can climb stairs and do a handstand while taking a piss, drunk. So again, the realistic physics engine can manage that for you as well, right?

No, it doesn't. Physics engines typically do 4 or 5 things:
  • Collision detection between primitives (spheres, cubes, cylinders,..), convex-hulls, and triangles (the world). Highly optimized, because doing this requires horsepower.
  • Collision response (friction between 2 surfaces, bouncing off, E=MC^2, ...)
  • Joint physics (ball & chain, hinge door, but also a ragdoll is basically a string puppet made of lots of primitives and joints)
  • Apply forces on bodies (gravity, spin, torque, movement, custom forces)
  • Special types like Fluids, Buoyancy or Cloth physics

Which covers a big important deal, but not everything. Player-physics for example are a black-art. Humans aren't boxes or capsules flying into all directions when you hit them. Or well, if a cement truck hits... Yet physics engines treat us just like that. Because *REAL* physics would be way too complex.

Obviously walking in real life isn't a matter of pushing us human-shapes forward. It's more a controlled form of tumbling forward, step by step. Push up, tilt forward, fall on the other foot. And repeat. No miracle it takes a baby some time to practice on his two legs (though I sometimes whish our youngest son never had legs, now that he learned how to climb onto practical everything). It's so difficult that God or Evolution gave most animals 4 or more legs, for Pete's sake. It's so difficult that hordes of scientists spend billions of dollars and hours into making robots that can do nothing but climbing stairs.

So having true human movement kinematics into games... better not. Even if it was available, it would probably beat the hell out the CPU. And then we have an alien character with 3 legs, or a crippled guy that walks on his hands... Got to start all over again. Just no. What we do have, is
either old fashioned homebrew fake-physics that are guaranteed to generate amazing stunts, or use the tools we get from a physics engine. Usually we do a hybrid; special rules for players, yet using an existing physics engine so it integrates with the other stuff in the game. Meaning it will bounce away a box if it was in your way, and meaning you can benefit from the same optimized collision detection systems.
Even the ED-209 hates stairs.

Jalapeno on a stick
Until recently, the Tower22 player was really just a capsule. On a stick. The tiny stick (cube) did some special stair stuff, and the somewhat wider capsule does the collision detection with other objects and of course the environment. Fortunately you can't see it (physic collision hulls are always invisible, the 3D mesh does not represent the actual physics shape), but man, it's a ridiculous model. Imagine everyone on street would look like Jalapeno on a stick, sliding forward by some invisible force. Because that is what happens, we push that thing forward, and use an up-constraint to prevent it from tumbling over. Like an invisible rope in the air that keeps us up.

Biggest problem is the sliding / pushing forward thing. What happens if you push a 80 kilogram washing-machine-box forward? Probably nothing, because it's fucking heavy. If you smear green soap on the floor, it may work though. So let's say we have green soap all over the place. Yeah, we're sliding now! Smooth as air-hockey! But crap, there is a little stump on the floor. Even though its 1 cm tall, it’s enough to block. Push harder, and the box tumbles, you landing on top. This is why a capsule-shape may work better, thanks to the rounding at the bottom, it has minimal contact with the ground, and it can lift up itself gradually. Over small obstacles at least. A 35 cm stair-step is either impossible, or requires an incredible amount of force. Increasing force is easy enough in a computer simulation, but hold your horses! Don't forget we also need to stop almost immediately when we release the forward button.

Oh dear, stairs. In the past that would mean you had to take 10 steps back, then charge like a raging bull, hoping your momentum would be enough to bring you upstairs.

Controlling the player like this, feels like manoeuvring the Bismarck. There is no direct control over it, you're at the mercy of physics. Which is exactly NOT what you want. I don't know how people do it in other physics engines, but Newton offers a bunch of "overrides", sort of. Rather than rocket-fueling force into the rear of my player, I can set its velocity. Sort of a PID-control will monitor the velocity and eventually correct it every cycle, in case it drifts off. Same stuff for controlling the spin force. If I say the player should be rotated 270 degrees, he'd better listen. The rotation is measured and guarded every cycle, meaning a correction spin will be applied as soon as the physics engine thinks otherwise (for example, when the player hits or gets hit by something). It works, but be careful that in some situation, you actually want the environment to have effect on our player. Well. Magical rules, overrides, different states... code quickly gets dirty for sure.
                               

Scanning, Scanning, Error.
I didn't mention the stairs yet. The horror. As I tried to explain, we basically just push stuff forwards. But that's not how a human being climbs stairs! Lift a leg, place it one step higher, pull up. Well, we can't really simulate that with a stupid capsule on a stick. But we have some more David Copperfield magic up on our sleeves. If we can set forward-velocity, we can also set upward velocity. Obstacle in front of us? Add some "lift". Problem solved? Of course not.

How do hell do you know if there is an obstacle in front of you? And then I mean an obstacle you can pass, not a wall. Otherwise you would slowly lift yourself over the Chinese Wall, that's not how it should work. The player should scan its surroundings. For example, fire a ray forward from your toes, to see if there is something in front. If so, this *might* indicate a stair. But before rocketing up, do a second scan at balls-height. Still an obstacle? Then you can't simply step over it. You may need to leap over, if that's allowed in your game. But just sending some rays forward (like I did earlier) is prone to fail. Take a look at this picture:

That's a classy stair right? "Thanks" to its open gaps, my toe-sensors don't sense shit. So, no obstacle, no lifting. In other words, we're stuck. But wait a minute, there a are a billion other scenario's that can fool you. What if we were to climb to stairs while strafing or walking reverse? Toe-sensors have to measure into another direction, or it still fails. And what if we see the stairstep, but miss a metal pipe in front of our head? Head-bang. The most annoying are tiny obstacles (less than a CM tall), like rubble. Your sensor-rays may fly over them, but they are enough to stop or at least slow you down.

Scanning is one way to make decisions, but do not rely on a few rays only. Fortunately Newton provides convex-raycasting (like sending out a thicker volume, rather than a thin ray) which already does a better job, as it less likely slips through narrow holes or gaps. But a very different approach, is to simply flatten the stairs. And I'm quite sure older games did that a lot, and maybe even modern games still do so. In fact, due polygon limitations, old games actually had diagonal ramps rather than real block-shaped stairs. Yet, it feels a bit fake, as the player doesn't "hop up". Also the animation should change; you climb a stair, not run it. Idiot.

Looks like stairseps right? But look again, carefully at the edges. It's just a flat ramped polygon with a stairstep texture on it.

A third thing you can do, is making hints, or a context. And this sounds pretty logical. You could mark every "shape" as "floor", "wall", "ramp" or "stair". You decide what can be climbed, and what not. This at least avoids an automated scan to make mistakes, trying to climb stuff that shouldn't be. It also allows to make the player aware of more advanced manoeuvres on its path. Like "ladder", "rope" or "passable for AI only". Giving hints for players and NPC's. You would still have to scan forward, and as said, the level designer shouldn't forget to mark everything properly.

Yet at the same time, it feels as if this shouldn't be necessary. Can't remember having to do this for every possible obstacle in the Duke Nukem or Half life level editors. Also games with dynamic environments that can be altered by building or destructing stuff, probably don't have to mark everything. Obviously it would be nicer if the player-physics can figure out what to without hints.



So. How DID we do it?

As usual, I’m very good at showing a hundred and one failure situations. But more interesting, where is the cure? Well, I wasn’t exactly Newton’s best student back at school. Then again, as said, player physics is more about hacks anyway. In fact, the code is so… if there were Burqa’s for programming-code, this piece should definitely wear one. It’s the type of stuff you’re ashamed of. It’s not founded on rock-solid, robust, proven methods. But on numbers, case specific approaches, and cheap tricks. It feels as if it can collapse any moment. But reading Google, it seems this “Black Magic Code” just happens to be the norm. Okay… If you say so.


  • Skinny Capsule

So, first of all, I replaced “Jalapeno on a stick” with Jalapeno only; a Capsule. A relative thin capsule I must add, otherwise you’ll find your ass getting stuck in door portals. No Kim Kardashian collision hulls. This capsule has low friction and bounce settings. Basically we want as little contact with the environment as possible.


  • PID Controlled Velocity
As explained earlier, rather than just adding force into our desired direction, we measure the actual velocity (and spin), and add more or less if needed. This gives a more stabile speed, at surfaces with different friction settings.


  • Hover Shoes

Even though our capsule makes relative little contact, I still found myself getting stuck behind 5 millimetre floor height differences. A doorsill would be enough to keep me outside the room. Like Garlic hanging in front of Dracula’s nose, it just stopped moving. The solution? Sci-Fi hover shoes. I constantly apply upward force (or vice-versa, you could disable gravity while standing on the ground). Just a bit, to lift me off a few millimetres. Be careful not to add too much, or you will “wobble” like a flying space scooter.


  • Convex Cast ahead

No toe sensors, but we do a downward convex cast slightly ahead into our desired direction. I'm using a flat disc for this. Now we can compare our feet level with the obstacle height at the next step. If the difference is less than a defined “MAX_STEPHEIGHT”, we can engage our shoe thrusters further, giving upward velocity. Notice we can also do an upward scan. This is useful to signal NPC’s to start crouching, in case of an obstacle at head-height.

  • Downforce

We talked a lot about climbing stairs. But how about getting down, without flying through the air? By default, only gravity will pull you down. So you don’t really step down, you just fall. If you run fast enough, you won’t be touching the stair-steps at all, losing control while being airborne. What I did, is reversing my shoe thrusters to “press” you down rapidly. But only if the height difference isn’t too big. As shown in #4, the down-cast will get below the player feet. If less than “MAX_STEPHEIGHT”, downforce will be applied. In essence, it quickens the fall. Be careful not to apply downforce BEFORE you’re over the ledge, otherwise you get pinned to the ground just before taking a step down.
  • Baywatch

Just keep in mind you may walk through a wall, or fall through the floor for whatever reason. So you'd better have a lifeguard. Make a respawn point, or use some hard boundaries to prevent falling through. If the lowest point in a room is -2,5. then just disable gravity or even push up whenever the player threatens to get below that point. Yes, it's stupid and it shouldn't be necessary. But better safe than sorry.



Does this provide waterproof, fine controls? No, but at least it''s a step into the right direction. And moreover, I just wanted to give you an idea of things *can* be done. I still find myself in odd situations, like getting stuck in corners that are complex geometry-wise. Or flying up onto a steep ramped wall that shouldn't be climbed really. And for some reason I keep falling through that damn floor for no apparent reason. But at least its a lot better already.



Sunday, March 6, 2016

Damn you Good Graphics!

Graphics... Can't live with them, can't live without them. No doubt the average 2016 game looks way better than a 2010 title. Funny thing is, six years ago you would probably think those graphics were unbeatable, but looking back now, some games look barely playable anymore. And well, leaping another 5 or 10 years back, is like comparing dirty medieval women to a modern bombshell. Yes, the train to stunning, photorealistic graphics is still moving forward, at a decent speed. And with Virtual-Reality really getting real in the next few years…

But of course, this wouldn’t be a T22 blogpost if I didn’t have something to complain about. As you may agree, awesome graphics is a double-edged sword.

How much hours did I put in rendering that stupid corridor better and better? Imagine if all those hours were spend on making more maps or gameplay instead! Only thing is... a horror game like this depends on immersion, and thus decent audiovisuals.


Doom4
Being from the Doom era, of course I’m following the upcoming Doom4 release with interest. Honestly, it’s one of the very few titles I could still care about. Not that there aren’t other good games, but I’m just not into reading magazines or IGN / Gamespot anymore. But also remembering the mixed feelings people had about Doom3 (personally I really liked it), and still having a bad taste in my mouth from Duke Nukem Forever, I’m not too sure if Doom4 will satisfy.

Doing that game *right* is almost impossible, and that is partially due graphics. First of all, reading Youtube or forum comments, kids aren’t too impressed about the visuals. Doom4 looks “ok”, according to them. Now after a technical powerhouse like Crysis, sadly beautiful Last of Us, or the wide open worlds of GTA, it’s hard to get impressed by anything really. Been there, done that. But yeah, I agree Doom4 / idTech6 (the Doom4 engine made by id Software) doesn’t whoop all others, as it used to do hundreds years ago.

Games tend to impress with massive, dramatic, destructive, in-game cut-scenes these days. A skyscraper tossed over by Dirtzilla, the Moon getting blown up by Aliens, whatever. Bigger, better. A generic sci-fi corridor from the Doom4 UAC base just won’t “Wow!” anymore, no matter how crisp and sharp the graphics are. But wait a minute… so what?

Sharp and much brighter than Doom3. Good things. But is it enough to impress a new generation of gamers?


So what?!
Yeah, so what?! Even if the graphics aren’t better than the others, does that make a bad game? Of course not. Although unfortunately, people DO judge by appearance. The chubby but intelligent girl with a fantastic character that can cook perfect Lasagne still gets beaten by an hollowhead blonde, when boys have to pick in a bar. Graphics work the same way. Like I said, just read the comments below a Youtube movie. You can easily pick old fans, and younger kids. “The Order 1886 looks 10x better, what a shitgame.”.

But the old-fan comments are sceptic too. Not about how good or bad the graphics look, but if “Doom will be Doom” yes or no. And that, is indirectly related to graphics as well.


Feminized shooters
Most fans agree; after the horror-jumpscare escapades Doom3 made, it’s time for an a true Good Old Shooter again. No complicated stories. No 100 year introduction/tutorial, no teammates, no auto regenerating health, no 2 weapon limit, no stupid puzzles, no quicktime events, no hints or guidance. No nothing. Just back to the basics: Blood, manly muscles, many guns, even more monsters, and SPEED. For anyone born after 1995, this is what we mean with speed:

Whereas modern shooters are usually tactical, stealthy and semi-scripted, old shooters relied much more on agility and speed. Let’s say much dumber, but in general also much harder games. Of course, entering the 21th century, games like Farcry or Half life finally added some much needed depth to these otherwise dumbass Commando-Arnold-Schwarzenegger action games. But now 15 years later, we started to miss our old heroes again. The shooter genre has become feminized really. It’s all so slow, and simple, and weak, and… so serious.

For those who think the original Doom was a horror game, nah. Not really. Yes you fight Demons, Doom takes place in Hell partially, and blood shall flow. But games back then didn’t take themselves too serious. It‘s more the “Braindead” kind of horror; overdone, and jolly. Unlike modern games were foes are supposed to be very scary and dangerous (but usually aren’t), you were definitely the Apex Alpha male in Doom (or Duke Nukem for that matter), killing everything on your way. And that was one the things that made Doom so addictive; firing a rocket into a pack of Imps and seeing one of them fly 6 meters through the air, was a blast. I can do that over and over and over again.

They look kinda cute, don't they?


Violent God
Now back to 2016. The Doom4 trailer was promising, as it didn’t feel like yet another Call of Duty railroad shooter. The tempo is somewhat back again, and seeing the player beating/stomping the shit out of demons (with a yelling crowd), I’m relieved that it’s not a serious tactical shooter, where you have to take cover 90% of the time. Not that tactical shooters suck, but when playing Doom, I want to feel like a violent God. Taking cover is for pussies.

Yet, comparing to Doom1 or 2, it’s still a bit slow, and neither did I see truly large groups of enemies to empty your rocket launcher or BFG on. In Doom, you would typically get surrounded by 20, or even 60 enemies when picking up some keycard. And 1 second later, the whole room turns into one epic barfight, as demons would tear up each other as well. Didn’t see that happening in the Doom4 teasers…


Ok. But what has that to do with Graphics? All kinds of things. For one thing, I can imagine computers will crumble if they have to render/animate 60+ enemies at the same time, with HD graphics. And yes, we must have HD graphics, otherwise those kids from the Youtube comments won’t buy it. In the end, Doom is like any other commercial game, trying to sell itself as much as possible.

Of course. Making a game Like Doom4 will cost the developers millions, many millions nowadays. It has to be compensated somehow. Although the ironic part is that, it is exactly those good-graphics that drive up the costs and development-cycle. If idSoftware would decide to make Doom4 with simple Sprite graphics again, they can probably make the game with 8 guys only in a year, having a less-than-a-million budget + some pizza’s. And although that game may sell less copies, it might even be a more fun product in the end.


The zombie in the closet issue
But anyhow, trying to achieve realistic-graphics has more impact than a potential limited set of foes to fight simultaneously due framerate impacts. We didn’t care 23 years ago, but don’t you think it would look silly to have 12 shotgun-zombies packed together in a tiny container that automatically opens if you pick-up an armor bonus? Doing that 1 time is forgivable, but doing that all the time (like Doom1/2 did) looks ridiculous.

Doom3 had a habit of storing zombies in closets, lockers, fridges and even ovens as well. But at least only 1 came out a time, not 100.

My point is, level design is radically different now that realism –including semi sci-fi or horror “realism”- is a basic must. Enemies have to be placed as if they were doing something useful there. Fixing a computer, sleeping in a dark corner, walking a patrol, guarding a door… Ok, ok. Zombies and demons don’t do jobs, but still. You can’t just place dozens of them behind a magic-opening wall! Somebody call PETA!

Speaking of magic walls that move up when picking up a double barrelled shotgun that just lays on platform… No no. Weapons don’t belong on the ground. You put them safely in an armory, or next to a dead body. Clean up your mess sir.

Doom didn’t just spray its bonus-stuff all around because they were lazy. In fact, like Pac-Man, it’s an essential part of the level design. Follow the trail of bonus items, but don’t pick them up if you don’t need them yet.



Modern boundaries
And then that wall itself. Again, no. It’s not realistic to have walls going down when walking over an invisible line. But man, how are you gonna reproduce Doom, if you are so restricted? In Doom, you had all kinds of senseless architectural abominations. A whole pack of elevators going up and down. 20 cm wide walls high in the air to balance on. Pentagram shaped platforms in Lava. Houses made of laughing faces or intestines. Bridges floating in voids. Walking through burning mud and slime waterfalls as walls.

It didn’t make much sense, but hey! The levels were fun. No, not just fun. They were brilliant. Because now, 23 years later and having them finished a hundred times before, I still play them. Doom levels aren’t particular big, but neither are they linear-corridors (a misunderstanding). Rooms were often so big and had multiple entrances, so the player could decide when and how.

Making such smart, well-balanced levels with modern graphics is going to be one hell of a job, if not an impossible job. For one thing, old Doom maps could be made fairly quickly (remember making your own maps with a Map Editor?). There weren’t thousands of textures, decals or props to choose from. The geometric shapes –not allowing multiple stores- were relative simply. And moreover, the question was not “How good does it LOOK?”, but “How good does it PLAY?”. Since you couldn’t make super advanced surface textures, or spectacular massive size Vista’s, all the focus was on the playability. As it should.

And since a new map was born fairly quickly, you could also drop them more easily. I wasn’t there, but it wouldn’t surprise me if idSoftware made 200+ maps, and filtered out the very best 30 (or 32 actually) for Doom2. And since the maps didn’t have to support a real storyline or plot either, you could basically make a random compilation of kickass maps. So, modern game maps are story/graphics driven, whereas old maps were quality/fun driven. A vital difference.


Now even if you wanted to, you can’t afford the same approach with modern graphics. First of all, stuff like a floating platform doesn’t work. Maybe one time, but applying it on a big scale would simply look weird! Even though you are in a Fantasy Hell, realism tells us to obey some physical rules. Add some support pillars, or add metal chains that carry the floating platform. Maybe not a big deal, but see, now you are adding stuff for aesthetic purposes, not for functional-gameplay purposes.

Now this looks pretty "non-normal". But this is just a single scene. Doom1/2/64 had dozens of levels like this! They could get away with pretty much anything, but shaping a Hellish world that looks good, plays well & still makes sort of sense, is a challenge.

Time = Money
Not to mention the extra time it takes to put all those extra details. Where an old Doom map was just about walls, floors and ceilings, a modern map is much more dominated by its little details. Well, everything takes more work. A Doom2 wall texture was a 64x64 bitmap or something. Now a wall is made of a 2048x1024 albedo or “base” texture, a normal(bump)Map texture, and some more layers to tell smoothness/roughness or secularity. And if you really want photo-realism, all those pixels need to be based on real measured data (PBR / Physical Based Rendering).

This can result in tunnel-visions. Rather than a spontaneous, trial & error approach where you just map your crazy ideas and dump them a day later if it sucks, maps are carefully planned now. Concept artists start with putting down piles of wacky ideas on paper. But be aware, just some boring dark corridor –the majority of old Doom environments- doesn’t make a kickass drawing. So, artists tend to add colossal structures and other eye-catchers. Now the lead picks out the best drawings, and next levels have to be designed on paper, based on the concept theme.

Then finally (3D) artists will work it out. That means drawing textures, modelling “props” (objects to decorate or fill the environment with), making the map structures, putting in lights, and finally scripts + sounds as well. As you can see, a lot of work. But what if this map turns out to be “not so much fun”? You can put down scripted events, some nice visuals and a thrilling ambience pretty well on paper. But as explained here it’s really hard to figure out if a certain map just plays well. Especially when your game relies on agility, dodging, running, and jumping. A dummy map (untextured, no details) can be used eventually to get a quick preview, but since modern games rely so much on immersion, it’s still hard to tell if it works without having proper audio-visuals.

So what happens if a map seems to be boring? We already spend precious concept-artists, designer and mapping time on it. So dumping is often not an option. Instead we twist, turn, and tweak it. Sometimes with success, but other times games just end up having weaker parts. And it also explains why modern shooters are often linear and short; simply no time/budget to create a big bunch of good maps. Thanks to awesome graphics.

Speaking of tunnelvision. Not a bad concept picture in itself, but Doom4 was supposed to be "On Earth", having human buddies fighting evil, vehicles, dramatic storyline... YAWN. Good thing they rebooted it. But probably an expensive reboot though...



I really hope Doom4 will find its way between rock solid additive gameplay, and a modern look that even impresses those kids on Youtube. A game that you still want to play in 2026. But honestly, I think that combination is just impossible at some points. Weird levels & Realism? Turbo-speed & well-done animations? Big groups of enemies & logic placement? Massive battles & high framerates? They could decide not to of course, but I’m afraid it will be not modern, nor nostalgia, pleasing nobody in that case. But, let’s just see. Coming in May! 

Sunday, February 14, 2016

Press my Button

Human Machine Interface 
You may have never heard of it, but you used them a million times by now. Although the word "HMI" is more an industrial/PLC term for touchscreens, you could call pretty much anything that lets you operate a machine or device, a "HMI". The thermostat display in your living room, a packaging machine button panel , the dashboard in your car, the control handle on fat aunt Beth's scootmobil, et cetera.

As the name implies, humans communicating with devices somehow. Well, I have made quite some interfaces throughout the years. And like mode & fashion, visual interfaces tend to change like the haircuts from Sixties Beatles to Seventies Bee Gees, from Eighties Rick Astley to Nineties Fresh Prince of Bell air. Large square tiles with simplistic retro symbols are hot now, but what will it be next year? Ten years ago it was much cooler to create an dark icy, complex, "The Matrix" style with lots of small buttons and nerd-information scattered everywhere. When I compare my older programs with the newer ones, they look radically different.


They all have one thing in common though; their users have to be considered either stupid or highly trained, and so the interface has to be as simple or powerful as possible. And this is where our programmer brains short-circuit sometimes. You see, making something easy difficult, is easy. Making something difficult easy, is difficult. Read that again.


Poor Carl
When we create a new program -let's say a packaging machine touchscreen- we programmers have two major flaws. As we designed our own program, we know exactly how to use it, and more important, what NOT to do. We're not able to approach our program without pre-knowledge, with a blanco view, pressing different buttons in the wrong order. Or worse, not pressing buttons because we have no clue what they do, and are afraid of screwing up. If a programmer comes explaining things, he's like "Oh that's simple. Press here, here, then here, and then –oops.. hey, that shouldn’t be there! Weird. Little bug still in this version I think. Well, in that case press there, and then you're done. Simple right?!!". 

61 year old Carl, who grew up in a barn without electricity, fought in the Great War, and used the first gas-driven telephone when he was 19, nods "Yes, I understand". But the cartoon-dream-cloud above his head says "..........". Most people will say "yes". Because we don't want to look stupid. But a good portion of machine operators, desktop office-clerks, or Excel administration nannies, were never trained or interested in computers. Listen young punks, I'm not that old, but even I didn't grew up with a telephone and apps. It’s not a second nature.

This is what you see on the cab-display while driving in transport mode in the harvesters I program. Hate or love the colours, but the point is that a dummy can see what he needs in an eye-blink. Also, the big cartoon buttons seem friendly - you can press them without blowing up the machine or ejecting the seat.


No!
Some people won't say "yes", and will ask though. And that's where our second flaw comes around:
we're arrogant. When that (ugly) lady from the office still doesn't know how to delete an item, when the chief calls in anger that everything is stuck, or when THAT guy complains for the seventeenth time, we're inclined to say: "Screw them". It's their own fault. How many manuals did you write? How many times did you say NOT to drive and press the handbrake at the same time? How many warning stickers are there on that hot oven? From all people, why did they put the analphabetic Indian behind the controls? Why don't they just understand?!

When that picky ass starts telling the font-size should be 1 pixel bigger, the button should be at the top instead of bottom, or thinks an extra confirmation pop-up is annoying, we're inclined to say: "Really?!". What a pile of horseshit. Pressing 1 extra little button, boohoo. LimeGreen background instead of PastelGreen, so what? Again, we fail to see our creation from a different, user, perspective. We make stuff, think it’s cool, and drop it off. Moving that button to the left really isn't that much work, but it's boring work. Our mind-set is already in that next, more interesting project. And of course, nobody really likes it if his plans or design are questioned. Can't they just adapt and deal with it? We're not calling Microsoft every day either, to complain about small letters or hard-to-find settings. But we forget that, when using the same software EVERY day, small annoyances can be become a big aversion. Do you use programs that don't feel good, if you don't have to? Exactly.


Stay cool, have fun.
So I'm making the Engine22 Map Editor (or “MapEd” in short) now. Or well, I've been working on that quite some time now, but recently another guy started using it. Julio, who contributed T22 assets since 2010, got a copy. For two reasons; Giving a toy to play with & Feedback. There has always been a T22 editor, but I never released it. Because I knew the interface was programmed "Rick only". So in the past, I would typically ask an artist to make an asset, say a Sofa. He has no clue what, where, or why, so I also give background information. A sketch, a photo URL, or a list of requirements. He makes the thing in Max, Blender, Maya, or whatever program, sends it to me, and then I would import it into Tower22, using highly sophisticated (read buggy user-unfriendly) software. And 9 out of 10 times, I would make an in-game snapshot plus a list of improvements, and send the object back to the worktable.

It works, and I guess big companies do it like this when outsourcing assets to some other company that "just makes models”, without having to know what this game is all about. But... it's not a playful, dynamic, creative flow of course. Especially not for a creative guy that does this in his free hours. He or she should have some artistic freedom. Fly through a room, have a careful look, then decide "We can really use a pink sofa in this corner!". He or she will make the asset, and import it themselves, get a preview, and tune it until they love it. All in all, a more inviting, as well as more efficient flow, potentially. Keep in mind that artists here work on free will. So “having fun” is a keyword. Giving them a “fun editor” is mandatory.

A broken editor that can’t do shit isn’t much fun though. Most artists, and certainly the skilled ones, have been spoiled with superior tools and engines, like Unreal, Unity or CryEngine. Of course, it’s not like mr. Rick from the Netherlands will do a better job with two fingers in his nose in the late hours. But I do have an advantage though. Since E22 doesn’t have to be an all-round, multi-purpose-ultra-engine that also works on Atari and Cyborg telephone platforms, I can narrow my set of goals. Ultimate goal? Making Tower22. Or at least that G@#% playable demo for a start. Additional goal? Eventually letting other (Delphi) hobbyists using the engine, or parts of, to make a somewhat similar fashioned game.

Artists should be able to import, tune and preview their own stuff this time. Still have a LOT to do though!


Multi-useless Tool
My experience with universal, multi-purpose software, can be described best as “Jack of all trades, Master of none.”. And I’m not talking about game-engines, as I honestly don’t have a lot of experience with them, but just in general. Warehouse, administration and ERP software for example. Since every company knows it all better, these packages are either highly complicated due all customizable parameters (most people I know have no clue how their package really works), or very restricted and therefore a pain in the ass. And in terms of UI, boring. Not intuitive at all, though it’s hard to blame the makers. How the heck should they know whether their software is being used in a paperclip factory, Thai massage saloon, or crematoria? Different story each time. So they have to keep it abstract and thus “bland”.

Frequent- or pro-users deserve better:
·         Every unnecessary step is one too many
·         Eliminate anything that slows down the process, or confuses
·         Good looks are nice, but speed & ease should get priority for pro-users.
·         Whereas a non-computer audience will be better off with a very minimal, playful UI
·         Whether you use text or symbols; be clear. Users shouldn’t have to guess what a button does.
·         Be consistent. Looks and procedures should be the same as much as possible.

And last but not least, know your audience. Take their feedback or complaints serious. No matter how stupid or picky it sounds. After all, they’re the ones stuck with your software or device-controls the whole day long. But! With one big side-note: have a vision and lead. You can ask a person what he wants, and implement it exactly that way. But if you ask another person, you’ll get a different story again. And what do you get if you mix 10 different colours? Yep, brown mustard poop. You should decide the main direction, whether to goo blue or pink. Then use the feedback and comments to fine-tune.


Engine22 Map Editor improvements
Now the Engine22 Map Editor. The audience is experienced here, they know how to turn on a computer. That means less concerns about stupidity, but at the other hand a more critical audience, as they know similar software as well. My first mistake was that the initial design had pretty large buttons with icons. The stuff I’m used to when making agricultural machine-cab interfaces. While driving you don’t want to read small letters (some can’t even read). Big simple dumbass indicators is what we needed there. But for a modelling/rendering application, big dumbass buttons will consume a lot of precious space. Turned out my “test guy” didn’t have a very high resolution either, so an awful amount of space was wasted on funky symbols, thick Form headers, and voids. Meaningless stuff.

So I received a whole list of suggestions to “compress”. Got rid of the standard Windows form headers, gone with the big symbol buttons, increase density, move less important functions into a sub-menu or something. Second, a lot of hotkeys had to be added. Yes, moving the mouse from A to B to click, takes a second (and a nano-calory) more than having your other hand pressing the magical combination. Personally I’m not a hotkey guy, as I can’t remember them. Kids still showing me handy shortcuts that have been in Windows for ages J But again, if you had to use this tool a substantial amount of time, anything that adds up to the comfort, should be embraced.

Lots of panels while editing this sofa. But, in contrary to the previous version, you can now move and hide all panels quickly, with shortcut keys eventually.


Third, and probably most important, it must work. That’s captain obvious, but really. Sometimes it’s better to keep half-finished stuff hidden, instead of implying that featureX is operational while it isn’t. A program like MapEd is complex. It has dozens of features. It’s more or less the game + an editor, double trouble! Since the engine core itself is under heavy construction as well, it sometimes feel likes a Jenga tower. Insert a block here, and crap, some other part falls out.

Julio began his journey with importing stuff (OBJ files and textures) to make them “props”. And as Murphy tells, more than a handful of things crashed. Of course there was the usual video-card beef. Shader bug here, OpenGL not supporting that, his screen blurry while my isn’t, et cetera. As expected. But also some of the executables didn’t run due some missing library for 32-bits, and it seems every 3D package does a different job exporting OBJ files, as that didn’t work in one shot either. Polygons messed up, textures upside down, that kinda stuff.

Since Julio is my test-guy, there is room for error in this stadium. But at some point, he will also be an end-user. So be careful with that “room for error”. If something crashed the first 100 times, that fragile feel will haunt your product for the rest of its life, even if the bug has been dealt with. Every update should feel as an improvement, not a wild trail-and-error ride. So I try to avoid a billion updates, and to make things more comfortable, E22 has a tool called “HUB”. This tool checks a FTP server for engine and asset updates. Especially the latter is interesting. When you’re done with an object, material or room, you can upload it within a few clicks. Then other users download it next time they check for updates. Too bad HUB itself still has a couple of issues :p