Planetary Exploration Module

This page is a discussion of the Planetary Exploration Module.

The Planetary Exploration Module is designed to handle all matters related to generation of planetary terrain, population of objects on planetary surfaces, and handling of game-play while the player is exploring a planet's surface (i.e. any time after the order has been given for a player's craft to descend to a planet's surface and before the order is given for that craft to ascend back into space once again). The basic architecture of the module is similar to other modules within the game that handle basic data types (such as integers and strings) and hash tables / dictionaries. It is unique, however, in that it is designed to build Panda3d egg files in real time while the game routine is running. This module is not specifically required by any other module in the game, though the Interplanetary Travel Module does require some data from the module during landing site selection, though there may be some other applications available in other modules. Through planetary exploration, the player can find minerals and lifeforms which they can convert into revenue, as well as artifacts that may assist them in their quest (or even be required for the quest to be successful). Some planets are inhabited, presenting the player with the possibility of trade and other interactions. Finally, planets add to the diversity of the Starflight Universe. For all these reasons, the Planetary Exploration module is vitally important to the game; it is one of the most important modules (and arguably *the* most important one). All code for the Planetary Exploration module is located in the sf3\_planex.py file.

## Summary Description

The Planetary Exploration Module will be called when the player selects a landing site from the Captain's Menu in the Starship Interface. At that time, the present planet's height grid will be called an a two-dimensional Mercator map will be generated based on that grid along with the planet's general type. Further data on the planet will also be loaded up at that time in the event the player wishes to scan/analyze the world to make sure they want to explore the world. The player has the option to select their landing site. Upon confirmation of the order to descend, the module will use the base height grid and an internal routine (which will utilize the diamond-square algorithm) to generate a more detailed structure model at the landing coordinates, which will be parsed in-program on the fly while any descent animation is taking place and rendered when necessary. At the same time, placement of lifeforms and minerals will be done at the various possible points along the detailed height grid at the designated coordinates, and the Event and Plot Handler module will be called to see if any specific ruins or artifacts need to be seeded in the descent area. Control of the game passes to the Planetary Exploration Interface once all generation is complete; the player's ship will be placed "airborne" over the landing coordinates approximately halfway to the ground. The interface will remain in use until all of the player's auxiliary vehicles have returned to their parent starship, the order to launch has been given, and the parent ship has achieved sufficient altitude to be back in space. Should the player get sufficiently close to the edge of the present terrain surface model, the present model will be replaced by a newly generated model. A timestamp for terrain model generation will be generated at the time of the model's generation; models older than two game weeks old will be cleaned, and can be reused should the player explore the same region again (i.e. data on the region, mainly mineral deposits and random ruin locations will be saved).

## Data Structure of the Planet Object

The following list is an indication of the various variables and methods that will be included in a Planet object. This list contains final methods and variables included in the object (these were fairly well set by the last permutation of the Sector Generator). Planet objects are meant to be used as children of Star System objects and contain all available data on an individual planet. Planet objects have no child objects. There are over 1500 planets in the game, each one having their own associated planet object. They are meant to be loaded by the Interplanetary Travel Module upon the entry of the player's fleet into the system containing them. Their data structure is as follows:

* Class: Planet:
	+ Integer: nNumber (planet number within the system)
	+ Integer: nOrbit (orbital lane in which the planet resides)
	+ Float (1 decimal): fMass
	+ Integer: nBio
	+ Integer: nMin
	+ String: szAtmo
	+ String: szHydro
	+ String: szLitho
	+ String: szType (planetary type)
	+ Float (1 decimal): fGravity
	+ String: szAtmoRho (atmospheric density)
	+ String: szTemp
	+ String: szWeather
	+ Integer: nValue (colonization bonus/penalty)
	+ Integer: nHydro (hydrospheric coverage; could also be used to hold sea level elevation)
	+ Hash/Dictionary: Mercator\_Height\_Table
		- *Key/String: Planetary Coordinates*
		- Value/Integer: Height Value
	+ Method: \_init\_(coords, XML)

## Data Structure of the Creature Object

The following list is an indication of the various variables and methods that will be included in a Creature object. This list contains suggested methods and variables included in the module. Creature objects are a composite object made up from SF3Actor, Combatant and Trade\_Good objects, with a few unique characteristics of their own. Character objects are direct child objects of Creature objects. A Creature object will be created when indicated by the Planetary Exploration Module, the Encounter Module (for alien crew statistics), the Starport Module (to generate recruitment lists), or the Main Menu Module (needed to create the player's character). While there may be many Creature objects created by the game, "pure" Creature objects (i.e. flora and fauna the player may interact with on planetary surfaces) will be limited to no more than two dozen at any given time (to limit how much memory the game will be needed to keep track of creature locations, statistics, etc). Their data structure is as follows:

* Class: Creature
	+ Class: SF3Actor (for more information, see the discussion under the Core Module).
	+ ~~Class: Combatant (for more information, see the discussion under the Basic Combat Module~~. *Pretty sure this has been redacted at this point.*
	+ Class: Trade\_Good (for more information, see the discussion under the Trading and Commerce Module).
	+ String: szName
	+ String: szNiche
	+ String: szSymmetry
	+ String: szDescribe (description text)
	+ Integer: nSizeClass
	+ Float (2 decimals): fVolume
	+ Float (2 decimals): fSpeed
	+ Integer: nDUR (durability)
	+ Integer: nLR (learning rate)
	+ Method: \_init\_(AI, XML)

## Data Structure of the Mineral Object

The following list is an indication of the various variables and methods that will be included in a Mineral object. This list contains the final variables included in the module; minerals will have no methods of their own. Mineral objects are meant to be used as child objects of the Planet Objects (they have no child objects of their own), are created in run-time by the planetary exploration module, and are transformed into Trade Good objects once they are picked up by the player. Their data structure is as follows:

* Class: Mineral
	+ Class: SF3Actor (for more information, see the discussion under the Core Module).
	+ Class: Trade\_Good (for more information, see the discussion under the Trading and Commerce Module).
	+ String: szName
	+ Flag: fRepair
	+ Flag: fFuel
	+ Flag: fContraband
	+ Method: \_init\_(XML)

## Data Structure of the Artifact Object

The following list is an indication of the various variables and methods that will be included in an Artifact object.
This list contains suggested methods and variables. Artifact objects are child objects of Trade\_Good Objects and Actor Objects, with no child objects of their own. They are meant to be used via the Planetary Exploration Module as a means of improving the player's capabilities through exploration, or as objects required to complete the game's overall quest. Multiple Artifact objects may be used in the game, though as a rule only a few will be active at a time; these will include any Artifact Objects on the planet the player is currently exploring, as well as any currently within their possession. Their data structure is as follows:

* Class: Artifact
	+ Class: SF3Actor (for more information, see the discussion under the Core Module).
	+ Class: Trade\_Good (for more information, see the discussion under the Trading and Commerce Module).
	+ String: szName
	+ Flag: fCurio
	+ Flag: fTradeRoute
	+ Flag: fAncient
	+ Flag: fTechnology
	+ Flag: fContraband
	+ Method: \_init\_(XML)

## Interface

    The Planetary Exploration Interface consists of two main areas as follows:

* Main Display Area
* Heads-Up Display

As should be apparent from the interface image, the Planetary Exploration Interface is indended to be a fully 3D component of the game. The two areas, the Main Display Area and the Heads-Up Display are concurrent, and both take up the entirety of the screen (though the Heads-Up Display will only use the areas of the screen required for its use). The Main Display Area will show the currently active vehicle (the player's ITV, ATV, flagship or an auxillary craft such as a remote drone) in the central bottom portion of the screen, with the surrounding terrain around it (the vehicle will either be driving on the terrain or flying over it) as well as any objects currently in the camera's field of view (such as lifeforms, minerals, ruins and relics). The active vehicle remains where it is on the screen and the terrain scrolls as the vehicle moves. The active vehicle accelerates to a maximum speed from a stop and then stays at that maximum. The maximum speed and rate of fuel usage are determined by the surface type of the terrain. A skybox will be utilized to generate the sky of the present world, the texture image of which will be used to represent current weather conditions (additional objects and ambient filters may be added to the scene for weather phenomena such as rainfall, hail, fog, and so forth). Control of the current vehicle through the terrain will depend on a mix of keyboard and mouse controls, with the keyboard devoted towards general navigation of the vehicle and targeting, and the mouse devoted towards controlling the camera and aiming any on-board weaponry. Default controls are as follows:

* **W-key**: Accelerates the vehicle (driving); pitches the vehicle downward (flying)
* **A-key**: Turns/banks the vehicle to the left (driving/flying)
* **S-key**: Decelerates the vehicle (driving); pitches the vehicle upward (flying)
* **D-key**: Turns/banks the vehicle to the right (driving/flying)
* **Ctrl-W-key**: Moves the vehicle laterally downward (flying only). Can be used to land if the vehicle is already in hover-mode.
* **Ctrl-A-key**: Moves the vehicle laterally to the left (driving/flying)
* **Ctrl-S-key**: Moves the vehicle laterally upward (flying only)
* **Ctrl-D-key**: Moves the vehicle laterally to the right (driving/flying)
* **Space Bar**: Brings the vehicle to a stop (driving); puts the vehicle in hover-mode (flying)
* **Enter**: Docks vehicle to its parent ship (if stopped/hovering), or brings up vehicle launch selection dialog (pauses action while active, arrow keys scroll, Enter key selects. One option will be "cancel".)
* **E-key**: Targets closest mineral deposit.
* **R-key**: Targets closest lifeform.
* **T-key**: Selects the "next" target (mineral deposit, lifeform, or ruin). If no previous target has been selected, this will select the closest valid target.
* **Y-key**: Selects the "previous" target (mineral deposit, lifeform, or ruin). If no previous target has been selected, this will select the closest valid target.
* **Z-key**: Targets closest hostile target (hostile sapient or hostile lifeform).
* **X-key**: Targets closest structure, if any are present (otherwise, the game will ignore this key).
* **C-key**: Targets anything in the targeting reticule, if anything is present (otherwise, the game will ignore this key).
* **Ctrl-E-key**: Targets closest mineral deposit and focuses camera on it.
* **Ctrl-R-key**: Targets closest lifeform and focuses camera on it.
* **Ctrl-T-key**: Selects the "next" target (mineral deposit, lifeform, or ruin) and focuses camera on it. If no previous target has been selected, this will select the closest valid target.
* **Ctrl-Y-key**: Selects the "previous" target (mineral deposit, lifeform, or ruin) and focuses camera on it. If no previous target has been selected, this will select the closest valid target.
* **Ctrl-Z-key**: Targets closest hostile target (hostile sapient or hostile lifeform) and focuses camera on it.
* **Ctrl-X-key**: Targets closest structure and focuses camera on it, if any are present (otherwise, the game will ignore this key).
* **Ctrl-C-key**: Targets anything in the targeting reticule and focuses camera on it, if anything is present (otherwise, the game will ignore this key).
* **~-key**: Toggles auto-pickup.
* **Left-Click**: Centers the camera angle on the targeting reticule.
* **Right-Click**: Fires the currently selected weapon towards the targeting reticule. Also picks up objects when auto-pickup has been toggled off; will default to pickup on stunned lifeforms.
* **Mouse Wheel**: Changes the present weapons selection, if the vehicle has more than one weapons system installed. *This replaces the "Weapon" option from the original games.*
* **Ctrl-Mouse Wheel**: Zooms the camera in and out.
* **Alt-Mouse Wheel**: Zooms the Mercator/Radar in and out.
* **Mouse Move**: Moves the targeting reticule.
* **Ctrl-Space Bar**: Returns the camera's focus to the aft of the currently active vehicle.

The Heads-Up Display will appear over the Main Display Area and will be largely transparent, except for in the areas where one of the associated "instruments" needs to be involved. The following instruments will be included:

* **Compass**: This will appear at the top of the screen for all vehicles and will let the player know the current direction in which their craft is heading. If the player has a current target, the bearing to that target will be displayed along with the compass with a carat-like icon. Only 90 degrees of arc will be displayed at a time; if the present target is out of that arc, the carat will appear along whatever edge would require the least amount of turning in order to move it to a straight-ahead bearing. If an auxiliary craft is currently deployed, a third carat will appear that will point the vehicle back to its mothership; a numeric counter will appear beside the compass to indicate the distance to the mothership in kilometers.
* **Weapons Indicator**: (not pictured) This will appear in the upper left-hand side of the screen, with each of the vehicle's weapons systems represented on a circle, at equidistant points from one another depending on how many systems are available. The currently selected weapon will have an icon in red at the 12:00 position. As the player toggles their weapons, the icon will change to green, and the position of the weapons icons will rotate along the circle clockwise or counterclockwise to the next weapon icon, which will then change color to red (and become active).
* **Speedometer/Throttle**:: This will appear along the right-hand side of the screen for all vehicles and will let the player know how fast their vehicle is going and how much more power they can expect to get from the engines. Both speed and throttle will be represented by carat-like icons which will move up and down along the gauge as the player accelerates and decelerates, relative to the vehicle's maximum throttle and maximum speed.
* **Altimeter/Elevation Meter**: This will appear along the left-hand side of the screen and will let the player know how far above the ground their vehicle is presently located. A carat will move up and down along the gauge as the player ascends and descends. The gauge will move relative to the distance to the ground; it is possible for the vehicle's altitude to change while flying straight and level if the underlying terrain is hilly. If the player has a current target, the altitude of that target will also be displayed with a different-colored carat; this should allow the player to ascertain whether their current target is above, below, or at the same altitude as the current vehicle.
* **Mercator/Radar**: This will appear along the bottom middle of the screen, and will give the player general information about what is around them. An icon representing the current vehicle will appear in the center of this mini-map, with additional icons used for lifeforms, mineral deposits, and ruins. The upper edge of the minimap will always point towards true North. *This map will replace part of the "Maps" and "Icon" functions from the original games. It may need to be given two levels of zoom, with buttons for switching magnification; whether or not this is necessary may be a function of how large the map is on screen.*
* **Status Area**: This area will appear in two places along the bottom of the screen, along both the left and right edges. The left window will show the general status of the vehicle, including the date, fuel status, current fuel efficiency, weather conditions, temperature, and cargo status (*partially replacing some of the "Maps" function from the original games*). A toggle switch will be available here to switch to a cargo manifest (*replacing part of the "Cargo" option from the original games*). The right window will show the current vitality status of the vehicle's crew; again, a toggle switch will be available here to switch to the cargo manifest. While the cargo manifest is open, the player may scroll up and down the current list of cargo aboard the vehicle (listed as artifacts, minerals, lifeforms and free space remaining in that order) using the keypad + and - keys or dragging a scroll button. Selecting an item in the manifest can be done with a left-click or by hitting the <Enter>; doing so will bring up a dialog asking if the player wants to drop the indicated item.
	+ *Left Bracket Key:* This button will toggle the left status area window between vehicle status and cargo manifest.
	+ *Right Bracket Key:* This button will toggle the right status area window between crew status and cargo manifest.
* **Message Bar**: This area will appear directly above the Mercator; it will take up a small portion of the screen. All messages that need to appear while the player is exploring the surface will appear here.

Whenever an attack occurs, the message "CAPTAIN, WE'RE BEING ATTACKED" is given and the vehicle's systems and/or crew's vitality is modified as necessary. Lifeforms attacking the vehicle takes precedence over everything else; other activities are interrupted if the player is busy when attacked. Mineral deposits, stunned lifeforms and artifacts will be automatically picked up when driven over by default. If there is insufficient room in the terrain vehicle, or if taking on the current amount of cargo will overcapacitate the vehicle's mother ship, the message "THERE IS NO MORE CARGO SPACE AVAILABLE, SIR" will appear and the object will not be picked up. Finally, messages may be displayed by selecting the nearby structure associated with the message.

## General Procedures and Notes

### General Notes

A dampening effect will be in place for planetary atmosphere/contact with the ground. Atmospheric/Planetary Contact dampening should only need to be a factor of ten (i.e. a vehicle with 5 gees acceleration in space will have 0.5 gees maximum acceleration while in a planet's atmosphere or in contact with its surface). This should still provide relatively realistic physics, but if need be this factor can be increased. To simplify matters, maneuverability will remain the same regardless of whether the vehicle in in space or planet-bound.

### Planetary Mercator Generation

The goal of the Mercator Generation procedure is for the program to be able to create a Mercator map for use when the player is selecting a landing site, which is also used when the terrain for the general area needs to be generated. The Mercator Generation procedure's purpose is to generate an elevation map; details on a planet are filled in based on this map, its type and hydrospheric coverage.

Elevation is important in game play in 5 different ways - known as THE FIVE SACRED WAYS in the original SF1 design doc.

1. creates a feeling of environment
2. creates identifiable landmarks
3. allows for efficiency in planet navigation (going uphill is very slow and inefficient)
4. creates specific environments in which certain species may be found
5. helps player locate minerals which are generally found in the mountains

General Mercator Creation Procedure:

1. Planetary terrain consists of an 360x180 array of elevation data (one value for each latitude by longitude coordinate set.
	1. Preferably short integers will be used for this purpose.
2. Basic data on each planet is created ***by an external program***.
	1. A random seed for an individual planet will **always** be the planet's hyperspace coordinates followed by its orbital lane.
		1. e.g. Arth's seed will be 1251003.
	2. Elevation values will created for every four unit intervals (i.e. a 91x46 array will be generated)
		1. When the planet is loaded, values will be passed into the first element, then every other fourth element of the array (i.e. (0x0), (4x0), (8x0), and so forth).
	3. Once the values are created, the terrain values along the "date line" (0x and 360x elements) will be averaged and set to the same value.
	4. Similarly, all values along the poles (x0, then x180) will be averaged together and set to the same value.
		1. Alternatively, a planet may be completely "digitized" before hand, with a full 360x180 array pre-generated. This technique may be employed for special worlds such as Arth where the continental configuration from the original games needs to be preserved.
3. When the player enters orbit around a planet, a full Mercator map is generated for that world at runtime.
	1. If the planet is pre-digitized, the values associated with the terrain are simply passed into the local planet's Mercator array.
	2. Otherwise, the values from the stored array are seed into the appropriate corresponding points in the local Mercator array.
	3. The 2^2 diamond-square algorithm is then employed to fill in the remaining values in the local Mercator array.

### Planetary Surface Generation

The goal of this procedure is to be able to generate a surface terrain model during runtime. Similarly to the Mercator generation procedure, the idea is first to generate a height map for a local area, which forms the basis for the shape of the terrain model. Further details on the model (such as what shaders to use on various portions of the model) will have to be filled in based on the height values, planetary type, hydrospheric coverage, biological concentration.

General Surface Creation Procedure:

1. The player selects the "Descend" option from the Launch/Land sub-sub-menu from the Captain's Sub-Menu on the Starship Interface. (For details, see the discussion under the Starship Module).
2. When the player selects "Descend", the height values of the Mercator Map of the coordinates selected and the eight surrounding adjacent coordinate sets are seeded into a 129x129 grid matrix.
	1. The coordinates the player selects are set at (64,64); the adjacent points are set at (0,0), (64,0), (128,0), (0,64), (128,64), (0,128), (64,128) and (128,128)
	2. The 2^7 diamond-square algorithm is then employed to fill in the remaining values in the array. Additionally, each new value is adjusted by a random "undulation value", the magnitude of which is based on the planet's type and overall elevation (higher altitudes will have more undulation, as will rocky and molton worlds).
		1. The seed for any random number generation needed for this process remains the same as that for Mercator generation, i.e. the planet's coordinate set.
		2. In the event that the player has selected a landing location at one of the poles, the height value of the pole coordinate will be used for all nine points. *I don't see an easy way to do exploration around the poles otherwise.*
	3. All new results are integer values.
	4. The planet's HOH value is used to set the elevation of the hydrosphere. The highest possible value on the terrain map is 255. The HOH is taken as a percentage and multiplied by 255, rounded down. The result is the maximum hydrosphere elevation.
	5. All values on the the terrain map are adjusted by subtracting the calculated HOH elevation from the given value. All negative values are set to zero.
3. The values of the terrain map are sent to an internal routine that generates a Panda3D .egg model file, which is then transformed into a .bam for immediate use.
	1. A schema for the various planet types will determine the shaders (textures, to use the Panda3d parlance) to be used for a given piece of terrain.
		1. These will be based on the planet's type and elevation.
		2. A survey of the surface descriptions from the original games may be needed.
		3. Preferably, terrain textures will be set up to "fade" between levels (e.g. grassy at low elevations, rocky in mid-elevations, icy at high elevations).
		4. The coloration of terrain (both ground and ocean) may ultimately be determined by the planet's mineralogical properties (hydrosphere, lithosphere), similarly to how the color of the sky will be determined by atmospheric density and composition.

*The sooner I can get an example of a terrain .egg file up here, the better. The syntax documentation for egg files is here. We'll need to know this syntax if we're ever going to figure out how to actually **write** an .egg file (which is the point of this procedure, after all). I'd prefer to have that information up here in case the Panda folks ever decide to take that information off their site.*

### Planetary Exploration Procedure

The goal of this procedure is to handle the actual exploration process. This will include handling of "encounters" and terrain regeneration, as well as peripheral issues such as planetary weather.

1. A check is made for terrain, encounters and weather severity when the vehicle first interacts with the planet's surface (i.e. immediately after "landing").
	1. The color of the sky is derived by the color of the planet's star, the presence of water in the hydrosphere, and the the density of the atmosphere.
		1. More water (higher HOH) will have a tendency towards a bluish sky color, yellowish otherwise.
		2. Lower atmospheric density will tend to make the stars/surrounding space more visible. No atmosphere gives a black and star-filled sky.
		3. The sky will be represented by a skysphere. This may need to be one of a series of skyspheres specifically pre-generated with the necessary textures to match the atmospheric/hydrospheric conditions.
	2. As a general rule, higher land elevations are harder to traverse for land vehicles. Sea vehicles are limited to the water, with areas further from the shore easier to traverse. Terrain difficulty for an airborne or planetbound space vehicle can be determined by referencing the planet's stats, using the planet's gravity and atmospheric density to make a best guess.
	3. Initial Weather conditions are set using the indicated table below. Temperatures listed alongside the weather conditions refer to the derived temperature at the vehicle's specific latitude, based on the overall global temperature range. For reference, temperatures rated as Temperate and Tropical are warm, Subarctic and Arctic are cold, and Searing and Inferno are hot.
		1. When a weather condition occurs that has warm as a possibility for both listed conditions, the game may select one at random.
	4. Initial encounters are determined in the same manner as the hourly check.
	5. All necessary models required for the initial "scene-setting" are loaded and rendered in their appropriate positions.
		1. A blank Panda node may be necessary for the reparenting of items that aren't necessarily going to be needed immediately and thus don't have to be rendered right away. *I'll need to go back through the Panda specs to see if there's a better memory-friendly way to do this.*
	6. The energy level (fuel) of any vehicle involved in exploration is "filled" to 100% before deployment.
2. The player will move their ship or specific vehicle around as they explore the planet.
	1. Terrain vehicle movement has two factors. The first is the movement speed and the second is fuel or energy usage. Energy usage is determined by terrain and weather. This usage value is reflected in the efficiency rating displayed for the player. Movement is smooth; squares are hidden terrain tiles that are used for distance calculations only. Fuel usage is calculated by an inverse ratio of energy efficiency. 10% efficiency equals 1% energy usage per square (for the ship, this equates to .1 cubic meters fuel usage).
	2. Terrain Efficiency is not uniform. It is modified by the eight squares around it. If all squares around the square are of lower efficiency than the square will be at the lowest edge of its efficiency range. If all squares around the square are of higher efficiency than the square itself, then the square will be at the highest edge of its efficiency range. Water and lava count for 100% efficiency when used in this calculation.
		1. Energy usage per square = (10 / terrain efficiency) \* weather penalty
		2. Displayed energy efficiency = terrain efficiency / weather penalty
	3. Speed of movement depends on terrain type (value between 0 and 5). Changes to altitude and altitude itself has no bearing on energy efficiency. Distribution of terrain depends on temperature which is determined by altitude, latitude, and the total planetary temperature range or climate. For example, all terrain with a negative altitude will be liquid or lava, depending on planetary type. A planet that has a climate range of Temperate to Arctic will most likely have rock, snow, or an ice at high altitudes and near the poles. Tropical temperatures will have a higher percent chance of containing terrain that is mud, sand, or carpet life(if the planet supports life.) Similar to altitude points, a number of terrain seeds are scattered randomly over the planet surface and grow their terrain until they intersect with another terrain seed's territory. As you can see from the table below, sometimes it is possible to move faster over terrain which requires more energy.
	4. The player's vehicle does not move. Rather, the terrain model (and everything on it) moves. This produces a "treadmill" effect designed to keep the vehicle towards the center of the screen.
	5. If the vehicle crosses a certain barrier, a new terrain model is generated.
		1. There are four invisible collision planes associated with the generated terrain, approximately midway from the terrain model's centerpoint to its edge along the four cardinal directions.
			1. Coordinates of the first permutation of the terrain generation (2^1) are kept. When player passes the line of that permutation, new terrain is generated in the same direction the player is going.
		2. When the TV crosses the midpoint plane, the game generates the terrain egg for that direction and appends it. If large enough this can be done without the player noticing.
		3. While the new terrain model is being generated, the message "SCANNING NEW TERRAIN" will appear on the player's HUD and the action will freeze.
		4. The positions of any secondary models (such as lifeforms, mineral deposits and ruins) will be updated to conform with their position on the new terrain model.
			1. *Ideally, the new terrain model will match the old terrain model along its edge. This would allow both terrain models to remain in memory. There could be some problems with this idea, especially if the same height map is not generated every time the player visits the area. We'll need to play around with this in code.*
3. A check is made for terrain, encounters, weather severity and fuel consumption on an hourly basis.
	1. An hour corresponds to ten real-time seconds.
	2. The vehicle's fuel status will be re-calculated. If the vehicle has reached 50% fuel since the last time it was checked, the message "FUEL SUPPLY HALF GONE" will be displayed.
		1. The distance the vehicle has traveled, as well as the average fuel efficiency over the terrain involved, will be recorded as the vehicle moves. This will be partially based on terrain difficulty and weather.
		2. If the distance traveled is high enough, the indicated amount of fuel will be subtracted from the vehicle.
		3. *This probably will change to a constant fuel usage, rather than an hourly check. Converting the fuel efficiency ratings over from hourly to constant usage shouldn't be that difficult.*
	3. The terrain difficulty will be determined.
		1. Weather will have a role to play here; bad weather during the previous hour will make the terrain rougher. This will reduce fuel efficiency.
	4. Weather for the hour is determined.
		1. Weather patterns are dependent on the categorical planetary weather. There is a 10% chance of weather shift every hour to a new random pattern. Temperature refers to only the derived temperature at the planet's specific altitude and latitude. Temperate and Tropical = warm. Anything cooler than those ranges = cold. Anything warmer than those ranges = hot. Certain weather conditions only exists in one type of temperature.
		2. A *Typhonology* Check occurs to mitigate weather damage, if necessary.
			1. Every hour during a storm there is a 20% chance of a crew member taking damage and a 10% chance of two crew members taking damage.
			2. If a planet is considered tectonically unstable (greater than 2 G's) then first before any other calculation a random chance is figured to determine if an earthquake condition (5%) occurs or any other weather pattern (95%) occurs. If the 95% chance occurs then one of the random weather patterns above is determined.
			3. Weather Damage = round down (base damage \* (10 / terrain efficiency) \* (1 / weather penalty %) / crew durability)
			4. For example, let us say that a human gets hit by electrical storm damage over water. First damage is randomized between 100 and 200, let us say 150. Terrain efficiency is 14%, weather penalty is 50%, and the crew durability is 6, so 150 \* (10 / 14) \* (1 / 0.5) / 6 = 35. Being in sheltering terrain greatly reduces damage as you can see from the formula above.
		3. A *Terregation*  Check occurs in the event of severe weather to see if the vehicle gets lost.
	5. A *Stealth* Check is made to see if the vehicle will avoid the notice of lifeforms during the hour.
		1. Elevation will determine if lifeform or minerals are encountered. Higher elevations tend to favor mineral encounters, lower one tend to favor lifeform encounters. Lifeforms will be placed according to altitude and region. Lifeforms will move about and exhibit other interactive behaviors with each other and the player.
		2. Determine which lifeforms have been encountered, and how many of those lifeforms there are.
			1. Lifeform distribution density on the map is based on two factors: terrain type and planet bio density. Multiply those two values (see terrain type table) to determine and it will give you a value to use for life form density on a planet surface. On terrain which has 100% life form density on a planet with 100% bio, on average every 9x15 area (135 squares) will contain four lifeforms for an average percent chance of 3% per square. Nonaggressive lifeforms can simply be picked up. If cargo space is not sufficient to carry the whole life form then the life form is not picked up. Aggressive lifeforms (basically any lifeform that can cause danger to the player) must be stunned before being picked up.
			2. Once the specific lifeform has been determined, the game will pick a number from 1-5. The result indicates the *number* of lifeforms encountered.
			3. This check may indicate a set of ruins or sapients have been encountered instead. If this is the case, the game selects one or the other.
				1. If ancient ruins are set to exist on the planet then distribute them evenly over the entire planetary surface was no distinction between high or low terrain. Every ancient ruin will have a endurium mineral deposit of 1.0-9.9 m^3 in an adjacent square. Ancient ruins have a 10% chance of the random curio artifact stored inside the ruin itself. If recent ruins are set to exist on the planet then distribute them randomly over the lower altitude terrains diminishing in frequency as the terrain gets higher. Recent ruins have a 20% chance of a random curio artifact stored inside to ruin itself.
			4. Sapient encounters occur just like lifeform encounters; a number from 1-5 will be picked to see how many have been encountered. This can either be individual members of the species and/or vehicles. This type of encounter is similar to a space encounter; communications may take place at this time.
				1. If sentients are present on the planet, place collections of housing, icons indicative of their technology level in diagonal groupings together. One out of four settlements contain a single trade center. Sentients either on foot or in a vehicle depending on technology will randomly leave one housing icon to travel to another, 50% of the time in same settlement, 50% of the time to another settlement.
			5. An *Archaeology* Check is made if ruins are encountered; if successful, a curio is seeded using a d% roll and the chart indicated below.
		3. Determine which minerals have been encountered, and how much of them there are.
			1. Mineral dispersion follows the same pattern as lifeforms, except with mineral density factors and the planet's total mineral percent rating of course. Minerals have a random size between 1 m^3 and 9.9 m^3. Use the Lithosphere components table described in planetary generation to determine what the percent chance of which mineral to place. If the cargo space is not sufficient to store the entire mineral deposit then only enough of the mineral to fill the cargo capacity to 100% is picked up.
			2. A *Geology* Check takes place to see if minerals are encountered.
			3. If successful, the chart below is used to determine which mineral is encountered.
				1. The chart on the Objects page may be used to make a subsequent selection, should the "random mineral" result occur.
			4. d%/10 (keeping the single decimal remainder) is added to the *Geology* score divided by ten; the result is the size of the deposit in m^3.
		4. Determine if a specific set of ruins or artifacts are supposed to be located at the same set of coordinates as the player.
			1. The Event and Plot Handler module will be checked for specific ruins, cities and artifacts. This will include any colonies the player may have dropped on the planet's surface (for details, see the discussion under the Starship Module).
			2. If found, the appropriate ruins, artifacts or cities are seeded onto the location without any *Archaeology* check involved
4. As the player collects items on the planet's surface, the planet's record is updated.
	1. Records on any encounters for a specific set of coordinates are updated.
	2. For example, if three Black Acid Squirters are in an area and the player picks up two of them, then moves off, there should be one Black Acid Squirter if they later return to the same area.

#### Tables

**Mineral Deposit determination by d% Roll**
 40-69
 70-89
 90-98
 99

## Methods

### Planet Class Methods

#### \_init\_(coords, XML)

*The XML argument flag is designed to be a way of indicating whether the game will be set to load data from XML files or from the saved toybox file. While the game is being tested, the flag should be set to True to load from XML. When the game is ready for public dissemination (including any public alpha tests), this flag should be set to False.*

This method loads up the data for a specific planet object. When called, the game checks to see whether the data will be loaded from the appropriate (sector\_name).xml file or the Toybox file, and then goes to check the coordinates for the planet requested. When a matching record is found, data on the planet's number, orbit, mass, biodensity, mineral density, atmospheric composition and density, hydrospheric composition and coverage, lithospheric composition, surface type, gravity, temperature range, global categorical weather severity level, and overall value are loaded and placed into the appropriate holder variables in the Planet object. If the data is being loaded from the XML, the game then looks for a match in the elevations.xml file and loads the data into the Planet object's Mercator\_Height\_Table dictionary, using the coordinates as keys and the height values as values for the dictionary (this information will be included in the records for the Toybox object; the game will simply copy the dictionary data over in that case).

### Creature Class Methods

#### \_init\_(AI, XML)

*The XML argument flag is designed to be a way of indicating whether the game will be set to load data from XML files or from the saved toybox file. While the game is being tested, the flag should be set to True to load from XML. When the game is ready for public dissemination (including any public alpha tests), this flag should be set to False.*

This method loads up data on a specific type of creature. When called, the game checks to see whether the data will be loaded from the appropriate XML file or the Toybox file. Upon finding a matching record, the data for that creature is seeded into the appropriate holders, either within the creature object itself or one of the holders used by its constituent objects. Once all the data is seeded, the game will check the AI argument, and set the flag of the constituent Combatant/AI object as indicated.

### Mineral Class Methods

#### \_init\_(XML)

*The argument flag is designed to be a way of indicating whether the game will be set to load data from XML files or from the saved toybox file. While the game is being tested, the flag should be set to True to load from XML. When the game is ready for public dissemination (including any public alpha tests), this flag should be set to False.*

This method's purpose is to load in data on a specific type of mineral. The game creates Mineral objects either by iterating through the Mineral list in the Toybox object or by attempting to parse a mineral element in the items.xml file. When called, the game merely checks for a matching record and loads the data into the appropriate places in the Mineral object's holder variables, or those of its constituent objects. This includes setting the values of the mineral object's fuel, repair and contraband flags as appropriate. Once the data is seeded, the method goes out of scope.

### Artifact Class Methods

#### \_init\_(XML)

*The argument flag is designed to be a way of indicating whether the game will be set to load data from XML files or from the saved toybox file. While the game is being tested, the flag should be set to True to load from XML. When the game is ready for public dissemination (including any public alpha tests), this flag should be set to False.*

This method's purpose is to load in data on a specific type of artifact. The game creates Artifact objects either by iterating through the lists of Devices, Curios and Other Artifacts in the Toybox object or by attempting to parse the same item element types in the items.xml file. When called, the game merely checks for a matching record and loads the data into the appropriate places in the Artifact object's holder variables, or those of its constituent objects. This includes setting the values of the artifact object's curio, trade route, ancient technology, technology and contraband flags as appropriate. Once the data is seeded, the method goes out of scope.

## XML

The Planetary Exploration Module, like most of the other modules in the game, is largely XML reliant; this will help keep things flexible up until SF3's design is finalized (i.e. creatures, minerals, artifacts and planets can be added and removed from the game freely, based upon what data is available in the various XML files). The Planetary Exploration Module relies on three specific XML files and a specific XML file type. One of the specific files contains data on both minerals and artifacts (the file "items.xml"), one contains specific records on creature statistics (the file "creature\_records.xml"), and one contains the elevation maps of the planets in the game (the file "elevations.xml"). Finally the module relies on a type of file for specific planetary data (the "(sector\_name).xml" file type). The items.xml file is discussed in detail under the Trading and Commerce Module, while the (sector\_name).xml file type is discussed in detail under the Hyperspace Module. The following briefly goes over what data is contained in the creature\_records.XML and elevations.xml files.

### creature\_records.xml

The file "creature\_records.xml" is designed as a record of all creatures that will be present in the game. Under the root element, entries in the XML file are elements with the name "creature", which hold specific information on one type of creature. Creature elements have the following attributes, all of which are mandatory (unless specified otherwise):

* **name**: This indicates the specific name of the species.
* **mesh**: A tuple, this is used to indicate the filename of the lifeform and all animations associated with that lifeform (corresponding to hit, attacking, idle and moving, in that order). A tuple with a single entry will be assumed to indicate an a Panda Model as opposed to being a Panda Actor.
* **icon**: This indicates the filename of a 2D sprite that can be used to represent the lifeform, used by the radar to indicate the lifeform.
* **sfxhit**: This indicates the filename of a sound byte that will play when the lifeform sustains a weapons hit.
* **sfxattack**: This indicates the filename of a sound byte that will play when the lifeform performs an attack, regardless of its target.
* **sfxidle**: This indicates the filename of a sound byte that will play when the lifeform is nearby and not necessary performing a specific action.
* **volume**: A one-decimal float, this indicates the overall volume of the species. Used for determining overall STV and cargo space usage.
* **stv**: An integer, this indicates the lifeform's standard trade value per cubic meter.
* **hp**: This indicates the lifeform's base level of hit points.
* **ahp**: This indicates the lifeform's base level of armor hit points.
* **hd**: This indicates the lifeform's hit difficulty value.
* **thd**: This indicates the lifeform's touch hit difficulty value.
* **fhd**: This indicates the lifeform's flat-foot hit difficulty value.
* **speed**: This indicates how fast the lifeform will be able to move.
* **transit**: This indicates how the lifeform moves around, which may be used to determine whether a lifeform may actually appear in an area (e.g. swimmers in particular are limited to hydrospheric areas)

Creature elements may possess one or more empty sub-elements. These sub-elements may have the name "attack" (used to describe specific attacks the creature may perform), "loc" (used to indicate where the lifeform may be found; all lifeform records must possess at least one "loc" sub-element), and "text" (also mandatory, this is used to hold the lifeform's description text). Attack sub-elements must contain either exactly one or exactly three attributes. Those attributes are "dmg" (immediate damage from an attack), "effect" (a string, this lists any special effect of the attack that causes HP drain), and "drain" (an integer, this indicates the amount of hourly HP drain imposed by the attack); if an effect attribute is present a drain attribute must be present, and vice versa. Loc sub-elements have exactly four mandatory attributes, "sector", "x", "y", and "orbit" (which are used to indicate a specific planet). Finally, Text sub-elements have a single mandatory attribute, "val", which is used to hold the descriptive text).

Sample structure of the creature\_records.xml file:

```

<?xml version="1.0" encoding="UTF-8"?>
 <root table-name="creature_records" version="0.1">
  <creature name="Black Acid Squirter" mesh="(blackAcid.egg, blackAcidHit.egg, blackAcidAttack.egg, blackAcidIdle.egg, blackAcidMove.egg)"<br/>   icon="blackAcidIcon.png" sfxhit="blackacid_hit00.wav" sfxattack="blackacid_attack00.wav" sfxidle="blackacid_idle00.wav" volume="2.0"<br/>   stv="800" hp="60" ahp="0" hd="33" thd="45" fhd="38" speed="2" transit="land">
   <attack dmg="7" />
   <loc sector="delta" x="35" y="69" orbit="4" />
   <loc sector="delta" x="184" y="148" orbit="6" />
   <loc sector="delta" x="242" y="164" orbit="2" />
   <text val="A black, fuzzy, amorphous creature. On the surface of the creature are several blue white globular clusters of light and heat<br/>   sensors. Surrounding each cluster is a ring of small holes through which the creature shoots a powerful acid substance. The creature's<br/>   rasp-like eating apparatus is on its sticky underside." />
  </creature>
  <creature name="Breathing Cactus" mesh="(breathCactus.egg, breathCactusHit.egg, breathCactusAttack.egg, breathCactusIdle.egg,<br/>   breathCactusMove.egg)" icon="breathCactusIcon.png" sfxhit="breathcactus_hit00.wav" sfxattack="breathcactus_attack00.wav"<br/>   sfxidle="breathcactus_idle00.wav" volume="3.0" stv="900" hp="70" ahp="0" hd="36" thd="51" fhd="35" speed="15" transit="land" />
   <attack dmg="7" effect="POISONED" drain=4" />
   <loc sector="delta" x="54" y="195" orbit="6" />
   <loc sector="delta" x="101" y="85" orbit="4" />
   <loc sector="delta" x="199" y="82" orbit="5" />
   <loc sector="delta" x="216" y="45" orbit="6" />
   <text val="A spine covered cactus-like plant with black, fleshy branches and triangular leaves. Covering the surface of this plant are<br/>   many small pores which rhythmically take in and expel air with a hissing sound. Each time the plant breathes in, it visibly expands.<br/>   Radiating out from the base of this plant are long, moving tentacle like branches, each of which has a rosette of long poison tipped<br/>   needles at the end." />
  </creature>
  <creature name="Parascopal Plant" mesh="(parasplant.egg)" icon="parasplant.png" sfxhit="parasplant_hit00.wav"<br/>   sfxattack="parasplant_attack00.wav" sfxidle="parasplant_idle00.wav" volume="3.0" stv="1000" hp="70" ahp="0" hd="25" thd="40" fhd="35"<br/>   speed="0" transit="land" >
   <loc sector="alpha" x="41" y="244" orbit="6" />
   <loc sector="alpha" x="52" y="56" orbit="1" />
   <loc sector="alpha" x="97" y="228" orbit="5" />
   <loc sector="alpha" x="132" y="165" orbit="1" />
   <loc sector="alpha" x="133" y="234" orbit="1" />
   <loc sector="alpha" x="215" y="86" orbit="3" />
   <text val="A tall, shoot-like photosynthetic plant. The plant's interior is hollow and segmented, giving it a unique vascular structure.<br/>   When in danger, the plant retracts itself in a manner not unlike that of a periscope and waits for the danger to pass. When the danger<br/>   has passed, or if the plant is attacked directly, it has the capability to shoot itself back to its full height with great force." />
  </creature>
 </root>

```

### elevations.xml

The file "elevations.xml" is designed as a record of the height maps of every world in the game. This is used by the planetary exploration module to generate the terrain when the player comes for a visit. Under the root element, entries in the XML file are element with the name "orbit", which matches the "orbit" element present in the (sector\_name).xml file type (see the Hyperspace Module for details). Orbit elements have two mandatory attributes, "pos" (which is used to denote the world's location and is listed as a tuple with Sector name first, x-position next and ended with y-position, all separated by commas) and "type" (which is used to denote how much data is stored on the world and must be of one of two values, "partial" or "full"). Each orbit element contains a number of "point" sub-elements, which are empty elements and are used to hold elevation data for specific points. These elements contain exactly three mandatory attributes: "lat" (for the latitude of the point; negative values are used for the southern hemisphere), "long" (for the longitude of the point; negative values are used for the western hemisphere), and "val" (the elevation value at that point).

Sample structure of the elevations.xml file:

```

<?xml version="1.0" encoding="UTF-8"?>
 <root table-name="elevations" version="0.1">
  <orbit pos="alpha, 125, 100" type="full">
   <point lat="0" long="0" val="128" />
  </orbit>
  <orbit pos="delta, 1, 24" type="partial">
   <point lat="-36" long="24" val="63" />
  </orbit>
 </root>

```

## Module Status

*This is current as of August 1, 2011.*

This module is currently in the final design phases; while specific descriptions of the intended functions of modules have yet to be written, the remainder of the module's basic description is complete at this point. Further design work on this module has been frozen for the time being, and will remain so until I'm ready to begin method descriptions for all remaining extant modules. At a minimum, this page needs to have the .egg file syntax added to it along with a practical design for how to write in that syntax. No doubt this module will require a good deal of tweaking before it works the way its intended to. Still what's here should be sufficient for the design team to proceed when the time comes.

NEXT: Trading and Commerce Module

PREVIOUS: Inter-Planetary Travel Module

TOP