Friday, November 15, 2013

Goods and Production Rate Balancing

The economy of Cultura is serious business. It's also set in the paleolithic age. For the alpha, the technology and economy will span only the paleolithic age. The "full" game, first iteration, will span from paleolithic to neolithic (the three ages will be paleolithic, mesolithic and neolithic). So let's take a look at the various concerns by splitting the economy into its various stages.

  • Sourcing Raw Resources
  • Collecting Resources
  • Producing Goods
  • Consumption

Sourcing Raw Resources

The beginning starts with a small band of sentients (human, ogre or elf) exploring an unknown landscape. There's no fog of war but the map is large (think Anno 1701 size). There's plenty of space. There's trees, bushes, grassy patches and animals. At the start, trees and animals are plentiful. Bushes and grassy patches are scarce. Once you pick up the technology of planting, you get to shift the balance. You can plant new trees, bushes, grasses and whatnot to improve the growth rate of the land. You can replace what plants grow where (but climate penalties will be there). Animal population will depend on some plant in each land region, remove it and you lower their growth rate.

Renewable resources (anything falling under the tree, bush, grass and animal category) can grow faster at first by simply planting more of those plants. Once you start researching agriculture techs then you can improve the growth rate of plants in your land regions. A year is broken into four seasons. When a plant or animal hits its growing season it starts replenishing its resource. If it's already at max then it starts to spawn new versions of itself (trees grow new trees, animals give birth to new animals). Growth rate of plants depends on the number of plants. Animals births are limited by the plant they are dependent on.

Non-renewable resources have a "draw limit". You can only take so much from it before the site is "exhausted" and you must "find more". Why all in quotations? Because the game is meant to be played as long as a player feels like, if I were to put in actual numbers for the amount a non-renewable node held then there is also a limit on how long the game is played. I could always put in a really high number that is physically unreachable but psychologically speaking it's nicer to just be infinite. Another choice is to bug the player to do some more prospecting to magically find more resources every so often but meh it's pointless and adds nothing. Technological improvements increases the draw limit and is themed as increasing mining/quarrying technologies.

Balancing! This involves an excel sheet and lots of numbers. The question asked is "How many people do I want to be able to live in a particular land region at full goods consumption?". Also what is "full goods consumption"? That is, how many goods do I want people to be able to consume? Here's what I'm thinking:

  • Paleolithic: 6-9 Goods per capita
  • Mesolithic: 12-15 Goods per capita
  • Neolithic: 18-21 Goods per capita

For balancing purposes, this means you need to be able to source enough materials per capita to supply 6-9 goods and have enough left over labour output to produce those three goods. When you first start, your labour output is capable of producing about 2-3 goods and collecting the materials for them. By the end of finishing the Paleolithic industry technologies, then you are able to hit that 6-9 range. The timeframe for a particular age I'm aiming for is 4-9 hours (plenty of time for building a city, enjoying it, getting into trouble, dealing with politics and other AI players and setting up complex trade routes for a multi-tier industry).

Collecting Resources

Having said a mouthful before hand I can be more brief here. Collecting resources is just about sending all your people out there and then stripping the earth of its bounty. Technology improves the rate at which you do it via your stone tool. The stone tool will be a magical repeat technology which you can pour tech points into and will give you bonuses and also when you hit milestones give you named bonuses (such as "biface" or "burin").

Like before, it is balanced such that 50% of a person's labour is used up for collecting enough materials for 6-9 goods at maximum technology. You start off at around 2-3 goods at 50% of labour.

The main concern about collecting resources is that the player must watch the ecological damage caused and ensure that they properly balance growth technologies. If you clear cut a forest, it is gone and the trees spend a very long time trying to recover (because growth is based on the number of plants or animals). You can help to plant more trees or bushes though through agriculture (bushes and grasses) or silvaculture (trees), animals have no technology. Those technologies aren't available until neolithic though.

Producing Goods

After your hard work growing stuff and collecting it, now you mash it with your hammerstone repeatedly until it becomes something awesome... like bread or beer. Because hammering wheat with a stone makes beer. Trust me.

Essentially, people will grab what resources you've collected and turn them into goods. These goods are then distributed as you see fit. There isn't much more to say... collect stuff and turn it into usable stuff. The target is 6-9 goods produced at maximum Paleolithic tech.

Consumption

The game revolves around consuming ever greater amounts of goods to improve your health and happiness to levels that support ever greater populations. With more people comes more problems (plagues and riots, your choice... or perhaps as the Swedish say "Choose between Cholera and Plague"). But with more people comes larger armies, larger cities, more complex industry chains and so on.

Each good when consumed provides health and/or happiness. A city (all the people in a single land region) have a graduated requirement. That is, the first 10 people require nothing. The next 20 require 5 happiness/5 health each. The next 70 need 15/15 and so on. A good is consumed in one minute, a year is one hundred minutes and thus 100 goods are consumed in a year to be continuously consumed.

Property lasts 1 minute and then becomes "damaged" and requires upkeep. This means a person buys an intermediate good and it instantly repairs property in her possession. Consumable goods lasts 1 minute and then disappear when finished, thus requiring the person to buy more (food is a consumable as an example). Super property lasts forever and requires no upkeep. It however costs 10x as much materials and labour to produce than a typical good.

Finally, I do intend to put in some "slack" labour output. This allows for labour wasted due to walking around and carrying goods to places. There are also other functions that soak up labour such as house construction, people used up in conducting trade, people used up in policing or military services and the production of military goods.

Yay

In a short description, the robust economic system is meant to intrigue you in sourcing new resources to set up new industries (higher tier cross-requirement goods), while the UI is streamlined to ease the maintenance/expansion of existing industries. The result is a setting where you have a constantly expanding empire where diplomacy, war, trade, cooperation, subterfuge and all the like revolve around one thing: consume more goods. Well actually, it revolves around one thing... giganticus stacks of gold bullion. Mmm piles of shit.

Monday, November 11, 2013

Alpha Economy

Think about fields of giganticus stacks of gold bullion. Then remember that Cultura actually starts in the stone age so what you really have are stacks of polished gold rocks. So last time I talked about consolidating for Alpha, well this is about the actual economy.

Mmm.

Alright long story short there are 14 raw items: grain, fruit/vegetable, meat, stone, wood, earth, metal, bone, fur/skin, fibre, filler, herb, precious metal, precious stone.

Complicated enough? Of course not! This is an economy game. We expect flow charts that make your eyes bleed. The food type raw goods (grain, fruit/vegetable, meat) each lead to two consumable goods and one intermediate good. The others lead to one property good, one consumable good and one intermediate good. Precious metal and precious stone make one super property, one property and one intermediate. All of these goods are appropriately themed for stone age (although I haven't decided what exactly they will be quite yet).

What do I mean by those types? All goods provide health, happiness or production bonus. The type they are determines how they provide the benefit.

Consumable good is a good that someone will simply take and consume. As long as they are consuming it then they will receive its benefit. You can only consume type of an item. Higher quality consumable provides a better bonus.

Property good is a good you place inside your home and then gives you its benefit. However, over time they require upkeep which means it consumes one unit of intermediate good. In order to produce them they require the same intermediate good.

Super property is a good you place inside your home and then gives you its benefit. Then that's it. No upkeep and no repair.

There are 5 different residential buildings which consume all the property and super property.

Then there are 3 industrial buildings and 3 tools. This one is a bit more complicated, you might notice that I have been careful about production rates and ecological growth rates. What is important here is that I want a region of land to support 100 people continuously consuming all goods. So the base production rate is not capable of doing this; maxing out production rates is what will allows full consumption. A player needs to worry about ecological renewable resource growth rate (which can be improved via technology) and industrial bonuses (tools and industrial buildings and their associated technology). Essentially, a player has to balance how much they can take from the land without damaging it and how fast they can take from the land and turn it into goods.

For military, there are 3 weapons and 3 armour. This means 3 different damage types.

I've specifically not listed out the exact goods, bonuses and other numbers because they're likely to change quite often. However, this is what I plan to include for the Alpha. Most of the gameplay features now work so it's time to flesh them out with game data.

Resources and More!

The world of Cultura has been going on and I've been finishing up the xml loading portion of the game. Right now I've just finished what one of my friends call "jack-testing" (ie. it compiles) of the last piece of the xml loading; modular-izing the material selection window between the goods crafting UI and the building construction UI. Yaaay! In any case this brings me to a point where game design matters before continuing any further so I thought I'd consolidate the game for alpha at this point.

Here's what I'd like to have: 14 raw resources, 17 consumable goods, 7 property type goods, 4 super property goods, 5 residential structures, 3 industrial structures, 3 tools, 3 weapons, 3 armour. Of course, all the gameplay and dev-style UI to go with all these features. By the end of the alpha I'd like to have random level generation, fully fleshed out tech tree and wealth management UI (dev-style UI is fine).

Suffice to say, I like economics and I like playing games surrounding them. What I like most is being able to get a visual reward out of it. The core of Cultura is about building stuff, using the stuff and piling that stuff up into giganticus stacks of hoarding. This is why I like seeing new games on the horizon like Clockwork Empires. In any case, industry chains and goods piling? Mmm.

The exact idea is like this: Cultura is about building stuff and using that stuff to expand the number of people you can support. More people means more labour and more military manpower. Over-extending (by not watching your health/happiness) brings about negative consequences worse than the positive aspects of increased population. So the basic distillation of the game is: Harvest Resources -> Create/Trade Goods -> Consume Goods -> Expand.

As said before I like stockpiling good stuff so I invented the concept of "super-property" which for now is built off of two raw resources: precious metal and precious stone. These types of goods last forever, require no repair and give cumulative bonus. Everything else should be streamlined for consumption (rather than risk bottlenecks and pile up of useless goods). I might toy a bit with consumption rates and property use to allow cumulative bonus. It all depends on what is more fun with more tweaking. That aspect of game design can be left open.

Only the property type goods require an intermediate good to produce. This isn't always going to be the case but for the alpha goods it will be. I don't think I'll make a final decision on the exact material types and for now they will all be equal in value. The health/happiness system has yet to be worked out entirely but I can forge ahead with everything else and leave code stubs for those calculations. In essence, I want a way to encourage players to have a variety of goods. For instance, if you want pottery you could get blue clay pottery or red clay pottery. You can store up to 5 pottery in a display room. If you display a greater variety of different pottery the bonus is greater than showing the same pottery. But with the possibility of blue clay pottery, blue/red clay pottery, red clay pottery... what is the bonus of using blue clay, blue clay, blue/red clay versus blue clay, red clay, blue/red clay? In the latter case, you already have pottery that uses red clay but not a purely red clay pottery... however items with more materials in them give more value. I might calculate bonus based off of "sum of item level" and then a second additional bonus of "materials used"

I'll compile a list of exactly what goods will be in the game design wise but leave what they actually are open. That is I'll say I need a Bone Consumable Good but it could be "bonemeal". I'm leaving that open since I have no graphics yet and the Stone Age theme requires a bit of resource to see what exactly people back then had. I'll also leave out tech-themed goods until the beta (Mundane, Steampunk and Fantasy). But in general, the Mundane gets the advantage of being able to build more types of goods (and thus receive more health/happiness as a result) to compete with the advantages of magic (Fantasy) or advanced machinery (Steampunk).

Wednesday, October 2, 2013

XML and Scrolling

Cultura has a lot of different resources. And it might be overwhelming to a player who isn't all the rage into Dwarf Fortress or Anno 1404. So, in Cultura, the concept is simplified a bit. There are "items". You can see below in the list those are things like "grain", "fruit", "meat". Within an item category are "materials". So there are different types of grain such as "wheat" or "oats".

What this means is that all goods will require "items" (not materials). So when you want to make "flour", you use "grain". It doesn't matter what kind of grain. But using more types of materials creates higher quality items. Higher quality items last longer or give better bonuses.

The current list of items and materials are:

  • Grain: wheat, oats, rye, barley, stone grass, green brome, silk rye, bluestem
  • Fruit/Vegetable: juniper berries, crab apple, blackberry, strawberry, glowing mushroom, crab plum, yellow berry, tiger nut
  • Dairy: none for now
  • Meat: gazelle, seal, mammoth, sabertooth cat, unicorn, ice crab, dragon, direwolf
  • Stone: granite, limestone, flint, chert, stonewood, rune rock, aquaferra, dark granite
  • Wood: pine, oak, cypress, sycamore, silverleaf, ironwood, amberbark, goldwood
  • Earth: clay, sand, kaolin, silt, bright clay, dark shale, fire sand, frost silt
  • Metal: tin, iron, nickel, zinc, viper stone, cold iron, frost ore, amber nickel
  • Bone: gazelle, seal, mammoth, sabertooth cat, unicorn, ice crab, dragon, direwolf
  • Fur/Skin: gazelle, seal, mammoth, sabertooth cat, unicorn, ice crab, dragon, direwolf
  • Fibre: silk, cotton, ramie, hemp, giant spider silk, thread mushroom, rock string, yarn bush
  • Filler: papyrus, ryegrass, leadtree, burclover, hollow weed, elf blade, grey shrub, goldclover
  • Herb: tea, ginger, basil, cinnamon, glowing nettle, ember flowers, comfrey root, mandrake
  • Precious Metal: gold, silver, copper, platinum, mithril, adamantium, snow silver, null iron
  • Precious Stone: turquoise, diamond, jade, sapphire, mana crystal, moonstone, sky pearl, power stone

In terms of code the only trickiness surrounds meat, bone and skin. For those items they are refined from animal (or sentient) carcasses. Your hunters will go out, kill a gazelle and then harvest "carcass" type goods. These are then turned into meat, bone and skin. This means for the game purposes, meat/bone/skin count as non-raw goods! Instead "animal parts" is what you collect and then based on the material of the animal part you get different meat, bone and skin. You can then use those to craft further items. The xml that has been written looks something like:


<good>
 <name>Meat</name>
 <id>10000</id>
 <prereq>
  <req>
   <id>100</id>
   <amount>1</amount>
  </req>
 </prereq> 
 <category>
  <id>100001</id>
 </category>
 <graphic>
  <meshname>meat</meshname>
  <texture>meat.png</texture>
 </graphic>  
</good>

This gives a quick way to add in new stuff into the game. How do we parse it? Using rapidxml :) I'm not going to write a poopy xml parser when there's a million out there. Those aren't particularly interesting or hard problems to solve versus making Cultura. The intent is, afterall, to make an awesome game.

Using xml, the units, structures, goods and materials are all loaded at initialization. Then they are saved in the "gameEntityCreator". This class holds all the definitions. Whenever some components needs to make a new unit or structure or resource node etc, they call the gameEntityCreator to do so.

Next for the xml loading is to change the UI to make use of the gameEntityCreator and its list of definitions. The goal is modularity and moddability. While I don't have an intent in making the game mod-able, I do intend to have as little "one-shot" code in the game as possible through better design.

Some additional awesome fixes by a friend:

  • Game starts with the camera properly centered on your cave
  • No more scrolling unto infinity, it stops at the edge of the map

Sunday, September 15, 2013

Work Orders and Terrain

Graphics in Cultura is designed around the idea that what an artist draws is what they get to see in the game. That way, there's no strange distortions (other than effects) and so on, allowing artists to simply draw. As part of that, the terrain on the ground used to be rotated quads but no longer! They are now the same as everything else. In addition, the terrain drawing has been randomised using a single hard-coded seed. What this means is that if I have three different grass textures I could rotate through to draw a particular square, it will choose one at random but because the seed is hardcoded, it always chooses the same one so it looks consistent as you scroll around or reload the game.

Using some test tiles, you can see that they are pesudo-randomly chosen and it is always the same every time you load up the game or scroll here.

Work orders have also been finished off, minus UI styling. They list out the existing work orders and allow you to modify them.

If you create one, it will then list it out. This allows you to select it and change it.

The rest is taken care of automatically in the game. Workers will shift what they need to do. By design, if they are already working on an item, they will complete that before adjusting to the new marching orders. That's fine to me so that I don't have to deal with partially finished goods.

Sunday, September 1, 2013

Item Crafting and More!

Features Completed

It's been a while since I posted the last feature complete type of post mainly because the item crafting feature involved a lot of moving pieces. But it's done! The goal after this is expanding it out (I wanted to be able to select a unit and then have an item crafting button at the bottom in a limited action panel) and also to build more infrastructure to support it (I've decided that I'll just go with xml data loading during initialization).

So what was done?

  • Industry Management Screen
  • Work Orders
  • Automated Animal Hunting
  • Automated Node Harvesting
  • Automated Item Crafting

The industry management screen loads up a test-version of the goods tree. On the left hand side are the raw resources and they lead to ANY secondary item that can be produced from them. Later I'll sort the goods alphabetically in their subcategories so everything can be found easily. The point of having each resource lead to any secondary item that can be produced from it is to be able to easily find secondary items (for instance, if an item requires both metal and wood then it will occur twice in the tree extending off from wood and also from metal).

Once you click on one of the goods in the tree, you can then select the options below to change the industry management. Only work orders are fully implemented. So if you select work orders you go to the work order screen.

Here you select how many you want, what materials to use (the options are: must use, use if available, don't use). This screen will also show existing work orders to allow you to change their settings. On next update, the labourers completing the work order will update their settings accordingly. So, there's a delay of building the current item for any labourer completing the work order (for instance, if you cancel the work order, the labourers will still finish what they are working on at the moment).

About item crafting, these are the following game decisions surrounding it:

  • Item crafting must occur in a building
  • The AI will select a building which the person owns or the government has assigned a government building to him (will choose the best building)
  • Material selection occurs each time the unit starts building the next item, in case material settings and availability has changed
  • Each building can only have ONE type of industry improvement (forcing you to build additional houses to improve the industry rate for more labourers)
  • After crafting an item, the carry limit is not checked, the unit will simply be carrying it and queues a drop-off

What doesn't get good screenshots but took a lot of work was the actual implementation of the work orders. There are three different situations: you gave a work order for hunting animals up to a limit, you gave a work order for collecting raw resources or you gave a work order to craft some materials. In the case of hunting animals, the AI finds an animal in the land region of a unit and then has the unit queue up a hunt animal action. The limit is in the amount of meat to harvest (not number of animals). I may, in the future, add in the ability to select an animal limit rather than a meat limit. For a raw resource, the unit finds a resource node of the correct type and material type (but the player can always select yes to all material types). So if you create a work order for wood and said "Y" to pine, then a unit will only try to chop pine wood up to the quantity. Finally, item crafting has a unit attempt to collect resources necessary to produce the good and then go to a building to craft it.

Here is some "flour" (I think my cavemen are making crack but if I don't debug then I can feign ignorance)

Next feature will be surrounding stuff to improve item crafting before I move onto the other buttons in the industry management

Sunday, August 18, 2013

Collecting Some Thoughts

In progress right now is the industry management and work orders. Each feature at this point is taking a longer time than previous ones since they are larger pieces. For industry management there are several components before an alpha version is complete:

  • Goods Tree Screen
  • Labour Dialog, Industrial Structures Dialog and Work Order Dialog

Those UI components are completed and functionality for the work order dialog is also complete. The other component that would be necessary for the alpha version of Cultura is the full functionality of Labour Dialog. Each of these dialogs are different ways to handle industry. Labour dialog allows you to assign a number of people to work in a particular industry to produce as much as they can. It also handles tool selection and non-ideal labour assignments (for the alpha it means people who have a house that is designed for a different type of good and in the future it will also mean people who are not using their best skill). The Industrial Structures dialog allows you to easily upgrade industrial structures and/or view what type of households exist. Each house can have only one type of industrial upgrade (dedicated industrial structures don't exist in the alpha and not likely until you reach neolithic age technology). The work order dialog allows you to order up specific amounts of a good to be collected/crafted using a material selection.

Currently, the work order functionality (you set a work order and then the game automatically begins to assign people to complete the task) is code complete but not fully tested (and debugged and so on). So that'll be finished soon enough. The difficulty in getting this to completion is the rather large number of edge cases and UI design issues that come up. Cultura is a complex game and that means a complex UI. But, ideally the game offers a simple UI to the user but holds easily accessible advanced options for them to micromanage to their heart's content. Additionally, outside of the management UI, there will be a limited number of buttons when units are selected to craft items and possibly other options in the future. Much of the complexity arises from how the code should intelligently react to user input (what should a unit harvest, when should a unit stop, should a unit queue up actions or throw away actions, etc)

Collecting all the tasks together what does Cultura need? Let's ignore UI issues for now. Those will be fleshed out when a feature complete alpha is done (since it's hard to say what might be clunky before actually playing the game).

  • Managing Work Orders
  • Managing Labour Assignments
  • Managing Industrial Structures/Households
  • Tracking wealth by household
  • Family Spawning/Reproduction
  • Random Level Generation for new games
  • Data-driven tech tree and goods tree
  • Data-driven graphic resource/mesh creation
And nice to have for alpha:
  • Event-driven system
  • Graphics component with event-driven system

There are a few open design questions that haven't been fully settled upon:

There might be a UI for seasonally created work orders. For example, it might be "Hunt up to 150 gazelle meat in Summer". This is useful if you don't want to accidentally damage the ecosystem. That currently doesn't exist. There are only work orders and labour assignment.

For now, each household may have any number of bedrooms, living rooms, dining rooms and other such residential rooms but only one industrial structure. Estates are composed of different houses, each with up to one industrial room. This is to simplify gameplay and reflect the cottage-style industrial of earlier ancient times.

Reproduction is currently going to be progress based and dependent on health. Poor health leads to slow reproduction rates. After a set amount of time, children become adults. A set amount of time after that they couple with someone else and start a new family. This new family moves out immediately and requires additional housing. Insufficient housing leads to homelessness (I'm unsure whether people can just randomly build houses or whether land property is controlled). I'm also unsure if I wish to implement cultural rules (such as a daughter moves into the son's estate). I'm also unsure of how to do estate spawning or estate joining. For example, let's say a son grows up and then gets married. Does he build his house in his family estate and combined his labour with that of his extended family or does he break off and start a new estate? Estates share the fruits of their labour but not personal property.

I'm still open as to the random level design. Mostly I gravitate towards having a balanced world where each land region is of a specific type and that type determines the kind of resources it may contain but is "balanced". For example, all land regions have 5 common resources and 2 rare resources. Additionally, I'll design the goods tree to be balanced. Each type of good leads to an equal number of industries except precious metal and precious stone which lead to extra industries (and thus drives up their value in a soft manner).

Lastly, my current set of "raw item categories" is: grain, fruit/vegetable, dairy, meat, wood, stone, earth, fur/skin, fibre, filler, bone, herb, precious metal, precious stone. Each has 4 mundane and 4 fantasy style goods. Steampunk theme means they may encounter either resource. Eventually I'd like to rank the material types by rarity. An item's appearance is determined by the most rare material used in its construction. I'd like that more rare materials give a greater bonus when used. The resources are paleolithic themed and that is why there aren't apples, pears or strawberries. Although I'm not clear on whether strawberries existed back then, it got rather difficult to be too authentic so the following list is only somewhat accurate to stone age:

  • Grain: wheat, oats, rye, barley, stone grass, green brome, silk rye, bluestem
  • Fruit/Vegetable: juniper berries, radish, dates, almonds, glowing mushroom, blue leek, yellow berry, tiger nut
  • Dairy: none for now
  • Meat: gazelle, seal, mammoth, sabertooth cat, unicorn, ice crab, dragon, direwolf
  • Stone: granite, limestone, flint, chert, stonewood, rune rock, aquaferra, dark granite
  • Wood: pine, oak, cypress, sycamore, silverleaf, ironwood, amberbark, goldwood
  • Earth: clay, sand, kaolin, silt, bright clay, dark shale, fire sand, frost silt
  • Metal: tin, iron, nickel, zinc, viper stone, cold iron, frost ore, amber nickel
  • Bone: gazelle, seal, mammoth, sabertooth cat, unicorn, ice crab, dragon, direwolf
  • Fur/Skin: gazelle, seal, mammoth, sabertooth cat, unicorn, ice crab, dragon, direwolf
  • Fibre: silk, cotton, ramie, hemp, giant spider silk, thread mushroom, rock string, yarn bush
  • Filler: papyrus, ryegrass, leadtree, burclover, hollow weed, elf blade, grey shrub, goldclover
  • Herb: tea, ginger, basil, cinnamon, glowing nettle, ember flowers, comfrey root, mandrake
  • Precious Metal: gold, silver, copper, platinum, mithril, adamantium, snow silver, null iron
  • Precious Stone: turquoise, diamond, jade, sapphire, mana crystal, moonstone, sky pearl, power stone

Saturday, July 27, 2013

Technology Management

Tech

Cultura begins in the stone age and is meant to eventually go to the Early Modern age. However, for the first iteration it'll just be the paleolithic age. And for right now, let's take a look at the test UI for the technology management.

In a somewhat Diablo style interface, a list of technologies is shown and rather than be like Civilization where you have research points accumulating to a specific technology you instead receive tech points. Technologies which you can research have a "+" button next to them. I may have technologies which cost more than one point or alternatively give you less benefit per point making some technologies strictly superior to others.

I'd like to add arrows to show prerequisites more clearly and also technologies have "level" requirements not just specific tech requirements. For instance, pottery may require Level 5+ in scraper tool. For now, this screen works. When you add a tech point to tents you are then able to build tents. Once you exit from the screen and go back to the game and then go to the context menu you will see that tent indeed shows up.

Yay

Saturday, July 13, 2013

Building Construction

In order to finish off building construction to the alpha stage several pieces were needed:

  • Context Menu
  • Placement UI
  • Material Selection
  • Wealth tracking
  • Technologies

There were a few bug fixes involved: getting the wealth tracking working right, fixing the graphic for updating trees and so on. The wealth tracking revealed that my quadtree accidentally double inserted items. When I added silverleaf trees, I discovered I had a typo in my code that accidentally changed all trees to the graphic of the one that was just cut down. Imagine my surprise when all my silverleaf trees became pine trees!

Context Menu

The context menu interface has changed to be a keyboard based interface. I left the right-click to show functionality but the primary way to show it is to press the "B" key on your keyboard. The reason? I kept having units selected and then I would right-click only to order the units to do something I did not want instead of showing the right-click menu. Durr!

Basically the context menu shows the base options (which will eventually become icons) and then the sub-categories and then finally the final options. It will also let you quickly open up the faction management screen. I think there will also be a single keyboard shortcut to just go straight into the management screen but that will be for when I create those screens. For now just the context menu!

Opening up the context menu shows this:

We select build

We select Cultural buildings:

Finally, we select Inukshuk

Now we see we can place the building anywhere and also select the materials with which we can construct it.

After we place buildings we can see that there is a bunch of rocks that mark the construction site:

So we can see a preview when we move the mouse around where the building will be and in the lower right corner we see what materials we will be using to construct it. Eventually I will add a resource overlay in the top right corner so that you can see your wealth - liability. You can spend into debt and the display will show negative (indicating that you should get more resources).

Wealth Tracking

Wealth tracking is accurate to the game tick. In actions that affect faction wealth it updates it on the fly. This is a bit dangerous (if I miss a spot in the code then the wealth is incorrect). To make up for this, I have a debug assert that does a resource wealth audit every 100 game ticks. If there is a mismatch between calculation at that moment and the current cached value of wealth then an exception is thrown. This will help me debug any place I have missed proper wealth tracking.

Wealth is defined by having resources stored in structures (therefore units carrying items do not constitute as part of wealth). Liability is defined by structures placed and how much more resources they need. Once industry is added, liabilities will also include work orders and item requests.

Technologies

The technology UI will be next but for now, factions record their technology in a std::unordered_map where it is technology ID to tech level. Many techs are repeatable and so int to int is a reasonable structure. Technology limits how many materials you can select and what buildings you can construct. Right now the two test structures a inukshuks (which the faction begins with) and tents (which the faction does not have). So when you open up the menu, only buildings for which you have the technology show up. Additionally, attempting to select materials beyond the limit results in nothing happening (there will be an error message added in the future). I will also probably have to add information in the material selection on technology limits such as "You may select up 1 material per item type".

Thursday, July 11, 2013

Diplomacy

Let's take a look at Cultura's AI engine and focus on the diplomacy section.  When you trade or make deals how do they figure out how to react, how to figure out whether it's a good deal?

We start with a way rate to all items equally.  Any item is thought of in terms of how much it increases a faction's score.  What is score?  It is the health/happiness/administration provided by the deal item.

Value = health + happiness + administration

It might be possible for a faction to value these scores differently.  If health is low, health is more valuable.  Administration points are more difficult to obtain so they are more valuable.

Value = health * bias1 + happiness * bias2 + administration * bias3

Okay, but how do we calculate the score?  We can define a set of "primitive" functions that we can use:

A) Direct Function

Trade item directly represents goods that have a score rating that can be estimated.  For instance, each unit of Pine Cupboard provides +1 health, +1 happiness.  You are offered 200.  We have no bias.  Therefore it is worth 200 * 1 + 200 * 1 + 0 * 1 = 400.

(Considering existing stocks)
We already have 100 Pine Cupboards and we have 200 people.  Each person gets full benefit from 1 Pine Cupboard.  Additional pine cupboards only provide 1/10 the score.  Now the value is 100 * 1 + 100 * 1 + 0 * 1 = 200 and for the surplus amount is worth (100 * 1 + 100 * 1 + 0 * 1) / 10 = 20.  The value is 220.

B) Trade Opportunity Cost Function

The value of a particular good is the best trade you can get for it.  If there are no previous trades this value is unknown.  Thus the value is the HIGHEST score of all the goods you have traded it for.

For instance, say you have 50 oranges.  They can be traded for 1 pear (+1 health) or 1 mango (+2 health).  In the first trade it is worth 50 health.  The second trade is worth 100 health.  Therefore the trade opportunity cost is 100 value.  We are simply applying A (the direct function) to each set of goods it can be traded for.

Alright, so there's two primitives.

That's pretty good if we're exchange goods.  We calculate the value of what we are trading away.  Let's take a look at an example:

Goguryeo Offers:
200 mangoes

Asks:
50 silk

Direction Calculation
Okay, 1 mango = 2 health.  We have no existing mangoes.  Therefore it is worth 200.
Silk = 2 happiness.  We have lots of silk, overwhelming our people.  So it is worth 100 / 10 = 10.  It is worth 10.

Trade Calculation
We are being offered the mangoes.  We ignore this calculation.
The best other offer is durians which are 3 health each.  Therefore, 50 durians are 150 health.  Trade value is 150.

Using these scores we determine this deal is:

Goguryeo offers 200 and asks 150.  Deal is +50 from our perspective.  Therefore we should accept at a high percentage chance.

Alright but what about more complex deals?  War, threat and raiding.  The situation here is more difficult.  But we could try to break it down to this:

C) Threat Cost

The value of a change in relationship is the threat cost difference.  This can be both negative and positive for when relationship deteriorates or improves.  We figure out the power of an enemy military.  For now we might make a simple calculation:

Military = sum of unit power values * bias

The bias is affected by real data points.  If we fought a war previously and strength was underestimated we can push the bias value to a higher one.

We figure the amount of military needed to counter another faction to be:

MilitaryPowerNeeded = MilitaryPower * Threat

The value for threat can simply be the value of relationship score between the two factions normalized over a value range (between 0 and 1).  So for any change in relationship then the threat value will change and change the MilitaryPowerNeeded.  The difference between the new and old value is the MilitaryPowerNeededChange.  We then estimate how many goods are needed per point of MilitaryPower.  How?

ValuePerMilitaryPower = MilitaryPower / Value of Military Goods

We take the total military goods use calculations A (direct) and B (trade) to get the value of the goods, divide our military power by that and figure out the value per military point.  Let's look at an example:

Song Dynasty demands:
Submission

Okay, if we refuse then we expect -10 relationship which in threat terms means +0.1 threat.

Song Dynasty has 5000 militaryPower.  Current threat is 0.2 and we might expect +0.1 threat if we refuse or -0.1 threat if we accept.  So if we refuse, we need 500 militaryPower, if we accept then we need 500 military power less.

Currently military power of your faction is 2000, with goods valued at 4000.  Therefore each military power is worth 2 value.

So the trade deal is:

Accept: +1000
Refuse: -1000

Are we done?  Military calculations are more complicated than this, so no.

B2) Opportunity Cost of Labour

The reality is that military goods are a drag on an economy.  So we need a new calculation.  Things we could have built if we didn't make the military goods.  Let's call that calculation B2, the opportunity cost of a good in terms of production rather than trade.  If we freed up the labour used to make the military goods what could we have made and use the calculation of A and B to determine the value of those goods.

Total Good Production / Total Labour Used = labour cost of good

This cost is chained.  For instance, a Flour Mill = Gear + Spoke.  Gear = 10 stone.  Spoke = 5 wood.  Therefore Flour Mill = labour cost of each flour mill + 1 * labour cost of gear + 1 * labour cost of spoke + 10 * labour cost of stone + 5 * labour cost of wood.

Knowing that 1 unit of military power = goods whose labour cost is say 50, then we see the best highest value good we could have made instead.

We'll say that each military power could have been 3 honey bread which is worth 6 value.


D) Raid Value

We might want to attack someone for their goods.  In this case, we estimate loss of military power for goods gained.  We might simply come up with a random starting value and then shift it up/down according to actual raids conducted.  Militant powers would estimate higher at first, pacifist powers would estimate lower.  Real raids give real numbers.

As an example: We raided Song Dynasty and gained 300 rice.  Each rice is +1 health.  We lost 20 military power (calculation is the same as discussed in C).  Let's say each military power is 2 value.  We gained 300 value and lost 40 value.  The gain is 260 value.  What is the raid value?  The value is 260/20 which means each military power is worth 13 points.

Like trading, we take the opportunity cost calculation.  The best raid value is the one used.  We pretend for now that Song Dynasty is the best place to raid.  What's second best?  We'll say it is a nation called Silla.  With Silla, each lost military power results in 8 value.

Notice that a tougher target means higher losses and will lower Raid Value, so it inherently takes into account both the prosperity of a target and its defences.

That's great we have a way of figuring out military power expended and the value we get out of it.  But the problem is, how much military power are we going to expend?

Now we can combine the two calculations of C and D.

Song Dynasty demands submission.  We can submit and free up 500 military power.  Therefore submitting is valued at 3000 by calculation C (military goods no longer needed and we value it by A, B and B2).  Therefore the final value is 3000.

Or we can reject.  By calculation C that is valued at -3000.  But it means our raids continue.  In order to break even we must expend at least 3000 / 13 = 230 military power.  So the question now is whether we are willing to risk that much military power.  A faction can set a military power risk threshold.  Let's say Gogoryeo is willing to risk 300 military power.  A -3000 value is not enough to justify the stop to border attacks against Song Dynasty.  If instead Gogoryeo is only willing to risk 100 military power then it is no longer justified to reject submission.

So finally we have a faction's thresholds.  This isn't a primitive calculation.

E) Military Deployment Perceptions

Factions have two values against one another.  The first is the threshold of military they wish to deploy against someone and feel it is still reasonable as a percentage of their military power.  The second is how much military they believe an enemy nation is deploying against them.

Say you are aggravating Song Dynasty.  You injure your relations with them but you know they are already fighting a conflict with Jin Empire.  So around 70% of the Song military is deployed against Jin and of the 30% left they are deployed in various ways.  You notice that only 5% of their military is deployed against you (Gogoryeo).

Song Dynasty has 5000 military power.  Only 250 military power is deployed against you.  According to previous conflicts you trade losses at a ratio of 2:1.  For every military power you lose, they lose 2.  That means you need 125 military power to take care of this threat.

If the actual threat value is higher than this, this means they are temporarily weakly deployed against you for whatever reason.  So if threat value says you need 250 military power but military deployment perception says 125 military power, take a value in-between.  We can keep it simple and just say the half-way point.

You combine D and E and figure out that the requirement of troops is 187.5 and furthermore, increases in threat value are not as significant because if military deployment has not changed then you perceive the military threat to be less than it could be.

What else is important about E?  Shifts in military deployment from your actions.  If you sign a deal to aid someone else in their war against an enemy, you see benefit from decreased enemy deployment along your border.  You might also incite war between two factions, using this calculation to see the benefit versus the cost of goods needed to convince the others to go to war.

Alright well that was quite a bit.

With these we can compile more complicated formulas by putting them together.  For instance:

1) Damage Infliction

Song Dynasty dislikes the Gogoryeo and denounces them.  They believe this will cause the Silla to take a more aggressive stance against the Gogoryeo because then the Gorgoryeo kingdom must redeploy military against Song.

For Song Dynasty it sees by D (threat value) a value of -200 due to increased military required against Gogoryeo.  However, it looks at E (military deployment) between Gogoryeo and its neighbours.  It figures that this begins to draw military away from its other borders and invite attack because their deployment levels drop below some of the military thresholds of its neighbours, such as Silla.

So, it calculates that military losses from such conflict will drop the total size of the Gogoryeo kingdom and as such then lower their troops along the Song-Gogoryeo border.  This freed up military in the long-term is calculated by D (threat value) and is then seen to be +300.

Threatening Gogoryeo is then worth +100.

2) Accepting Roman Protectorate Status

The Romans promise military protection but then we (the Gauls) must pay tax.  By calculations A and B of the non-military goods sent we figure out that the value is -500.  In return the Romans promise protection.

Between the Gauls and the Romans, we see a threat level drop.  Using calculation D we figure out that the freed up military is than valued at +300.

The Romans also post a garrison in our lands.  Depending on our trust of the Romans we may view this as completely not a threat (100% trust) or an insidious invasion plan (0% trust).  It's likely somewhere in-between.  We calculate via D and/or E that this lowers our military deployment and so is worth +700 but due to our trust level (70%), it is lowered to +490.

The total deal is worth +290.

Saturday, June 29, 2013

Radial Right-Click

With a RTS interface well known, the hope is that there is no need for any menu system at all for basic RTS commands. Move, harvest, attack, follow and drop-off are all just a matter of right click when you have a unit selected. Selection is through a left click. Scrolling is by holding your mouse to the edge of the screen or using WASD.
In keeping with the same theme the right-click menu will be just as minimal. It'll consist of icons that appear in the same manner as a context menu and will be designed radially. For the prototype version, it'll just be simply arranged box-shaped buttons but the idea is shown below:
Once the player has selected something to build then the UI shifts into building placement mode. Originally I had designed it to be a simple click and if you wanted to place multiple buildings then it was a shift click.
The shift in mentality is to have a more city-building friendly UI. In that light, placing just one building is more rare than placing multiple buildings. So shift is not required. After you place a building, the mode persists in order to allow you to place more buildings. Instead, you need to right-click in order to exit building placement mode.
Building structures in Cultura is a bit complicated versus most city-building games. Because my concept of "wood" is actually a category of goods you can collect (pine, oak etc) and I want the interface to be more friendly, I opted to follow something that is a combination of Sim City 2000 and Capitalism 2 interfaces. Basically, you go through the radial menu. First you select build. Then you select housing. Then you select tent. Now you are in building placement mode. A tent requires wood and fur/skins. In the bottom right corner a window would show up to show the various options and persists as you place buildings. Those settings are used per building placed. This allows for a quick way to build a lot of "common" structures using cheaper materials and then splurge on a select few "elite" structures in a quick and easy manner.
Sim City would have a large left panel with lots of building categories which would open into small sub-categories. Capitalism would let you place a building and then go into a settings menu. For Cultura, the large left panel is replaced by a radial context menu. The settings screen is replaced with a temporary settings panel at the bottom right of the screen. The real estate used in the UI is then temporary and once you are finished it immediately goes away.
I'll work on tweaks to make the UI experience faster/smoother once I have more of a game to play around with and see what is good and what needs to change.

Wednesday, June 12, 2013

Context Menu

Context Menu

Rather than have a full-on RTS style button grid at the bottom of the screen, Cultura will have a minimal menu presence. The game will rely on intuitive RTS control scheme (left click selection, right-click action) and a small tutorial to teach it. So it relies on established gamer knowledge and standard UI implementation. For everything else it will be done by a context menu. You right click anywhere and the context menu shows up.

In Cultura, it uses CEGUI and it uses Ogre3d and those two combined means they must communicate with each other. The actual context menu exists in CEGUI. The effects it has on the game and the RTS interface exists in Cultura code (which uses Ogre3d). That means I need the CEGUI component to communicate with the Cultura component. Now, since I have yet to implement an event system it entails a bit of tight coupling.

The Cultura component handles when to show the context menu and then "gives up" handling mouse events. The CEGUI component is informed that it should show the context menu and properly attaches listeners to various mouse events to buttons pressed. When a left click occurs that is outside the context menu, the menu is hidden and control is returned to the Cultura component. By control is returned, I mean the Cultura component now understands that the context menu is closed and therefore goes back to its original handling of mouse events. This means that on the first left click outside the context menu, the context menu is hidden, but no unit selection occurs. I think that is actually somewhat expected. The primary issue with making it any more complex is that because I cannot guarantee order, in a reasonable manner, of how an event is handled, the CEGUI component simply either handles the mouse click or it does not through all its possible listeners and the Cultura component can be blind as to what happened and simply waits for control to return.

The context menu currently only allows the construction of buildings, it will eventually include empire management options. Also it will probably become a radial menu and at the very least, use icons instead of text (but have text tooltips). If a build is selected, the menu then shifts into possible buildings that can be built (based on faction technology) and then if a building is selected, it then returns control to the Cultura component which then handles the placement of the new structure.

In the Cultura component, it will have a transparent version of the structure sitting at the mouse cursor locked to the closest game grid square. Left click means to place. Right click is to cancel everything. There is shift-click to place multiple buildings. Each placement of a building queues a faction-level action in the faction's action queue. In the faction class' updateTick() method, it will attempt to assign jobs to idle civilians (who work for the government directly). That can be more complex later in the game when there are more complex government options.

Eventually you will need a way to cancel actions and also to requeue actions if civilians are interrupted and stop doing a job, that job needs to be requeued.

I will finish "factionActions" in the next post!

Monday, June 10, 2013

SaveGood and LoadGood

SaveGood

Saving is the "easier" part in the Cultura project. What's being used is the simplest thing that can be done for now which is serialization into a bytestream and then writing this to a file. Difficult to debug and difficult to maintain but extremely fast. Essentially, each class that needs to have data save implements the serialize function, deriving from a class I called GameEntity (for you Java folks just pretend it's like Object). From here you can do whatever you please.

For primitives I simply cast their address to a char* and then save bytes into a byte buffer equal to their sizeof(). For objects that are not pointers, I call their serialize function. For objects that are pointers I can do the same. For arrays and other objects with size, I serialize their size and then serialize each individual object. The resultant byte stream is then directly written into a .sav file on disk.

Key notes here are that dependencies are not serialized (for instance, someone with a reference to AppStateManager will not serialize the AppStateManager and cause an infinite loop of serialization). Serialization is strictly "downstream" in the class hierarchy. Second, the graphics components are not serialized. I call createScene after I'm done deserializing when I load in order to recreate all the graphic entities.

LoadGood

Loading is the trickier part of deserialization although all of the problems are of course because you didn't serialize properly :). A file is loaded up, the contents are read and then put into a bytestream. This buffer is used for deserialization.

For primitives I can simply read a number of bytes and then assign the value I get to a primitive. For instance, read sizeof(int) bytes and put it into an int. Whatever value you get is what it is. Yay!

Objects are somewhat trickier. The constructor for all my classes that are serializable have a default constructor to make it easier to do this. In the default constructor, non-pointer member objects are constructed with their respective default constructors. When deserialization occurs, those objects can simply call .serialize(ByteBuffer) and for pointer objects then we create a new instance (using the default constructor) and then call ->serialize(ByteBuffer).

For arrays and the like we have to get the size, which we saved, and then resize arrays or unordered_maps and such and then begin to deserialize objects or primitives and then add them. For certain containers, we don't serialize the container, we merely serialize the contents. For instance, we can serialize the list of units in a faction and then create a new QuadTree and then add them to the QuadTree (so upon loading it is a fresh QuadTree with the saved units).

Dependency injection is terribad. After creating new objects you must then inject dependencies again since you cannot save pointers in serialization (what would it point to?). This creates very strange and complicated deserialization call trees. The worst of it in Cultura were actions which require pointer to objects to allow it to manipulate the game world. Poop.

And here is the result of loading, the unit is still carrying out the action that was queued, a harvest node action.

Menu Upgrade

The menu automatically generates the file name. I'll leave it in automatic generation even to release to avoid problems with bad user input. Both the save/load menu refresh each time you go back, looking at the files that exist in the save directory. It is also capable of stripping the .sav from the file name to show the user a nicer looking name (although right now it's just numbered from 0 to whatever). There are no loading screens but in the work needed to perform loading, quitting the game, going back in, creating a new game, saving the game or loading the game all work as expected (game is cleared, there's no accidental double deletes, there may be a little bit of memory leakage but I haven't checked yet).

Now you can SaveGood and LoadGood

Thursday, June 6, 2013

Cultura

What is Cultura?

This is a game about empire building with a focus on city building and diplomacy. It takes place on a large map with a wide variety of resources to explore and discover. There are trees to cut for wood, ores to mine for iron, strawberries to pick and seals to hunt.

You start off on a large empty map. There's very few people and you control them directly but as population grows you begin to gain indirect control options in order to focus on higher level decisions. The world is not a vacuum. There are AI players that are in there doing the same thing, trying to struggle and survive as well. You eventually meet with these factions and work with or against them.

The game begins in the stone age, just at the discovery of fire and your first technologies include various stone age tools such as the hammerstone. Technologies represent new ways to interact with the world. At first you gather food and hunt animals. But as you develop ways to chop trees with axes, build huts, plant different plants you begin to shape the world and progress your way into a grand empire.

And new technology means doing more things faster. You can start to replace whole forests with different trees. Get rid of bushes that you don't want and begin to create large swathes of strawberry bushes. You can fill in empty land with wild wheat and harvest it next spring when your nomadic group comes back to the region. As you gain more technologies the options open up to do more.

How is it played?

Controls

The control scheme is a familiar RTS style. Left click to select and deselects. Control groups. Context-sensitive right click to issue orders. Then there is a right click context menu to build structures. As your society grows and you research more management options you can begin to issue indirect commands and manage a large number of labourers.

Resources

The game is heavily about city building and diplomacy and by extension this means a large economic and trade portion to the game. A large part of the game involves managing your population in collecting different resources. Then gather that into giant piles of stuff. Then roll around in those piles. Well I suppose you can't roll around in them. But like a game of Settlers, you collect resources, refine them or immediately use them for finished goods. Then you use the finished goods to improve your society or for the military.

Resources are grouped into categories. Raw categories would be (not the final list): wood, metal, precious metal, stone, precious stone, meat, grain, fruit, dairy, skins/furs/scales, bones. Then there are finished goods: pottery, chairs, tables, earthenware, crates. Some finished goods later become intermediate goods with increasing technology: gears, clockwork, rope.

Each category of resources has different material types. The idea is that you can have metal but it could be iron, copper, tin or viperore. Finished products can be made with ANY material, as long as it is the correct category. Swords require metal. You can make a sword from iron or from copper, both would work because those are both metals. However, having a higher variety of metals allows you to make higher level tools/weapons. A farming hoe that uses iron AND copper will have an extra item level, making it better than a farming hoe that only uses one or the other. This encourages trade or raiding.

The game is about exploration and discovery as much as it is about building your economy. So resources should be interesting. For each raw category there are 8 item types. They are split equally between "mundane" (real life) materials and "fantasy" materials. Furthermore, for goods where it makes sense they are also seasonally split, 1 mundane / 1 fantasy per season. For instance, "meat" can have "caribou" (spring)/"seal" (winter) / "gazelle" (summer) / "rabbit" (autumn). It's not entirely realistic (I mean do rabbits only breed in autumn? :P) but it's nicer for game purposes to push players to move around to discover the world and find new resource nodes being refreshed each season.

Additionally there may be extra special exotic resources that are rare and hard to find. These might be required for wonders or they might just be extra material types in an existing category (such as a "9th" metal type). This allows for the creation of extra special goods (goods using more types of materials are of higher quality) or wonders.

Industry

In Cultura you'll develop an extensive economy and later when you have indirect management technologies you can automate the collection process so that the focus shifts to ensuring the total industry is running smoothly. It's very much like a combination of Anno 1404 and Settlers where the player collects resources and then converts them into intermediate goods and then creates finished goods. Some goods can be made directly from raw materials (and with the game starting in the stone age, that is the case for almost all the first types of goods).

Goods have "levels" to indicate their quality. For tools it means how long they last before they break. For goods that convey health, they give better health bonuses. For goods that convey happiness, they give better happiness bonuses. For military weapons it improves their ability to do damage or block damage and decreases the chance they break if the unit dies. For consumable goods it means they last longer (for instance a bolt of cloth is used to repair clothing and a higher level bolt of cloth lasts longer).

These "levels" are determined by the skill and technology of the labourer as well as the types of materials used in the construction. More types of materials used the better the good becomes. This is mostly limited by technology (a higher level in metalworking technology allows you to use more types of metals). Exotic versions of an item category are exempt from the limit to make them more useful.

Some industries require tools. Before a tool or structure exists to give a production bonus, the work rate is zero. That would effectively mean you cannot make anything. Technologies would be locked in this manner such that goods that require tools to make cannot be researched until you have those tools first. However, you can always trade for things you cannot make.

City Building

At the start of the game in the stone age you do not city build. You find caves and you huddle in them. But the living space of a cave is limited and eventually you'll need to research basic housing technology to survive. This leads to temporary housing and while you are nomadic you will regularly abandon housing to move to a new land region to access new resources. You then have to, again, build housing there.

Ancient housing doesn't simply disappear. It may remain in later times to be salvaged or admired as an archaeological site. Either way, eventually you'll build a sedentary settlement. City planning and construction is very direct at the beginning. You decide everything. In later stages that decision making becomes more about zoning out areas for use and letting the people (modeled as rational economic actors) decide what needs to be built, when to expand industry and so on. You set the zoning and restrictions and then manage the industry. Better technologies allow finer control and higher level decision making.

Structure building is meant to be modular. You research "living space" and ways to make it more permanent (it might begin as a fur tent before becoming an adobe hut) and you build a "living space". However you might later research "eating space" and to design a house with a dining area and a bedroom, you place a "living space" and then connect a "eating space" to it. The same would be for industry. A blacksmith shop is likely to be a "metalworking space" and in there you can add different types of furniture that further improve that space and the bonus in construction speed it conveys to a worker.

Diplomacy

Diplomacy in the game is folded into trade. This revolves around the trade route. You directly control the core of your nation allowing you to shift resources around as needed within that region of control. But for any entities that fall outside of this you must develop a trade route on an agreed upon exchange (even with sub-entities in your own society). This leads to a control gradient. The level of actual control you exert on others and others on you is dependent on the sum total of the agreements.

So at first, in the stone age, you might have small groups of people carrying a package of goods move to another society, you perform trade deals and other political exchanges (such as gift giving). Then they return home and the agreements and trade deals are complete. It's important to note that they have to return for the deals to be complete (like bringing back or sending a peace treaty).

Later these deals could be more permanent or seasonal. For instance a trade festival every summer at a particular village. Or an extended trade agreement of meat (pork) for fur/skin/scales (dragonturtle shells) at an agreed upon exchange rate and scale, with a convoy that sends the goods back and forth automatically.

In all of this, diplomacy can only happen when envoys are in their proper spots. Your envoy at their court or their envoy at your court (well in the stone age, it's more like someone from their tribe visiting your tribe or vice versa).

In terms of empire building, exerting control on others is more gradual than in most games. One of the focuses of Cultura is that technology is tied with options in diplomacy. So rather than the only options being alliance, peace or war, the options are much more subtle. Perhaps you have a military agreement where you must protect them against invaders but instead of a strict agreement, the idea is this: They may "plea for protection" in exchange for "the right of two cartloads of goods to be traded in their society per day". It's complicated sure but this leads to a more gradual imperial domination. Someone might be a vassal because of how the agreements work (you're the military protector in exchange for trade rights) but perhaps someone else is "more" of a vassal (you have a standing military there, can conscript troops and they pay yearly taxes, in exchange for permanent military protection against all threats and this is a strict agreement with heavily political penalties for failing it).

Of course all this also means that the AI must recognise relationships and value them accordingly. They more appreciate a dominating power that offers good trade and real military protection against enemies than one that is more evil (threatens them, demands tribute and so on, they'd try to find someone else to aid them against such a power). As well there is a conflicting idea of whether they want to become more independent (develop their own military, pay less tribute) or more dependent (they might receive yearly gifts as an enticement to remain a vassal so why not?).

One aspect of imperialism in history was for example China's dealings with the Ryukyu kingdom (modern Okinawa and Diaoyou islands area). As an enticement for Ryukyu to remain a distant apparent vassal of China, the imperial leadership would ask for tribute from the Ryukyu but at the same time give many gifts as a show of power and beneficence. The main point? The gifts (goods such as expensive crossbows which required a large industrial base to produce) were far far greater in value than the tribute received (mostly luxury goods, very valuable in China, not as much in Ryukyu where it was more plentiful). So the Chinese Empire expended large resources to maintain its vassal relations (also why when various Dynasties went into decline and income levels dropped they could not afford to maintain these relations and vassals would drop out of the Chinese sphere of influence). The other point is that Ryukyu Kingdom may have been a disparate vassal of China but the control was fairly loose. Compare it with a much closer society to the central Chinese authority and the relationship would be much closer and the control much greater.

Other examples include the diplomacy of the Roman Empire. The relationship with Rome and its Italian allies involved allowing Italian villages to send representatives to the Roman Senate but in exchange the Italians sent taxes to the Roman state and even sent young men as soldiers for the Roman legions. That's a much closer relationship, one to a point where the Italian cities could be considered a part of Rome. In Cultura, the Italian cities would be a "sub-faction" in the game.

Technology

Cultura has three technological lines: Fantasy, Steampunk and Mundane. Those of one society cannot research any technology of the other two. This also means goods produced by one society may be impossible to build in another society. Hopefully that encourages cooperation (or war). But it does mean that interaction is typically quite meaningful for both parties.

Fantasy technology is themed around a strong military and a small society. Most of the fantasy technologies involve various spells, enchantments and magical artifacts that variously improve the military but also some of civil life. For instance health potions may be a good that improves the health of a population.

At the end of each game day a player earns tech points according to the amount of research conducted and their world ranking in scientific research. The idea is that poor research doesn't lead to an excessive gap. It also does mean diminishing returns for excessive research spending.

Tech points are used to unlock new technologies or improve existing ones. The technology tree is meant to be incredibly in-depth, involving many different upgrades for a single technology. For instance, pottery can be researched but then you could also research glazing (using up extra fuel to improve quality) or you can research leeching (using up whatever acid will be considered in the game in order to increase quality and make it look fancier). This leads to a more nuanced technology tree and a more progressive continuous shift into later ages. Instead of simply moving from one age to another you shift into it as you replace older technologies or acquire new technologies and make industries out of them.

Population Stages

Population growth leads to new stages in the game. Like a session of Anno 1404, as your population grows they gain new demands. In Cultura the model revolves around health and happiness. At higher population levels health is monitored and then happiness is monitored. The consequences of insufficient health/happiness becomes more severe at higher population levels.

At a later stage, for large empires, administration is the last of the three metrics by which your empire is scored. This represents the ability to manage the empire, low score leads to corruption and crime. Low health leads to sickness. Low happiness leads to emigration, civil unrest and even revolt.

Closing notes

Cultura is a large epic game. It's going to be released in phases with the first set just in stone age. Each subsequent release will include more technologies and more options to build a larger and larger empire. My hope is that it's a game where you have fun simply developing a great history for your culture; that you continue to play through the highs and lows. Explore a world. Find some walrus bear wyverns. Punch it to death. Make armour out of them. Conquer your nieghbours. Make your people happy with wine drunk from the skulls of your foes. Cultura.

Friday, May 31, 2013

Menus Everywhere

Saving and Loading

Menus! Right now there are no in-game menus or overlays and everything but new game and quit game do what they are supposed to do. The next task on the list is to fully implement saving/loading. Additionally, I wanted to fix up the menu transition in and out of game. There are two minor issues: you lose your selection of units and your mouse position is also reset.

Also I've been keeping a list of infrastructure debt but that list will be tackled on an as-needed basis to get a working game (also lets me have more time to figure out what I really need to do to solve those problems because I'm fairly unfamiliar with future issues that might arise in Cultura).

Saving/Loading

The saving and loading dialogs need you to be able to select save files or save to disk. I don't know if you really want a full file explorer or just a simplistic "save/load" console style. I'm leaning toward console style.

CEGUI provides something called the layout container which I plan to use to create the list of files to save/load. When the dialog is loaded it scans the save/load director for files following the *.sav format. This creates a cross-platform issue which will be ignored for now (we'll just use the windows directory system to load up the list of files). For each file we create a window and add it to the layout container. Then we will have the same functor used as the subscriber to the onClick event of each. We will set userData on each window so that when the user later clicks on it, in the listener function we can then determine what was clicked and set the correct file as the one to be saved/loaded (also do fancy UI stuff like highlight that box and unhighlight all other boxes).

Here are some CEGUI references that are relevant:

The user then clicks on save/load to perform the actual save or load. For now, I will not allow user defined file names. Instead they will be automatically generated.

Currently, the serialisation works on creating a byte array that is then saved to disk. The serialisation is a bit manual. All objects that need to be serialised essentially derive from CGameEntity. The serialisation uses a custom class known as a CByteBuffer. Objects write to a byte buffer when serialisation or reads from the byte buffer when deserialising. Each class must know how to read/write its member variables inside its serialisation function. Each class calls the super class's serialisation function. That way you get a chain serialisation occurring. It's somewhat tricky to choose which variables inside a class to serialise but there are special considerations (which can be cleaned up with refactoring later): not serialising temporary member variables such as graphic entity pointers.

Also, to simplify serialisation, units/structures and many other entities are being compacted. Originally, I had subclasses for units and structures for different types of units/structures. However, when you get to serialisation that becomes a problem (I have a CUnit pointer but is it really a CAnimal?). Instead of something fancy, the different levels will be compacted into one with a few classes added to record large blobs of data (a new StorageStates class for structures).

I will have to serialise actions as well and in that case, I will have to serialise what action was just serialised (so I can perform proper desserialisation). This means adding a few constants to the UnitAction class and a variable for UnitActionType.

Compacting the Classes

In an effort to simplify serialization, I am compacting my unit and structure classes into a single class with several "container" classes hanging off of them.

Unit:

  • CombatStats
  • EquipmentStats
  • CounterStats
  • Carried items
  • Location

Structure:

  • CombatStats
  • CounterStats
  • StorageStats
  • Location

CombatStats:

  • Hitpoints
  • Damage

EquipmentStats:

  • Item* HeadSlot
  • Torso
  • LeftArm
  • RightArm
  • LeftHand (for weapons or equipment)
  • RightHand (two handed weapons will have both slots point to the same item
  • LeftLeg
  • RightLeg
  • LeftFoot
  • RightFoot

CounterStats:

  • int MoveCounter
  • AttackCounter
  • bool incrementMoveCounter //returns true when move counter gets reset and the unit should move, false otherwise

StorageStats:

  • std::vector Capacity //-1 means unlimited, uses constants for item categories, checks narrowest category first before moving upward, for alpha, just have all/food/non-food categories
  • std::vector StoredAmount //list that mirrors capacity, must update all categories when giving or taking items
  • std::vector StoredItems
  • int GiveItem(Item* item) //returns amount not stored
  • void TakeItem(Item* item)

Carried items can just be a StorageStats object that is not using most of the functionality and only has a single storage limit for all items.

Location is a std::pair to indicate a map location

Tuesday, May 14, 2013

Alpha Design

Designing Cultura

I'd like to pause for a second to develop a clear goal for the alpha and just blab a bit about the game I want to create.

Checklist

  • RTS Interface
  • Management Interfaces
  • Diplomacy and AI Factions
  • Menu Basics

RTS Interface

The core of the game is very much an RTS, the ability to scroll around and watch your empire do work in real time. But, the ultimate intention is not for you to individually control units. As you progress you spend more time managing your empire than you do individual people. There are three main RTS interfaces that will happen: Direct, Partial and Indirect. Direct control means units that do nothing unless you tell them to do things. This will remain true of military units in battle and of only some civilians units (all units at the beginning of stone age will be directly controlled). As you automate more of your labour through the various management interfaces they begin to act automatically. The intention is that as your society gets large and you try to maintain direct control, then you will likely lack enough focus to keep everything running smoothly. Partial control means individuals who are tasked to certain tasks but you can still give them one-time orders. Those one time orders will cause them to deviated from their automated behaviour but once completed they will return to their original task. For indirect control, units will not listen to your orders at all. Instead the only way to manage them is through the management interfaces. At much later stages of the game, such as well into the classical age, portions of the population act completely autonomously and you only affect their behaviour like any government of today: incentives, tax policies, tariffs and so on.

Management Interfaces

The management interfaces are a slew of UI dialogs that you can access in game (which will pause the game) that let you handle different aspects of your society. These interfaces are likely to have to morph through the times (depending on technology). The goal of these interfaces is to lower the amount of direct individual interaction with units in order to manage your society. It is also through this interface to do some special actions such as claiming or abandoning areas.

Wealth Management: An interface that looks at the total stocks, the stocks owned by regions, by individual people and allows you to distribute wealth to individuals. The accuracy, or the ability to have these numbers, will likely depend on technology and bureaucratic size. In addition to that, I am intending to add administrative cost (someone has to count, keep track of records and then physically hand out goods) to distributing goods as an incentive to streamline good distribution without direct government (you) intervention.

Region/Empire Management: This allows you to look at population level and owned structures. It also allows you to claim or abandon regions. Abandoning regions is more common early on when you might leave to find new food sources. As well you can see happiness/health score and perhaps secondary information such as change of disease, revolt or natural disaster. A tab or transition to another screen should allow you to set various social policy. Right now, I'm only thinking of taxation but whether I wanted a "rule" base engine or something less fancy I'll have to contemplate. I don't want it too complex to play but this is already a fairly niche game so whatever.

In addition to the Empire Management it should probably feature a second for population and animal growth (for directly owned animal herds). Since population growth is dependent on food it should be affected here. I figure all new births are in the spring. Because what the hey.

Industry Management: This allows you to assign labour to particular tasks, for all seasons, for particular seasons. Also allows you to set production minimums, maximums, quotas, rate limits and so on.

Technology/Culture: Here you can see the tech tree, culture trait leanings and of course spend tech/culture points to acquire new techs or cultural traits. This should also show you the cumulative effect of your various cultural traits

Diplomacy and AI Factions

The other meat of the game is about diplomacy and so I need at least the existence of AI factions in the alpha. Maybe the AI will be really bad or whatever, but I just need them to exist to allow diplomacy to be conducted (albeit not very useful with a player that does nothing). Of course later on AI factions will play a major role in making the game "fun" because they will be a dynamic part of the world.

Menu Basics

For the alpha, at the very least, we need new game functionality (with world generation) and saving/loading. Other than that, I don't think I'll spend any effort into graphics/audio settings (well in fact I have no audio as of right now :) ). I just need a fully functional menu.

Inspiration

There are a number of games inspiring me to make Cultura, the two most important are Civilization and Dwarf Fortress. Unlike Civilization, this is an RTS (so I suppose more like Rise of Nations). Unlike Dwarf Fortress this is about managing a society rather than individual dwarves.

But because I focus less on individual needs and more on social needs, the focus of the player changes to bigger management decisions with industry, diplomacy, trade and war. Those reflect ideas I pulled from other games. An industry-chain for each finished good; this is like Settlers. Diplomacy based on trade-routes but also intelligently reacting AI: trade is like Anno series and diplomacy is more like Galactic Civilization where they don't simply have a flat point-score in making decisions, they take in the context of the socio-economic condition of the game. But the world is vibrant, with a mixture of mundane, fantasy and steampunk. The exploration of the world is more like Master of Magic where you always wonder what strange new resources exist "over there", or what creatures you might encounter and must deal with.

Ultimately, I'd like to eventually see a game where some Mundane society is sending a trade ship across the ocean carrying ivory carvings when it runs into a kraken just off the coast of a fantasy nation under blockade. Then... BROADSIDE!

Look and Feel

I'd like to capitalize on the 2dness of the graphics that I am implementing and what would be a good fit is a "painterly" look. I think that'd be the most bang for the buck. It'd look really slick but not require any extra special graphics tricks compared to what I am already doing.

For the game itself I'd want it to be a mixture of direct control and indirect management. The entire goal is for you to be building a history with the society you are shaping from the very first days of the discovery of fire all the way on forward. It should be personal, it should be your tribe and you should feel like its leader. But, it's not meant to be about controlling individual people, it's about the whole society. So as you progress you should feel like you are capable of doing more grand things while the society takes care of itself.

You'd start off with a bunch of cave people, the first races being human/elf/ogre, and you need to go out and explore the world. You must find natural caves at first until later you can begin to construct buildings. Before sedentary life you might abandon places seasonally to go on the hunt for more food in different regions. The environment is vibrant, lively with an ecosystem you have to follow. But it's a living environment. Perhaps you want more cherry trees instead of pine trees, so you slowly over time shift the eco system of regions. Then as the land becomes more productive, you can support more people and so you go on from there to build a greater and greater society.

The tech tree is meant to be slow and more about differentiating your society from others. So it's more about very specific technologies with a small section devoted to cultural technologies where you define culture specific luxuries and cuisine. You develop specific good-preferences, value systems and so on which will affect how you manage your society (preference for specific goods will push you to develop those industries) and how you might interact with others (a preference for peace versus war).

Another aspect of the tech tree I hope to differentiate from Civilization is the elimination of the "1000 year war" problem. Where, in the time span of a single war, you can move through 2-3 ages worth of weapons. I think that breaks a lot of the suspension of disbelief. By the time you send your archers and warriors to the frontline, there are axemen and chariots following up behind and finally swordsmen and catapults. I want Cultura to be a game where you don't just "feel" technological progress but there IS technological progress throughout the game yet at the same time you play out whole scenarios in the same tech age.

I accomplish that through being very specific with technology. You develop the burin before a chisel and needle. You have to research scrapers before you can do leatherworking. It's very in-depth and involves a lot of small improvements to society. There will be no clear line between stone age and copper age. You will just slowly shift your industries into the latter. But, I like having a player be able to invest their time into something, have it last and mean something and for them to be able to sit there and formulate grand plans for world domination, to have to worry about this faction and that, while still using stone axes and after all those plans have finished... new technologies and factions come about to upset the balance. I want a player to fight 2-3 major wars just in one age, have convincing stories and history about it and then move into the copper age.

The ultimate goal is for a player to find archaeological ruins of their own making in Cultura. Why, these caves? These were the ones you lived in back in the early stone age but now that you've built Rome in a neighbouring region, they are merely a curiosity.

Less talking. More Raiding.