State of the Game - Episode 2

The current goal is to stitch together the various prototypes into a playable alpha.

This video shows off the new terrain as well as logging, mining, and basic farming. These are the basic economic loops allowing players to generate revenue. NPC behaviors are slowly being built up using Behavior Designer. 

Next up is getting the constrution of buildings up and running as well as the start of basic dialogue with the NPCs. Stay tuned for more.

Want to have input on the development? 

Come join the discord server. It's the best way to make your ideas heard!

The Bump From A "Viral" Post

Getting the word out about a game is tough. Really tough. Try as you might the world is a full of games with "great ideas." The social reach needed for a successful game launch is a huge hurdle for small teams and maybe more so for hobby or solo developers like myself.

Over the last week or so I've posted and shared a GIF and a video of a low poly waterfall. I created the scene to test particle effects for use in my second game. I spent a little extra time making it look nice as I wanted it to be a real prototype - could I actually make a half decent water fall?

Based on the response, the answer is yes, yes I can make a half decent water fall.

The Numbers

I first posted the waterfall on twitter. As of writing this the tweet has been re-tweeted 18 times and been liked 42 times. This seemly earned me 10-20 new followers and maybe a few more over the next several days as the tweet continued to get some attention. Not bad but not viral.

A post on the low poly reddits earned over 500 up votes. One or two people asked questions and I was able to share more info about the game. My website (this site) also saw a bump of about an extra 100 views. Not bad, but still not viral.

Then 10 days or so later I posted on Imgur, a site I mostly use to share images with online friends. I posted the GIF and saw 60-70 up votes before heading to bed. Nothing too exciting. When I woke up the image had over 1000 votes and was featured somewhere on the front page. Imgur classified it as a "most viral" image - at least for a few minutes. 

As I type this post the image has almost 1200 up votes and 290,000 views! Wow. 

So what?

Those votes and views trigger a dopamine rush, but what did they really do for me? How did they move my game forward?

I'll be honest I wasn't prepared. My game's landing page is pretty basic. I was updating a few bits as all the views and up votes were rolling in. I didn't link the game right away, and probably only the last third of the views had access to more info about my game.

Oops. Maybe a big oops!

So the best that I can tell here's my gains from the imgur post:

  • Twitter followers - nothing significant.
  • YouTube - 7 or 8 followers
  • Newsletter - 28 at last count
  • Discord - 8 or 9 
  • Website - 480 visits and 700 page views

These numbers are small... The Newsletter and Discord were the most exciting as both were essentially at zero before. I had "launched" the Discord server just a few days earlier with zero publicity and the newsletter gets almost no push from me.

While this activity felt good it's not the 1k, 10k or 100k people that I might need to launch a game "successfully," whatever that might mean. 

My Take Aways

I'm writing this post as much to share my experience as to organize my thoughts and what I learned in the process. For me this was a break through in the PR department, even if it's small. It helped me understand and get a feel for what success could look like. 

The value of a good image is worth so much. Sharing works in progress have their place, but maybe not with the general public. People say share and share often and don't wait until the game is finished to share your work. I think this is largely true, but I also think there is something to be said for taking a little extra time to polish what you are going to share. Just because you're excited doesn't mean that very many other people will be too.

Where's the balance? I'm not sure, but I have a better feel for it now after this experience.

Motion adds so much. I've read this over and over, but I'm not sure I really understood. I also shared an image of my river at the same time as the waterfall. The river has motion but it's much more subtle - it got almost no response! At this point I question sharing much of anything unless there is some form of motion. All of our social feeds are full of static images - some are amazing, but the images that have motion are so much more engaging.

Somehow I need to reproduce this "viral" post over and over! It's scary to think what it would take to get to the social reach needed for a "successful" game....

 

 

NPC Job System

I needed a picture at the BEGINNING... At least it's a place of work?

My day job is at full speed with my weekends being controlled by bike races (head coach) so development is coming in spurts. It's disappointing to watch the slow crawl of progress, but at least the bike team is placing first in the conference! 

Ok, that's not why you came here... But while your distracted, if you didn't notice I've added a discord channel. It's quiet atm but feel free to stop by if you have questions or comments.

The big focus for the past month or two has been the job system. It is designed to the allow the player to hire NPCs to do basic jobs. These jobs are created from tasks which contain specific actions. These jobs are then "posted" and the NPC uses a simple  value system to determine what job they want to accept. The goal is that these jobs are superimposed on top of the NPC's other needs or desires and that jobs provide money for the NPC to provide for itself. The jobs also intended to speed up the progress of the player - rather spend time to chop wood they can pay an NPC to do it allowing the player to become more efficient and do more. 

The job system has developed in three major chunks. Code backbone. User interface. Creation of actions. 

Code Backbone

The base Actions class

The job system needed a generic framework that could be expanded and extended upon. To do this I broke the design into three main classes; jobs, tasks and actions. 

The job class is the boss of the whole deal. It controls the flow of tasks that the NPC will do and is also the communication link between the rest of the game and the job as a whole.

Task scripts are pretty similar to jobs in that they control the flow of what actions the NPC will do. Having a second container with no real effect made sense in that a task can fail and if the job contains more than one task the NPC would still be able to accomplish something... There is also the option (not fully implemented) that each task can have a time limit. The thought is that a NPC shouldn't spend 3 days looking for kindling if they could also be mining for coal. I'm not 100% sold on the need for tasks, but will likely leave them in for now. 

Actions are where, well, all the action happens. Actions are pretty specific and an individual job or task will likely have several actions. New actions can be added fairly easily due to the base class that is easily extended. Actions will include searching for items, dropping them off for processing or selling them to a vendor and whatever else seems useful.

The three classes largely communicate and interact by checking the status of their "subordinate." That is the job checks and reacts to the status of each task contained in the job and each task checks and reacts to the status of each action contained in the task. When all the actions in a task are complete the task is complete. When all tasks in a job are complete the job is complete and checks to see if it should repeat. Jobs can be done once, daily, continuously or a set number of times. For simplicity the status of jobs, tasks and actions all use the same enum - not started, running, complete, failed or paused. 

User Interface

The ugly current state of the Job Menu

There's a lot going on in the creation and the assignment of a job to an NPC. So the UI is probably the most complex I've made so far in my short dev career. Can I really call it that? I hesitate to even show it as it's so damn ugly, but it's easier to post a picture than describe it all. 

Essentially the left panel is where the job is constructed while the right panel contains posted jobs, saved jobs and inventory items that plug into actions. Not the most refined, but it's working (mostly). 

The job menu has already been through several iterations. With many more to come. I'm trying to hold off on the fancier bits until the full design is complete or at least closer to complete. Each new action makes me rethink the design of the UI or at least the action interface. Once the set of actions are more complete the design of the UI should come together.

Creation of Actions

The first action created was a rather useless one in that it was a random wander. Not something you'd likely want to pay some one to do, but served as a good testing grounds for the system as a whole. 

I would like to keep the number of actions fairly small, but still allow a wide range of jobs for the NPC to complete. Hunting for the system that allows emergent behavior! Currently actions are focused on the collection and delivery of resources. I hacked Inventory Pro to use the item database for the job actions. This greatly simplifies what I have to create and also helps keep a common interface and database.

At the moment I have one UI prefab for all actions and I am simply toggling on/off the needed parts. I'm not sure this is the best solution, but seems to be working fairly well. The toggling is controlled by a series of booleans in the actions themselves - the info in this communicated when the action UI element is created. 

So far the available options are an item, location, range from location, and a number of times to repeat the action. These options are holding up well with the exception of needing to show or indicate the location. At the moment the location is a vector3 which is pretty useless to the player... 

The Results?

The results of this work is a functional prototype of a job system. It's not complete, it's not ready to be added, but it was a proof of concept. The job system is likely to be left out of the first alpha build, but should make it's way in once the first couple rounds of bug fixing and balancing.

What's Next?

The job system was the last major piece of coding that needed to be completed in the prototype phase. So now the working goal is a fully playable alpha build. 

This leaves me focused on the visuals. In particular I begun the process of modeling buildings and working to refine my terrain creation process. I want to include rivers and waterfalls both as eye candy buy also as potential energy sources (hyrdo), but getting a low poly waterfall to look decent is tricky... but more on that in my next post.

I'll leave you with a WIP render of some market stalls.

A WIP render of market stalls - yes I know the lighting isn't awesome

 

 

Resources and Resource Systems

Progress on Game #2 marches slowly towards the goal of have a "releasable" product. Not a Steam ready product, but a product ready to tested by others. So much work to do...

A Chicken taking a stroll around a steam engine

A Chicken taking a stroll around a steam engine

In my first game I made the mistake of implementing "feature X" and then "feature Y" only to have to go back and hack the code for "feature Z" into the code base. I had no idea how to make my code easy to use or easy to extend. Simply adding a new building to a menu took hours...  Oh the mistakes I made! 

In my current project adding a new building to the UI takes approximately 45 seconds. 

With game #2 I am trying to build the systems before adding any significant content.  I don't expect flawless execution of this, but when I find myself writing code that will only work in one situation or copying code and only changing the value of a string I'm trying to step back and generalize or abstract the code. I'm making better use of getters and setters to keep behavior consistent and spaghetti code to a minimum, more of my variables are private and I'm making (some) use of the delightful world of static classes and static methods.

I have a bit of a man crush going with static methods at the moment.

One of my many static functions

One of those static classes is a "Helper Function" class that contains static (naturally) methods for things such as finding the nearest gameObject with a given component (good for snapping functionality), or finding the distance to a player or rounding a vector3. Not methods that every class needs, but methods that are needed frequently and all over the code base. I'm learning to do things better. Slowly. 

Static lists are doing good things too especially when it comes to searching for components in a scene. Several of my more common classes add their instance to a static list when they are initialized (and remove themselves when they are disabled). This allows for the quick searching of a list of components rather than a more time intensive "Find Objects of Type" situation. 

I don't think the extra memory usage a concern, at least not for now. 

All of this is helping to create a more manageable code base.

So what is the result of all this work? 

Energy Mechanics

The focus has been to get the basic resource mechanics working. As mentioned in an earlier post Energy is Everything, so getting the "generation" and delivery of energy working was a major goal.  At the moment energy is broken down into two categories, mechanical and electrical. Steam engines, wind turbines (not yet implemented), maybe solar (these aren't functional yet either) and even hand cranks will generate energy. While generators and motors will convert between the two types of energy. 

The current design vision is that energy sources can be attached directly to objects that need energy or that energy can be converted to electrical energy - at a cost - and transmitted via power lines or some other transmission mechanic.

The energy mechanics are largely functional and the parts that still need work should be easily created by extending the code that already exists. Getting this all working took several iterations and several bouts of refactoring with careful choices on script inheritance. There is, of course, plenty of tweaks and balancing that will need to be done, but the basic framework is in place and working well. Check!

Resource Gathering

I want to keep the resource gathering simple. I also want to make it easy to extend or add new resources. Can you sense a theme? So once again the focus was on building the base mechanics - which certainly needs some tidying and refactoring, but by in large the mechanics are functional and I'm happy with the product at the moment. Inventory Pro has gone a long way in helping structure much of the resource code - both in good ways and bad - the built-in item types and categories provide a natural structure for the resource content.

Currently, I'm focusing on wood/lumber gathering and basic mining. These should provide several resource loops as well as the basic building materials for all (most) structures. Or in other words, hopefully enough content for alpha build. 

Logging

Chopping down a tree with the CAW system

Chopping down a tree with the CAW system

With the logging I started working to get the visuals right before tackling the coding or player side mechanics. Maybe this is backward, but if chopping down a tree didn't feel good it wouldn't matter how great the code was...

So, in Blender I took a basic tree model and added a loop cut to the trunk to allow it to split into two parts. I spent a few hours adding colliders, rigidbodies and tweaking physics settings until I arrived at something that felt decent. A particle based dust cloud finished off the chopping down of a tree and I was ready to implement the chopping mechanic. 

I love physics. Both as a subject and as a game feature/tool. My trees use physics to fall.  So why not use physics to chop the tree down? I added a trigger to my axe and a script to my tree. Hit the tree the right number of times and ... Timber!

I loved it. Until I had to line my character up with the tree. Ugh. 

Trying to get a third person character lined up with a tree and get with in the range of the axe's trigger is doable, but that's not generally how you want to describe a commonly used game mechanic. "Oh yeah, it's 'doable.'" Cutting down a tree is not supposed to be the hard part. Did I mention the obvious fact the that axe is in front of the avatar so the player can't see it without rotating the camera.... Not awesome. So back to the drawing board.

I paused my work with logging and moved on to mining.

I often find when I'm stuck on a problem, big or small, moving on to another task often results in a more creative or at least better solution.

Mining Mechanic

Mining a cube... Can we all say "Place holder?"

Mining a cube... Can we all say "Place holder?"

I started with this Minecraft like vision where players would build an above ground mine and then be "transported" to a mine full of cubes. I wrote some code to generate the mines and place them below the game world. I added walls to limit player movement as well as block out the directional lights from the outside world.

Why not just have a new scene you might ask? I want/need the simulation in the outside world to continue and I also want NPCs to be able to visit a mine. 

It was all looking good, I was feeling good about my mining solution. That is until I placed my player into the mine. Damn walling clipping! I immediately saw the huge flaw in my plan. It didn't take 3 seconds to know this approach wasn't going to work. Totally dead on arrival. The camera was clipping through everything. It looked horrible, especially when the camera was outside of the walls looking at the world above and the vast nothingness below.

Again, a new approach was needed. Something that will feel good and look good.

At times I wonder if I implement ideas from others because I'm lazy or maybe because they realized the issues and designed around it... Hmm. Good artists copy, great artists steal?

Click and Wait

Basic building using the Progress bar

Basic building using the Progress bar

With the tree chopping feeling lousy and the mining mechanic needing to be redone I decided to implement the classic "click and wait" (CAW) mechanic with mining just to see how it felt. And by CAW I mean that a player would walk up to an object, click the mouse and wait for an animation/action to finish. When the animation is finished the resource (or whatever) is ready to be collected. Add a progress bar to this and you've got nice, easy, and hopefully well understood feedback to the player. 

It may be not be very creative. It may be fairly cliche. It may be a lot of things. But most importantly it feels good. The player walks up and clicks. The computer does a quick distance check and the progress bar starts doing it's thing. It's so much easier. Not only that but the previous method didn't really communicate to the player what was happening. Sure the old physics based approach had sound effects and particles when the pick axe hit the chunk of ore, but nothing much happened when you missed... Not good design. The progress bar, as cliche as it may be, teaches the player what to expect and gives near immediate feedback as to whether something is working or not. That's worth an awful lot in my mind.

The CAW mechanic felt so good I immediately added it to the chopping down of trees. While I miss the elegance of the physics based solution, as soon as I had the CAW working it was way more fun. I made a line of trees to just cut them down over and over... for testing purposes! I spent a little time appreciating the sounds, particles, motion and general goodness of how it felt. Hopefully the future players won't even notice - it'll just feel right and never get much attention. 

Best of all with a little clever refactoring, the CAW mechanic can be applied quickly and easily to other game mechanics. 

Freezing Player Input

When I was first coding up the farming scripts I made the decision to freeze input to the player and rotate the avatar towards the point of action. This did a couple things. First it helps the animations look better. It's pretty silly if your character is facing left and dirt is flying on the right... Second it solved the issue of the player interrupting an action part way through. While I like the idea of the player having control, breaking out of an action requires a good deal more code and bookkeeping then simply knowing the action will be complete. 

As the only player tester, I thought it felt pretty natural and normal. I was more engaged with where I was clicking than the direction that my character is facing. Hmm. It would be interesting to get feedback on this. Maybe I'll implement hitting the "escape" key to break out of a CAW loop. So far it doesn't seem like a game where cutting down the wrong tree or planting a carrot in the wrong spot would impact game play much...We'll see.

Progress Bar

My progress bar at the moment is nothing fancy. Just a UGUI slider with the handle turned off. Maybe I'll make a dial or a circle or some thing with a little more style, but for now it works. 

As of now I only foresee one (player) action happening at a time I added static methods (of course) to the script on the progress bar. This allows any script to call the progress bar and update it's value. No need to grab an instance via script or drop in a component in the inspector, simply call ProgressBar.UpdateValue(value) and the progress bar will toggle itself on and display the appropriate value. Have I mentioned how much I love static methods?

What's Next?

Chicken Cam! 

Chicken Cam! 

So what's coming next? I've been avoiding working on the AI side of things. Partially because I'm not 100% set on all the details of the game and also because, well, I know it's going to be hard. After watching "Less is More : Designing Awesome AI" I was encouraged to truly start simple. No need to plan out the entire AI, but rather start with basic functions and features, adding and tweaking until it behaves in a way that adds to the game.

I'm starting with farm animal AI. Why you might ask? I'm starting there as a way to learn and get familiar with Behavior Designer (my chosen AI solution for #2). Surely a behavior tree is over kill for a chicken, but I want or rather I need to start simple. 

 

Resources: Processing, Consumption and Inventory

As a solo developer (of an admittedly over scoped game) relying on outside assets is a key to building a game "quickly" and efficiently. I'm not the type of person to subscribe to the idea that I need to build everything from scratch. I have no desire to build my own game engine, but I do understand why folks often prefer to roll their own solution.

I've become very skeptical of assets that run with the game. I have learned that editor tools are more reliable and don't come with performance downsides that many runtime assets do. I've tried using several assets that are overly bloated or have turned out to have poor performance. My snow shader and graphing tool came out of such experiences. It's a tricky to find the balance between using pre-made tools and rolling your own. There are pro's and con's both ways.

Game #2 will allow players to collect and use items - this will in fact be a key mechanic. This means that I need some kind of inventory solution. I did a little research on how to do the basics, but decided to also look at solutions on the Unity Asset Store. If nothing else the Asset Store can be a good source of ideas. 

As a Unity Plus subscriber I get discounts on a handful of assets. One of those assets is Inventory Pro. So I figured it was worth a look since I was shopping for a inventory solution and the reviews were nearly flawless. 

I watched the tutorials and did as much research as I could. While not "cheap" it's an asset that would take me several days if not weeks to reproduce even in the most basic of forms. Plus it has a level of polish that would take even more work on my part.  So why not give it a shot?

I made the purchase and spent some time playing around. My first impression was positive. It has a nice and easy to use editor. Out of the box it handles person inventory, vendors, looting, banks, a skill bar and two styles of crafting. It comes with a pretty decent default look too (but, I suspect almost any developer will want to modify it). What's not to like about it?

Inventory Pro Editor - Item Editor

Inventory Pro also plays nice with several other popular third party add-ons. This includes Playmaker for those who don't want to dink around in C#. 

It also has custom functions for Behavior Designer which is a major plus in my book as I intend to use Behavior Designer as my AI engine. 

If you are intending on building game with a fairly typical or standard use of inventory then Inventory Pro should be on your short list of assets to check out. However, if your design has some non-standard uses you should keep reading. 

The Other Side of the Coin

As I continued to explore and think more about the custom needs my game was going to have I was becoming discouraged. The code base is all open source, which is greatly appreciated, but it feels like a mess of inherited classes and prefabs. Ugh. The documentation is decent, but doesn't do a great job of describing how to truly customize the tools. The learning curve is moderately steep.

The odd blog post by the developer were very helpful and cut hours out of my work. The needed info is out there, but it can be a little hard to find. 

When trying to setup a scene you can't simply drag and drop UI prefabs in the scene. They don't easily slide into a scene because there are too many connections that need to be made. Too many prefabs that need to be dropped into the inspector or combination of components that are required. It's certainly possible, but it's not easy.  Adding the UI to a scene is best done by copying from a demo scene and then turning off the parts you don't need - a custom editor to add the parts you want and get them all connected correctly would be a major plus and make the product that much more user friendly. 

There is a cost to using someone else's code base... That shouldn't be a real surprise. I got frustrated enough with Inventory Pro that I spent a few hours working to roll my own custom inventory code. It was all going well until I began to write a custom editor to create content. I went running back to Inventory Pro and I'm very glad I did.

Custom Windows

I mentioned a chicken, so why not include a image of my chicken?

For Game #2 I need some custom windows for resource consumers and resource processors. A resource consumer could be something such as a steam engine from my previous post that may take in wood or coal and produce a more usable form of energy.  While resource processors may be something such as a windmill that will process corn into corn meal that can be used to feed your chickens, i.e. turn items into other items.

Each of these custom windows is easy enough to create from a purely UI perspective, but coding them took a bit more especially as I was to digging through someone else's code. 

A resource consumer is very similar to a vendor in that individual objects in a scene will have there own collection that is loaded into a common UI. The main differences being that the resource consumer needs to do something with the items even when the player is not currently using that object, i.e. a steam engine should continue to burn coal and produce energy when the player is busy elsewhere and I don't want to be selling coal to a steam engine...

A snippet of the some of the custom code - All in all there's several hundred lines in the new classes some is copied other bits are mine

Rather than inherit from the vendor classes, which would bring functionality I didn't want, I chose to essentially copy the vendor scripts (ItemCollection and Trigger) and modify the scripts once I had basic functionality working.  The result was a custom trigger script, custom UI window (damned ugly at the moment), a custom collection script that controls what is shown in the UI as well as a base class resource consumer that is designed to be extended for a variety of resource consumer objects (steam engine, chicken feeder, etc). 

I promise it won't be this ugly in a final build

The resource processor is a bit different. At its core resource processing is very similar to crafting. Items go in and products come out - all following a blueprint. Given that Inventory Pro has a built in crafting system it seemed worth the time to fight through the code to create a custom "crafting" window that would meet my design needs. 

The idea here is a that a player (or NPC) drops off some items to be processed and it gets turned into a different item that can later be collected. This means that the UI needs to have an input and a output collection/inventory. It's also required that each individual scene object has it's own input and output collections to that get loaded to the UI when the player interacts with the object. A final two requirements is that the resource processor continues to work when the UI is closed and that the products get assigned to the correct scene object when the processing is done so the product doesn't get lost and the player can collect it later.

A snippet of the Custom Trigger

This last requirement was the biggest hurdles and required about an hour of hunting through code to follow the flow of the information. Inventory Pro has a "craft info" class that contains all the basic information which gets passed through about 8 different methods before an new inventory object is actually created.

I almost lost it at this point. Lots of deep breaths needed. 

To get it all working required an addition to the CraftInfo class to track what object had ordered the product to be created. This allows a finished product to look up where it was supposed to go and assign it to the appropriate collection. 

Custom Inventory Items

Default Item Types - Plus 3 of My own

While I found the process of adding custom windows and functionality challenging and frustrating, adding custom inventory item types was easy and almost fun. Out of the box Inventory Pro comes with several default item types, but anything beyond the typical RPG will likely require custom item types.

Different types have different properties (oh, shocking). These properties are not particularly well documented or at least I haven't found the documentation. Thankfully most are self explanatory. 

Game #2 is not the typical RPG with the collection, crafting or upgrading of gear playing a central role. Rather most inventory will have some use in creating something in the world. This might be a shovel that is used to prepare the ground to plant a crop or coal that will be used by a steam engine to power an industrial building. Inventory Pro's items all inherit from a parent class that calls a Use() function. This function can easily be overridden to perform any actions needed. The Use() function is called when the player uses the object. Which can be done from inside the inventory or from the skill bar.

A sample custom USE() function for a tool item type.

The Use() function returns an integer that indicates whether the object can be used.

In the case shown using the tool will call an outside public function that toggles a mode of the game (i.e. use a shovel and you can dig to plant seeds). 

The inventory item can also have public variables that will be displayed in the Inventory Pro editor. For example the Tool Type enum can be set for each inventory item of this type inside the editor which makes for easy and organized content creation. 

The ease of creating custom inventory items was a stark contrast to making custom windows and triggers. Why can't the rest be this easy?

The Final Verdict - Inventory Pro

Inventory Pro caused me a good amount frustration, plenty of swearing but also gave me a much more functional inventory system than I could have created on my own.

If you are looking to build a game with non-standard use of inventory and aren't comfortable with C# then you should probably look else where or be willing to hire a programmer to code up some custom solutions. 

But if you don't need custom functionality or if you are comfortable with C# and reading someone else's code then Inventory Pro can solve your inventory needs far quicker than you'll be able to roll your own solution. Mucking around with the custom windows wasn't particularly fun, but the end product was worth the time and money.

Energy is Everything

Game #2's design is fairly well established in my head and on paper, but I'm still very much in the stage of exploring what I can reasonably do from a technical perspective - not to mention from a time perspective. (Read as: I'm trimming down the scope by figuring out what I can or can't do.) I'm running through the big picture list of features to make sure that each can be implemented in a way that I like and fits the vision for the game. This is an iterative process. As features are implemented other aspects of the game are getting adjusted or redesigned, but that's not exactly news worthy...

Energy

A core feature/game mechanic of Game #2 is going to be energy. Energy is everything. With more energy we become more productive. With more efficient use of energy we can do more with less. The use of energy is what allows for modern society to function and, to hint at a game mechanic, use of more energy allows for a higher standard of living. 

There's of course a dark side to energy consumption.Increases in efficiency allows more to be produced with less. That might be less workers, less energy or less effort. All of which improve the quality of life. While this can drive down prices, increase production and consumption it also has the effect of higher unemployment or underemployment - i.e. the current stat of the rust belt. 

A rigged and animated steam engine model. This was also the first animation I'd ever rendered in Blender - GIF made with GIMP.

This give and take concept is something I very much want to explore in Game #2. The first step of which means I need to develop an energy mechanic. The mechanic requires the "generation" of energy (the physics teacher in me cringes writing that), the distribution of the energy, and the "consumption" of that energy.

The game is likely to be set in the industrial revolution time period. So... Steam engines!

Steam engines can provide a local source of energy. They can be fed with wood, charcoal or coal - really anything that'll burn. All of which can be found or produced easily with low tech methods. Steam engines can be built on site in a variety of sizes. Seems like a win. So off to Blender I went to see if I could produce something that I liked. 

A view of the rig in Blender.

Nothing profound in the modeling department, but rigging and animating is still pretty new to me. I didn't want to "fudge" the animation I wanted a rig that with the rotation of a single object could animated the entire model.  I wanted this for ease of animation as well as for a degree of realism. 

A combination of bones and constraints to tie the mechanism together and allow smooth animation. The constraints of copying location, rotation and or scale were all new to me and opened my eyes to a new world of possibilities. I'm excited to play with more mechanical animations...

There are very few tutorials on mechanical rigging - I might put one together in the future. Who knows?

I'd like to work renewable or at least pollution free energy sources into the game as well. At first glance windmills are a pretty obvious choice - so those will be added at some time in the future. At the moment I've avoided rivers (as I have no idea how to make a good looking low poly river) so water power is more or less out for the moment.  

Energy Transfer

Power Lines - Mostly eye candy at the moment

Power Lines - Mostly eye candy at the moment

The industrial revolution largely used mechanical energy which (clearly) has limitations. Moving towards electrical power as a way to transfer energy could help in several design areas, but could break the immersion or at least a sense of believably.

While it may not fit with the (current) intended time period I spent a little time playing around with power lines. Being able to generate power in a centralized location could lead to higher efficiency and more contained pollution. This is further specialization would allow workers (and the player) to spend more time doing something besides feeding fuel into a steam engine. 

Borrowed Code that when passed an Array of Points with Return a larger but smoother array of points - Don't Remember the Source, Oops.

I can see the game going away from a historically accurate time period (ha, as if I'm capable of historical accuracy), but I don't want to delve to far in to fantasy or steampunk styles either... 

The power poles are just to cubes scaled to look like modern poles. The lines are line renderers that start with three points and then are smoothed by some (borrowed) code to add additional points. 

The performance of moving the poles is pretty bad and will need some optimization if the code makes it into a build. I have to redraw all the lines when a pole moves - at the moment EVERY line is redrawn.

To be honest the power lines came out of frustration (lack of creativity) with another idea. They may just be a short lived idea that goes away.

Some form of energy transfer mechanic will need to make it into the game whether that is power lines or not I have decided. At the moment the energy transfer mechanic is simply the player or hired workers stoking the fires of steam engines - I think a step up in sophistication would be good.

Plenty more to iterate on...

Graphing Script - It's not exciting, but it needed to be made

A download link to my graphing asset is at the bottom of the post - if you want to try it out.

Game #2 will likely be centered around economics as well as climate (change). Deciding where to build a farm will likely be best done when looking at some climate data. Does it rain enough? Maybe too much? How hot does it get? Is the ground water polluted? Or looking at historical prices of commodities may help a player decide what type of business to pursue or how much they can afford to pay NPC employees. I don't want the game to be a data crunch fest, but data will be a part of the game. So naturally I'll be needing a way to visualize that data and graphs seem like a good way to do that. Pretty sure players don't want to read a list of float values.

Visualization - Basic line (scatter) graph

Graph Maker

I'd seen Graph Maker on the Unity Asset store and bookmarked it many months back. The reviews are pretty decent and it is definitely capable of a lot of heavy lifting. I'm aware of at least one reasonably successful game that has made use of it. So it seemed worth the risk of a few bucks. Graph maker clearly has had hundreds of hours poured into it. It's polished and feature rich.

All those features have also caused it to be fairly complicated. Each graph has several nested prefab elements each with scripts attached. The documentation is also a bit rough. As a new user the number one thing I want to know how to do is send the graph a list or array of my data and have it graph it.That's it. One simple function. So where is it?

I spent a while clicking around trying to figure out where the data was stored (turns out to be in the series prefab/script). I opened the documentation and couldn't find clear directions of how to send my data to the graph via script. I opened the scripts in search of the list or function that would import my data... Couldn't find what I was looking for.

There is a neat reflection script that can be attached to gameObjects and looks like it could do some handy stuff, but I couldn't get it to do what I wanted. All in all the asset looked way bigger than what I needed. Do I need radial graphs? I don't think so... 

The second thing I want to do is modify the appearance of the graph. The shear number of (nested) prefabs not to mention the number of settings in the main script it seemed like it was going to be a long battle to customize the looks of a graph.

So as I so often do, when I can't figure out an asset I start down the path of rolling my own asset. If you have more patience than I do, I know that Graph Maker is a good asset and will make pretty graphs for you. 

Rolling My Own

The goal of rolling my own graphing asset was to make something simple, lightweight and easy to use. As of writing this post my graphing asset has 6 prefabs and three scripts (one of which is a custom inspector to allow graph updates in edit mode - another detects mouse hovering). The prefabs largely consist of gameObjects with just an image component. A few such as "tick marks" or "axis labels" have children with Text components, but nothing gets more complex than that. Sending data to the graph is done with 1 of 3 functions. Pretty simple. 

Just send the data and let the graph do the rest.

In the end it's taken me way longer to roll my own graphing script then it would have taken to figure out Graph Maker. Is mine as pretty? No. Does mine do nice tweening animations? No. But I know how mine works and I know how to modify mine if I need to.

The feature list is short. It can switch between line (scatter) and bar graphs. The axes, points, connecting lines, and tick marks can all be tweaked in size and color. 

Bar graph of the same data as at the top of the post

Fonts, font size and font colors are all of course adjustable as well. Modification of the images was left out of the inspector/script and can be done with the prefabs. This was done for simplicity and the simple fact that changing images is less of a "tweak" than font size might be. 

I still have one feature to figure out and that's auto-scaling. Currently the axes will auto scale and adjust to fit the data, but the values displayed on the axes does not. I'd like to figure out some basic auto scaling to keep things simple - sure I can manually adjust the values in the inspector (or by script if I expose the variables or add a new function), but that's hard to do when the game is published... I like to be involved the community, but manually adjusting each player's graphs is a bit much. I'll keep the linked package up to date if anyone has ideas of how to auto scale I'd love to hear them.

Edit: The auto scaling is now working. 

Download (Free)

I may polish the asset a bit more and put it on the Unity Asset store, but that's a lot of work for not much of a return. Until then I'll happily handout a free download (box via goo.gl). Feel free to use it or modify it. Just don't flip it and sell it - don't steal my $12 in potential sales! If you do use it I'd love to hear about bugs or ways to improve it (but not bloat it). 

Not until writing this post did I realize I named my asset the same as the one I'd purchased. Oops.

Tutorials: Low Poly Snow Shader

My last post was about adding snow visualizations into Game #2. In the end I came up with a custom shader that ran faster than an asset I found on the Unity Asset Store. In my (quick) research I didn't find a tutorial showing what I needed, so I thought I'd do a quick series and show my project. The tutorial series covers the full creation of the shader (in Shader Forge) as well as a simple script to control the snow effect scene wide. 

If you want to see more details about the creation of the shader or if you'd like to try it out (download link in the video description) then check out my tutorials series. The first video is just an intro and explanation of what's to come. If you want to get to the meat then click here to skip to Video #1.

Intro video showing what will be created in the rest of the tutorial. Shader Forge: https://www.assetstore.unity3d.com/#!/content/14147?aid=1100lHSw Tutorial Assets: https://app.box.com/s/npupei7px4tjavkkg4gtbz3y3mj6b73b

Low Poly Snow Shader

With the environmental simulation getting near to finished it was time to start looking at how to visualize the weather. I'm using Tenkuko Dynamic Sky for my overall lighting and day/night cycle. It's not perfect, but makes my scenes look so much better than I could do on my own. It's worth every dollar.

Seriously. This looks good. This took about 3 clicks...

Tenkuko does a great job for general lighting it also has functionality to support rain, snow, fog and clouds. The clouds aren't perfect  and probably won't work for a low poly game. What Tenkuko doesn't have is snow accumulation. So I started doing a bit of research to find a solution. 

Global Snow

I headed over to the Unity Asset store and picked up Global Snow. It's beautiful. Truly. It supports flat shaded snow as well as two other modes that produce more realistic snow. The asset doesn't require you to change shaders or materials, but simply adds a script to your camera.

Global Snow with Flat Shaded Snow

I was seriously impressed. It took maybe 5-10 minutes of messing around with settings and I was pretty happy with how my scene looked. The bummer came when looking at the performance hit. Now a little performance hit is no big deal. The the snow scripts are not going to be used all the time. Plus the game is not an action game so a small frame rate drop is not a big deal. All the same I'm still aiming for 60+ fps on reasonable hardware.

On average I saw a 5-10 ms hit... At max settings it was sometimes 20 ms.

Full disclosure, the scene I'm running this in is huge. The terrain is roughly 2 km square and its totally NOT optimized. Meshes are not joined and no occlusion culling is being used. Many of my trees have no LOD on top of all that. Unity says it's rendering 10+ million verts, so not a tiny scene. Still a 5-10 ms hit is a lot. Not a deal breaker, but enough to make me look for another solution. The last line in the profiler is a script I'm using to control my custom shader.

If I had a smaller scene or a simpler game I'd definitely look at Global Snow as a potential snow solution. I may give it another try once my scene is more optimized too. 

Custom Shader

This is probably what I should have done first, but like a lot of us out there in game developer shaders scare me and seem like black magic. I watched a video or two and dusted off an old shader book I had. The result was the creation of a custom low poly (flat shaded) snow shader using Shader Forge to create the shader. 

If you haven't seen Shader Forge it's worth a look. The interface is all visual/nodes but it compiles as a proper shader script. This means that shaders can be shared and run on computers that don't have Shader Forge. In theory this should also make the shader run more efficiently - not sure how it would compare to a carefully coded shader. 

The final shader all wired up in shader forge.

The snow shader has height dependent snow and frost (upper left nodes). The frost essentially eases or fades in/out the snow. The shader also has a snow coverage slider that allows a selection based on normals so that snow can be just on top all over or somewhere in between (middle nodes).

Show Material Options

Producing the shader took me a handful of hours. Mostly because I'm totally new to shaders. But the result is pretty decent. Granted it's not a complex shader, but I'm still pretty happy with it. Below is a screenshot using my shader (same angle), compare it to the earlier screenshot using Global Snow.

Same angle as with Global Snow, but using my custom shader.

Is mine better? No. No way. But it is a whole lot faster. I didn't get exact numbers but at most I saw 0.5 ms difference between my shader and the standard shader (I'm rendering 10+ million verts in a very un-optimized scene). I suspect that was just random fluctuations more than anything.

Some work on the "snow texture" to give a bit more depth and variety will make the two very comparable. Probably moving the snow color just a bit away from pure white will also help.

Tutorials

I'll probably make another post, but if you're interested to see what I've done or better yet try it out and tell me how to do it better. You can check out my YouTube series on the snow shader.

Environmental Simulation Part 2

This post is a continuation of a earlier post - find it here.

Continuing the journey of an environmental simulation we have now come to the hard part. Or at least the part that has been giving me fits for the past several weeks.

Water / Rain Cycle

Creating the water cycle was a fair amount of additional code. Most of what is described in the previous post is controlled by two scripts - a climate manager and a data containing script attached to each climate block. Adding the ability for water to get transported by clouds added just a couple more scripts but plenty more interactivity between those scripts. Which makes for so many more potential bugs, wrong ideas and as it turns out a few floating point issues.

The Basic Idea

Water is stored in the ground as (shocking I know) "ground water." This will represent water that plants and crops can use to grow - with plants having ideal or preferred conditions that allow optimal growth. Ground water flows between neighboring climate blocks and evaporates depending on temperature. All evaporation and ground water flow stop if the temperature is below freezing - not totally physically accurate, but maybe to a first approximation it is... I'm not about to start modeling sublimation! This causes water to build up during the winter and provides wet soils for spring crops. All in all this matches with what I want to accomplish, but will likely need lots of tweaks and balancing.

Early Attempts playing around with rising sea level

The final step to the water cycle was to enable clouds that could carry water while being pushed by the seasonal winds. The ground water or ocean water evaporates and generates localized humidity. When this humidity hits a cloud formation threshold a cloud is spawned and the moisture contained in the humidity is transferred to the cloud. The cloud is then free to ride the winds and will begin to drop is water when it certain conditions for a climate block are met - essentially cumulative humidity plus cloud water content equals a given threshold. 

Getting the basic mechanics up and running was fairly easy. Isn't that true of most game design elements?

The struggle came in balancing the cycle. Now it wouldn't be hard to simply have the ground water fluctuate with the seasons, but I want more variability than that solution could provide. I want rain shadows from hills, I want the coastal regions to be wetter,  I want localized flooding, I want rain fall to be tied into larger climate factors... I want a simulation rather than hard coded weather or totally random weather. 

Challenge #1 - Cloud movement

Getting the clouds to move over land and drop water has been tricky. If the cloud drops all of its water back in the ocean that's okay, but if every cloud does that then there's no rain... Creating a on and off shore breeze was key to this. Hot ground with cool atmosphere above it causes an on shore breeze, while cool ground tends to cause off shore breezes. 

Challenge #2 - Water Return

Once the water has made it to the ground it then needs to cycle out via evaporation (cloud formation) or flowing back to the ocean. For simplicity (haha, I can anyone say over scoped?) I don't have rivers in the terrain. So they aren't an avenue for the water. The water must flow through a climate block's neighbors until it reaches the ocean. 

Challenge #3 - Dynamic Balance

Since the world should react to the players actions, but do so in a way that is "reasonable" the water cycle needs to somehow dynamically balance itself. I think the fancy term for this is "stability." Yes I want the water cycle to speed up or slow down, but it shouldn't be unstable - the "butterfly effect" is cool and all but makes for lousy game play. So far most simulations have been very unstable with tendencies towards drought or flood being very common. Hmm.

Basic climate stats plus ground water heat map

Basic climate stats plus ground water heat map

Idea #1 : Open System - Endless Water!

At first I tried an open water system. The ocean for my purposes would be an infinite source and sink of water. After every cycle the water content of each ocean climate block would be reset. This seemed to make sense as the amount of evaporation from the ocean would not be heavily dependent on how soaked the ground might be (since evaporation rate is dependent on ground water content). This led to a highly unstable system. Small tweaks in variables would cause massive and consistent flooding. While other tweaks would cause complete drought. Not good.

To add to the struggle a year in-game takes about 5 hours to simulate (at current settings). So Each major or minor tweak required 10+ hours (2 in-game years) to see what difference had been made. Ugh.

Why did I choose this game? I keep telling myself either "I'm an idiot" or "good things only come with hard work." The longer this balancing takes the more I tend to hear the first message.

Idea #2 : Closed System

With plenty of moaning, groaning and head scratching I tried desperately to find a new mechanism for water transport - not different from clouds and rain, but different in the mathematical sense. 

I realized that my ground water flow simply wasn't cutting it. It wasn't moving water fast enough and it was generally moving the system away from stability (flood or drought). 

The new model has 3 significant changes to the water cycle.

  1. The system is now closed. The ocean will not visually dry out, but the amount of water in the world is now constant - no more infinite source or sink. So as ocean water evaporates it is not replaced until it rains or water flows from the ground back to the ocean. There is a few lines of code that check the total water in the system and add and subtract as needed - just in case.
  2. There is now a "target" for ground water. A PID controller (overkill?) adjusts the water flow rate for each climate block to slowly return the ground water content to a target value. I don't like having this, but it seems to add stability.
  3. An adjustable portion of the ground water flow now returns directly to the ocean no matter where that climate block is located. This required that each ocean block is not independent but shares a large pool (no pun intended) of ocean water. This functions as underground streams which are a real thing or so I've been told.

Early Implementation of a PID controller for the ground water

At first blush this approach didn't work.  The result was still an unstable system quickly alternating between floods and droughts. To add to the challenge the system wasn't actually closed... Oops.

Idea #3 - Closed System with New Water Transport

At this point I was ready to give up. Really and truly. It had been weeks of struggle with little that would work in a commercial game (even a small time indie one). I took a little time off while I ran 12-24 hour long simulations - I was irrationally hopping to find stability with small tweaks in parameters.

Once I pulled my head out of my butt I started to rethink the cause of the system not being closed and how I transported the water. 

The cloud mechanism made a lot of sense as water transport, but it added substantial complexity and inter-connectivity that I wasn't excited about. The clouds had the added bummer of being physics based which needs to run on the main thread in Unity. This not only results in a (slight) slow down, but a decent amount of interplay between the a "cloud thread" and the main thread that's running the physics engine. This seemed like a very good potential candidate for causing the system to not be closed - errors given the complexity and syncing data between threads. 

I rewrote the water transport code to get rid of the cloud and to use humidity to move water from neighbor to neighbor based on relative levels of humidity as well as the direction of the wind. This allows humidity to both spread around the map and to move with the wind. Since only the direction and magnitude of the wind is needed all of these calculations could be run off the main thread. Nice bonus! 

I ran a few simulations with this new mechanism and was generally happy with the result, except the system was still not closed. After 30-60 minutes there was a noticeable error in the total amount of water in the system... Shit.

The errors per simulation cycle were tiny. Almost not there. I tracked down a few to simple small mistakes in coding. Simple mistakes that with larger numbers would have shown up much earlier and easier - when you're changing a value in the 6th or 7th decimal it can be hard to see the problem. Some of the others were harder to find.

Some of the error was simple floating point errors. Most values in the simulation are between 0 and 1, but a few such as the total water are in the hundreds. Now I don't claim to be smart enough to fully and deeply understand floating point errors, but I know they exist and I could see them creeping into my simulation. The errors in some of the larger values were bigger than the changes in other values...

Since I'm targeting PC (and maybe OSX) I'm not too worried about memory - at least not yet - I switched the whole simulation to double precision floats.

AND?

At long last the simulation was stable. Not perfect. Not balanced. But stable. I ran the simulation for over 30,000 cycles and saw an accumulated error of 0.00001 in a value that was close to 1000. I may have danced a little when this happened. Which led to the most wonderfully boring GIF I've made (watch that last digit change).

ground water is stable!!!

I have a dream that the hard part of creating the simulation is over. Let me have my dreams! 

So what remains?

  • Tweaks and balancing
  • Pollution and movement of pollution
  • "Green house" effects from clouds and CO2  

In reverse order... The green house effects are already "coded" but currently have no effect (multiplying by 1 type of thing). So adding that functionality might fall under the tweaks and balancing as much as anything. Not too worried about that aspect. I am interested to see how the cloud based green house effect will effect the system. The wind flows from hot to cold and clouds will have a tendency to insulate. So areas shouldn't get as warm or get as cold. Hmm. Maybe a net zero effect? 

The CO2 will of course have a similar effect, but will be global rather than local like the clouds. The difference with the CO2 effect is it has a lot of interacting parts. There will be several CO2 sources and several sinks. Once again getting that balance could be difficult. The first phase of the game is unlikely to have substantial sources of CO2 so full implementation of the greenhouse effect may wait until large industrial structures are available. 

I wanted one more picture in the post. So here's some poppies.

Pollution will just be a double precision float variable like ground water. My plan at the moment is simple, have pollution move with ground water. A percent of the pollution will move with each cycle and spread to neighboring climate blocks as well as into the ocean. There will be some decay of pollution - i.e. it just goes away. How exactly that will work is unclear. My thinking is that pollution will accumulate in the ocean and break down while there. This leaves the door open to allow pollution to make its way to the player and NPCs via drinking water and eating fish or other food containing pollution. We'll see.

With the simulation now stable, I'll be turning my attention back to creating a playable game loop. There'll likely be a "Part 3" to this series of posts, but that might be a while. 

 

Environmental Simulation Part 1

When I settled on the current game design idea a central piece was an environment simulation that would effect player experiences and that player choices could in turn effect - creating a feedback cycle.

Iteration 737 - Humidity Heat Map

The goal wasn't (and still isn't) to create an environmental simulation that was "physically accurate." The goal was to create a simulation that was an abstraction of reality or at least had some of the key features seen day to day and year to year. I wanted the player to be able to alter the world around them in a way that reflects reality but that doesn't need to be 100% realistic. 

Key Features:

  • Day to day temperature swings
  • Seasonal temperature swings
  • Wind to transport moisture
  • Water/Rain cycle
  • CO2 effects
  • Pollution accumulation and transport
  • Runs off the main thread

Building Blocks

The first step in creating the simulation was to break up the environment into a series of blocks. Each box would have it's own set of environmental variables (temperature, humidity, ground water, wind, etc). These "climate blocks" would interact with it's neighbors to create localized weather and also to allow local variances such as terrain height and cloud density to impact the weather. 

Test Terrain with Climate Blocks

As the simulation developed and more complex interactions were add a few changes/additions to the climate blocks were needed. The first critical piece was the addition of an "atmosphere block" on top of each climate block. The atmosphere block is simulated air space above that often has a different temperature than the air on the ground/ocean. This allowed for up and down drafts that could help move clouds and cause an on or off shore wind depending on the season (more about this later).  Without an onshore wind clouds and more importantly rain rarely make it to the land.

A second key addition was the classification of terrain types. At the time of writing this the simulation is only using three types of terrain ocean, grassland and mountains. This largely controls the "target" temperature of climate block and in the case of the ocean maintains a constant saturation of ground water. Oceans have moderate target temps with smaller seasonal and daily fluctuations. Grasslands have a higher target temp than the mountains but both have larger daily and seasonal fluctuations than the ocean.

Daily and Seasonal Temperatures

Seasonal sun intensity is controlled by an animation curve that is sinusoidal in shape. Max values occurring during the "summer" and of course minimum values occurring during the "winter." A second curve was used for daily fluctuations. The curves are currently identical... That may change in the future. 

At first these curves were used and tuned to be a true energy flux with energy being added during the day and energy lost during the night. While more physically accurate and potentially allowing for more emergent weather, it also made it far more difficult to tune and balance. After significant testing and tuning this method was abandoned for a more controlled method. 

Each terrain type has a median temperature that serves as a target temperature. There are also values for seasonal and daily fluctuations of that temperature.  This means that median temperatures + seasonal flux + daily flux is roughly the high temp and likewise median temperature - seasonal flux - daily flux is roughly the low temp. Variance from this is caused by the connection of neighbors and other factors. 

One of the other factors that adds some variability is the average height of the terrain. In the real world the higher the terrain the cooler the air. To reflect this each climate block samples the terrain height at multiple points and calculates an average height. From this the median temperature is adjusted slightly. This provides variation in the climate that (hopefully) lends itself to more interesting and emergent weather.

Wind

Wind in the simulation does not  have a physical presence and is simply a Vector3 that stores the wind velocity. The wind for an individual climate block is calculated based on the temperatures of the neighboring climate blocks, including the upper atmosphere. The inclusion of the upper atmosphere allows up and down drafts which allows for onshore or offshore breezes (as mentioned above). 

To calculate the wind the simulation calculates a temperature difference between the climate block and a neighbor and then multiplies that by a vector that goes from the climate block to the neighbor. Final direction (sign) of the wind is based on blowing from hot to cold. 

The simulation sums all the winds due to neighbors to arrive at a (nearly) final wind value.

A prevailing wind is then added. This allows larger global winds to be added to create larger and different weather patterns. The strength of the prevailing wind is a tune-able variable. Current testing is with an in/out pattern that helps to blow clouds away from land in the summer. 

An early WEather Prototype

After the prevailing wind is added the vector is normalized. There was some debate about normalizing the wind...  In the end the choice was made to keep the normalization as this meant that clouds always would have some wind. It also prevents unrealistically large or small winds that become problematic when trying to transport clouds/moisture.

The final step is a check on the vertical component of the wind. Since the upper atmosphere is often at a very different temperature it can therefore be the dominant contribution to the wind. This is a problem due to only simulating two layers of atmosphere rather than more layers or the ideal of a continuous atmosphere. Effectively the vertical component is clamped to a range between -0.5 and 0.5. This helps to keep clouds generally moving horizontally.

Additional controls are needed to avoid the clouds going too high or going through the ground. The altitude of the clouds is mostly visual as the horizontal location determines where clouds can deliver rain. Because of the this a simple min and max altitude are set. Clouds check against these values and degrees of freedom are restricted in the rigidbody to prevent clouds from going outside the bounds. Checks on vertical velocity are also necessary to allow the clouds to move away from the limits. 

Continued in Part 2

In Part 2 I'll discuss the most difficult part (so far) of the simulation that being the Water and Rain Cycle. Or more specifically the balancing of that cycle.