Introduction
Installing and requirements
Running the bot
In-world commands and concepts
Task examples
Map generator PHP script
Loadbtr function
Credits and Contacts
Introduction
BERRAIN stands for Mr Brain's tERRAIN Manipulation bot. I wrote this bot because I'd always wanted to write a bot like this when I was a citizen of ActiveWorlds. AW has a very poor interface for terrain manipulation, so it's extremely hard to obtain good results. Using Andras' excellent dem2rwx, it is possible to create your terrain using another program and then loading it into your world. However, if you manually change the terrain afterwards, you can no longer use your Digital Elevation Model for large-scale changes.
What BERRAIN is: A bot that can be used by world owners and staff to change the terrain beyond the world limits, or apply large-scale changes to the terrain in your world. You can quickly and efficiently save parts of the terrain to load later, or load multiple DEMs from dem2rwx and merge them seamlessly, as well as use several algorithms for texture drawing (partial flood-fill, line drawing, patch edge tracing) and height modification (sum, product, convolution matrix smoothening). It was designed to run non-stop in the background, not to be turned on and off constantly.
What BERRAIN is NOT: A bot meant to be used as a terrain manipulation solution for the visitors of a world, or a bot with sturdy error trapping. Everyone with bot access can perform any change to the terrain, including some extremely destructive ones, and, for the sake of efficiency, users can do a few things that will crash the bot. Please make sure you know what you're doing before you enter a command ;-)
Installing and requirements
Here's a list of things you need in order to run this bot:
* Linux with glibc6 (may also work with glibc5, I didn't try it though). This is a linux bot, because I'm an advocate of free software, and linux is free. If you prefer to spend a lot of money in Microsoft solutions, find another bot - or write your own. Some casual-user-oriented versions of some distributions of Linux, for example Ubuntu, may not come with glibc already installed; Please check your package/upgrader instructions on how to download and install it.
* Dynamically linked libraries, which should be in your libraries directory: libm (standard maths library, usually everyone has it); libpthread (POSIX threads, should be included with every distribution of linux); libstdc++ (required by the AW SDK for usage with C); libaw_sdk.41 (the AW SDK, which you can download from the AW website - Rename it to this name or create a symbolic link to it using the ln command).
* Caretaker access to your world - This goes without say. You don't have to be the caretaker, but you need a caretaker's citizen number and priviledge password.
* The bot's executable, which you can download here.
Installation instructions
* Make sure you meet all the above requirements.
* Create a new empty folder in your Linux computer and download the above file to it. If you're installing in a remote server, you can probably use wget to download the file directly to the server.
* Uncompress the file using 'tar xzf berrain.tgz'
* If you want the bot to be able to save terrain, make sure the bot folder is writeable by the bot (if both bot and folder are owned by the same user, you only need to use chmod u+w foldername from its parent folder).
* That's all!
Note: If your world server runs in Windows - and I know this is very common - try installing Berrain in your object path server. This will allow Berrain and the Map Generator Script (read further down) to work together.
Running the bot
There are two different BERRAIN executables: berrain and berrain11. The difference between them is that berrain was compiled with a monitoring range of 5 (meaning it monitors a square centered in ground zero with 5x5 terrain pages), whereas berrain11 has 11x11 terrain pages. Each terrain page contains 128x128 terrain cells, so using the berrain executable you will only be able to perform operations up to 315 NSEW (I left a safety margin of 5), which should be enough for most people. With berrain11, you can go up to 700 NSEW. Attempting to perform operations outside their ranges will crash either bot.
The reason why you will usually want to use the berrain executable is because it loads the world terrain much faster, and uses fewer memory. It only has to obtain (5*128)^2=409600 cells in each refresh, while berrain11 needs (11*128)^2=1982464 cells. That's almost five times as much, which means five times the memory usage and one fifth of the speed ;-)
In this manual I will use 'berrain' to refer to the executable; Just add the 11 if you need to use that version of the bot.
After making sure the bot has executable permissions (chmod u+x berrain), you're ready to run it. The syntax is:
./berrain <citnumber> <password> <universe> <port> <world> [daemon]
The citnumber is the citizen number of the bot's owner; It must be a caretaker's citizen number.
The password is that citizen's priviledge password; NOT his account password.
The universe is the domain name or IP address of the AW universe you want to connect to. The main AW universe is auth.activeworlds.com .
The port is used for connecting to the universe. The main AW universe uses port 5670 .
The world is the name of the world you'll be working in. Remember that the previously mentioned citizen number must have caretaker rights in this world.
Optionally, you can append the word daemon to the command line if you want the bot to run as a daemon, that is, in the background. This is the recommended mode. If you don't use daemon mode, the bot will be tied to the terminal you're running it from. Please note that BERRAIN is not a full daemon, because it depends on the starting folder (if you want to delete or move the folder make sure you turn the bot off first).
It can get quite tiresome to have to type this every time you run the bot, so I suggest that you make a shell script to call the bot with the correct parameters. Search the web for more information if you don't know what I'm writing about ^_^
A few seconds after you run the bot, it should enter your world. It will then proceed to query the world server for all the terrain within its monitoring area. This will usually take some time - about 30 seconds if you're using the 'berrain' executable or several minutes using 'berrain11' (note that these times will change with the proximity between your world server and bot server). Once this is done, you can begin using commands.
In-world commands and concepts
Owner commands
Refreshing the internal array
Working area and coordinates
Height and texture restrictions
The status command
Checking and saving
Halt!
Loading
Height manipulation tasks
Texture manipulation tasks
Manual terrain painting
Originally all the commands had the syntax /berrain COMMAND PARAMETERS, but I was told that it was tiresome to type /berrain over and over (you may need several hundreds of commands until you're satisfied with your world), so I replaced that with a simple #. Now all the commands have the syntax # COMMAND PARAMETERS .
The commands are presented below in order: First the non-destructive commands, which you can safely use without breaking anything. Then the task commands, which actively mess with your world's terrain.
Remember that this bot uses centimetres for all the terrain cell altitudes; decimal separators are not acceptable.
Due to SDK restrictions and general Mr Brain laziness, this bot has a maximum working area width of 1000 cells along the W-E axis. There is no limit for the N-S height (other than the bot's monitoring area).
Owner commands
These commands can only be used by the owner citizenship or someone using his or her priviledge password.
# die
Stops the bot. This is the only graceful way of terminating the bot. If the bot for some reason stops responding, you can always kill the proccess (if you're not running daemon mode, use CTRL+C first to recover the shell).
# avlist
Shows the bot's internal list of citizens. Usually these are all the citizens (and tourists) who are online and all the citizens who are offline but have permission to use the bot.
The information displayed is in this format: (session_number) citname (citnumber) Grant: 0|1 Owner: 0|1 . Grant: 1 means the user has permission to use the bot, but is not the owner. Owner: 1 means the user is the owner or using his priviledge password.
# grant CITNUMBER
Grants someone permission to use the bot (except for owner-only commands). The citizen who is receiving permission must be online and in the world. This information will be kept until you stop running the bot. Fairly limited, I know, but this is a working bot, not a user accounts system :P Use grant again to remove bot usage permissions from a user.
Refreshing the internal array
# refresh
The refresh command reloads the whole terrain (within the area that is monitored by the bot, read the Running the bot section for more information) from the AW server. In the beginning of 2007, when I was starting this bot, there were several occurences in which the server was sending corrupted terrain data to the SDK after large operations, so to make things more safe and effective I decided to stop this bot from listening to terrain changed events. Instead, most of the BERRAIN tasks automatically update the bot's internal representation of the terrain, so you can safely use a sequence of BERRAIN commands with no problem. However, after MANUAL changes to the terrain and before using BERRAIN again, you must use refresh for the bot to 'learn' of your manual changes. Otherwise the bot doesn't know you have made changes, and it will un-do them the next time it works with the cells you modified.
Working area and coordinates
Almost all the BERRAIN tasks work inside a rectangle that you define in real time, by specifying its north, west, south and east coordinates - ALWAYS in this order. BERRAIN always supports SDK coordinates (positive coordinates are just a number, negative are minus number, North and West are positive, South and East are negative) as well as user-friendly coordinates (a number followed by N, W, S or E in lower case). User-friendly coordinates are simply replaced by SDK coordinates, so 20e becomes -20 and so on. You can combine both types of coordinates in the same command if you want.
Some BERRAIN tasks do not use a working area; Instead, they use a starting point and, optionally, an ending point. For all purposes, the N and W coordinates of the working rectangle are exchangeable with the starting point, and the S and E coordinates with the ending point.
While it is possible to enter one or more of the coordinates of the working rectangle directly into each task command, when you're going to apply several commands to the same area it could get quite annoying to retype the coordinates. That's why BERRAIN has the ability of memorizing the working rectangle coordinates for you, so they can be reused over and over. The N, W, S and E coordinates are stored individually using the following commands:
# setnwse N W S E
Memorizes the whole working rectangle in one line. You have to provide the four coordinates. Please remember that N must be to the north of S, and W to the west of E, or NO command will work with these coordinates (if you make a mistake just use the command again with swapped coordinates).
# setnw [N W]
Memorizes the starting point for modifying terrain, or the northwest corner of the working area. You can either specify both coordinates or none. If you specify none, the coordinates of the cell where your avatar is standing are saved as the NW corner.
# setse [S E]
Memorizes the ending point for modifying terrain, or the southeast corner of the working area. You can either specify both coordinates or none. If you specify none, the coordinates of the cell where your avatar is standing are saved as the SE corner.
# set [NS WE]
Memorizes both the starting and ending point for modifying at the same time, or sets the working area to a single cell, whose coordinates are NS and WE. If you don't write the coordinates, the coordinates of the cell where your avatar is standing are used.
IMPORTANT: Whenever you want to use a memorized coordinate in a command, just replace the coordinate with a dash. For example, if you wanted to use 'check' with the memorized north and south limits but specifying the west and east limits directly in the command, you'd use: # check - 10w - 10e (for example) (read below about the check command). This works in ALL coordinates parameters of ALL commands that use coordinates.
Height and texture restrictions
While most BERRAIN tasks are restricted to a working rectangle, you can also optionally restrict the (original) height and texture of the cells you want the bot to modify. For example, you can have it leave all the cells in the working rectangle untouched except for those whose height is between 0 and 1000 and that are textured with terrain5.jpg . Here's how:
# seth MIN MAX
Sets the minimum and maximum height of the cells that will be modified by the bot. By default these values are -999999 and 999999 for 'no limit's. If, after temporarily restricting the working heights, you want to go back to unlimited mode, just use # seth -999999 999999 .
# sett [MIN MAX]
Restricts the bot to only work in cells textured with the terrain textures whose numbers are between MIN and MAX. If you don't specify MIN and MAX, the texture the bot thinks that's currently set for the cell your avatar is standing in will be used for both MIN and MAX. Both MIN and MAX can be terrain texture numbers (between 0 and 500), or the words 'hole' or 'none'. 'hole' stands for cells with a terrain hole, and 'none' means no limit. For example, # sett 100 none means the bot will change all the cells textured with terrain100 or above. Use # sett none none to remove the limits.
The status command
# status
This command displays a lot of useful information. The first line shows your name, citizen number and BERRAIN access permissions, followed by your current position in the world (in SDK coordinates) and the altitude and texture of the terrain cell you're standing on, between parenthesis. Finally, the task status is displayed - this can be the word IDLE or BUSY. IDLE means the bot is not performing a destructive task for you, BUSY means it is. You can only have the bot perform one task for you at a time. Different citizens can ask the bot to perform different tasks simultaneously, but I DON'T RECOMMEND THIS - if you must do it, make sure your working areas don't overlap at least. And back the terrain up first :P
The second line contains the coordinates of your working area as memorized by the 'set' commands (read above). Before you use any 'set' commands, these will be the coordinates of the bot's monitoring area (the area the bot can 'see').
The third line contains the current restrictions on terrain cell altitude and texture, also as memorized by the 'set' commands (read above, but not so above as before :P). And finally, the fourth line contains the current status of the 'paint' commands, which are explained further down.
Checking and saving
This section contains the first commands that actually do something ^^
# check N W S E
This command, limited to a very small area, will output to your chatbox what the bot thinks that the heights and textures of the cells in that area are. If the results to not match what you are seeing, either the bot is right and you need to dump your cache (AW often doesn't update terrain properly after large changes, especially when your world's maximum visibility is too high) or AW is right and you need to use # refresh to update the bot.
# save N W S E FNAME [BASE]
One of the most important commands in BERRAIN, this command will save the working rectangle into a terrain dump file, which is usually in botfolder/FNAME.btr . If there is already a terrain dump with that name, it will be overwritten. These terrain dumps are specific to this bot and not compatible with standard AW terrain dumps. They are human readable. They contain the original location of the saved rectangle, so you can load it to the exact same place.
The optional BASE parameter allows you to specify a different base height for the saved dump (other than the default, which is 0). This means the bot will save the dump as if the whole terrain in the rectangle was BASE centimetres above (or below if BASE is negative) its current height.... Well, cutting the crap, the bot subtracts BASE from each cell's height before saving it :P
This command runs very fast so feel free to use it often, especially for backup purposes (just watch out for HD space usage).
# analyze FNAME
This command displays the N, W, S and E limits of a saved terrain dump, so you can know exactly what you're going to destroy if you load it. It also tells you if the dump doesn't exist, so you can use it before 'save' to avoid overwriting terrain dumps.
Halt!
The following sections contain destructive commands; This means they will modify the terrain in your world. Before you go crazy, I'd like to point out the existence of this command.
# halt
When the bot is performing a task for you - and 'tasks' in this context are things that make the Task: indicator in # status change to BUSY - It launches a separate execution thread which performs the task while the main program keeps listening to your commands. If you find out that, for example, you messed up - let's say you forgot to use # refresh and are now tearing down that mountain your friend spent 12 hours making - you can use # halt to KILL THE TASK THREAD. This is not a very neat and tidy procedure, so avoid using it other than in case of an emergency. Also, note that, while # halt works most times, there are times in which IT MAY NOT WORK! So don't rely blindly on it.
Loading
# load N W S E FNAME [ONS OWE [t|h|mh|mth]]
This is the single most powerful command in BERRAIN. It will load a terrain dump, which by itself doesn't look all that important, but you can use this to move large patches of terrain around, draw maps or even seamlessly merge existing with new terrain! (Check the task examples section below.)
Let's go through all the possible parameters one by one. First of all, the working area coordinates, in this command, apply to the scope of the terrain dump, NOT the world. What this means is that if you use the 'analyze' command on a terrain dump and it tells you that it contains a rectangle extracted from 10n 10w 10s 10e, you can use the load command's coordinate parameters to 'crop' this rectangle, loading only a portion of it - for example, # load 5n 5w 5s 5e (...) would only load up to 5 nsew from the previously mentioned terrain dump.
Next parameter is the fileNAME of the terrain dump; Like in # save, you don't have to append .btr to the filename, because the bot does this for you.
ONS and OWE are the OFFSET for loading the terrain dump. Basically, AFTER cropping the dump with N W S and E, all the coordinates will be shifted by ONS and OWE - By default this is 0 0, which loads the dump in the exact same position it was saved from. Imagine you had saved a terrain dump containing the terrain in 10n 10w 0n 0w, and you wanted to load it in 0n 0w 10s 10e. You'd use # load 10n 10w 0n 0w dumpname -10 -10 .
Finally, the last (optional) parameter is the load mode. Please remember that you can only specify this parameter if you also specify the offset; just write 0 0 if you aren't interested in an offset. As for the load mode, by default the bot loads the height and texture number of each cell in the terrain dump into the world, replacing the current values in the target cell. If you use mode 't', only the textures will be loaded, and the heights left untouched. In mode 'h', the heights will replace the existing ones and the textures left untouched. 'mh', which stands for Merge Heights, will ADD the height values in the dump to the current height of the cells and build the resulting matrix, leaving the textures untouched. Finally, 'mth' does the same as 'mh' and also loads the texture numbers from the dump.
Load works in two steps: First it parses the terrain dump file into the terrain matrix, which may take a few seconds or even minutes for VERY large dumps, but usually takes no time at all; Then it iterates through the affected area rebuilding the terrain with the new values, which takes considerably longer. Because the AW server doesn't take too well to being flooded with requests, BERRAIN only sends one terrain update request per second in all commands, with only one exception, the 'ttrace' command (see below). Load has been known not to stop with # halt, so make sure you back your terrain up before using.
Height manipulation tasks
This set of tasks will leave your terrain textures untouched.
# hset N W S E VAL
This is one of the basic commands of BERRAIN and it will set all the cells in the working area to VAL cm of height. Flat.
# hmod N W S E MOD
This modifies the height of the cells in the working area by MOD cm, which may be a positive or negative integer. For example, to raise the terrain by 1m, use # hmod N W S E 10 . Note that if MOD is 0, this command will rebuild the terrain inside the bot's internal matrix without changing it, so if you use this command with MOD set to 0 you can use it to reload terrain or undo manual changes.
# hprod N W S E BASE COEF
Similar to hmod, but multiplies the distance to a base level by a coeficient; This can be used to exaggerate or 'squeeze' terrain or to invert it (turn a mountain into a valley and such). The operation performed is BASE + (altitude - BASE) * COEF. For example, imagine you have a mountain that starts at height 0 and has its peak at height 10000 (100m). You want to slice off the top, let's say starting in height 70m, and turn it into a volcano with a crater. You'd use # seth 7000 999999 # hprod N W S E 7000 -1 .

# hsmooth N W S E LEVEL
Uses a convolution matrix to remove rough edges from the terrain, making it more smooth and uniform. In layman's terms, this works by replacing the height of each cell by the average of the heights of the cell and all the cells that surround it, up to the distance LEVEL. Note that, because of the necessity of reading values from the surrounding cells, there will be a 'border' next to the edge of the working area where cells remain untouched - if LEVEL is 1, this border will be 1 cell thick, if it's 2, 2 cells thick, and so on. The minimum width and height of your working rectangle (in order to use this command) are LEVEL * 2 + 1. If you want to increase the range of the command just increase the size of the working rectangle.
This command is very powerful and can turn the crappiest manually edited terrain into something that looks good. Using 1 in the LEVEL field is enough for most cases; 2 will seriously smoothen your terrain; personally I never had to use 3 or more. As an example, if you have a flat world and want to build a small hill, you can use: # hset 5n 4w 5s 4e 1000 # hset 4n 5w 4s 5e 1000 # hsmooth 7n 7w 7s 7e 2 .
Texture manipulation tasks
These tasks will change the texture of the terrain, leaving its height untouched.
# tset N W S E NUM [D]
One of the basic commands of BERRAIN, tset changes the texture of the terrain cells in the area to NUM (where NUM can be a texture number or the word 'hole'), optionally rotated to D. The rotation direction is either 'n', 'w', 's' or 'e', where 'n' (north) is the standard un-rotated terrain texture, 'w' is the texture rotated 90º counterclockwise, 'e' is rotated 90º clockwise, and 's' is rotated 180º (if you don't specify a D, it's 'n' by default).
# tline NS WE NS WE NUM [D]
Uses Bresenham's line algorithm to draw a straight line between the first pair of coordinates NS WE and the second one. The line will have texture NUM rotated to D, where NUM and D work like the ones in 'tset' (read above).
# tflood NS WE NUM [D]
WARNING: This command is not limited by a working rectangle.
Partially flood-fills an area FULLY ENCLOSED BY ANOTHER TEXTURE using the specified texture and rotation direction, where NUM and D work as in 'tset' (read above). NS WE are the starting coordinates for the flood-fill.
For example, imagine you have a perfect circle textured with texture 0, and the area both outside and inside that circle is textured with texture 1. You want to change the inside of this circle to texture 2. You would use # tflood NS WE 2, where NS and WE are coordinates of a point inside the circle.
While in the above case tflood will fill the whole circle, for some shapes that won't happen. Here's how it works: Starting from the point NS WE, tflood will search towards the SOUTH until it finds a cell with a texture different than that of NS WE. Then, starting in the last cell that still has the same texture, it will texture that W-E row with the target texture, then move one row to the north, if it can, and repeat the procedure until there are no more rows to the north.
If at some point there are TWO lines to the north of the current row encompassed in a different texture, tflood will merely select one; It will never backtrack to the south. That's why I call it partial flood fill. For example, in an X-shaped terrain patch, only one of the southern arms and one of the northern arms of the X, plus the center, will be retextured (at most). In this case, just use the command again for the remaining areas.
# ttrace NS WE T0 T1 T2 [D [NS WE]]
WARNING: This command isn't limited by a working rectangle, is extremely heavy on the world server and doesn't update the internal terrain matrix - you must use # refresh afterwards (or if you messed up, undo the changes with # hmod N S E W 0).
This dangerous command often goes wildly out of control. What it's supposed to do is: Starting in NS WE, which MUST be a cell in the border between two terrain patches textured with different terrain textures, it 'traces' that border drawing transition textures between the two patches. Because this command is so dangerous, there is a limit of 1000 cells that it can draw in one go; Afterwards, you must call ttrace again if it still didn't finish. The optional argument D is a direction - n, w, s or e - which is used as a suggestion for the algorithm of the direction it should begin drawing towards. It doesn't always follow the said suggestion. The second and optional set of coordinates, NS WE, represents a point where the algorithm will stop tracing, PROVIDED that point is ever reached. If the algorithm doesn't reach that point, it will have no effect. By default, the ending point is the same as the starting point.
I should warn you at this point that this algorithm sends 20 terrain update commands to the server at a time, and then rests for one second, before sending another 20 - all the terrain updates are of a single cell. This makes it extremely heavy on the server and all users, and I don't recommend using it when there are many users online.
T0, T1 and T2 are the terrain texture numbers of the textures that will be used to draw the transitions, where T0 is an outer corner texture (filled ~75% with the texture on top of which the algorithm is drawing and ~25% with the texture along which the algorithm is drawing), T1 is the line transition texture (~50% each texture) and T2 is the inner corner texture (the opposite of T0).



Manual terrain painting
These commands can be used for general/small-scale terrain changes outside the buildable limits of a world by using your avatar as the paintbrush. Remember to walk slowly or the server can't keep up :P
# painths VAL
Applies hset (changing the height of a terrain cell to an absolute value) to every cell you enter, unless the cell already has the desired height.
# painthm MOD
Applies hmod (modifying the height of a terrain cell by a value) to every cell you enter - Remember that if you go to a cell twice, it will be modified twice.
# painthp BASE COEF
Applies hprod (multiplying the difference between the height of a cell and a base height by a coeficient) to every cell you enter - Remember that if you go to a cell twice, it will be modified twice.
# paintts NUM [D]
Applies tset (changing the texture of a terrain cell) to every cell you enter, unless the cell already has the desired texture.
# paintstop
Stops all paint functions. While painths, painthm and painthp are mutually exclusive and enabling one will disable the other, you can use paintts together with any of the three if you want. You can check out your paint status in the fourth line of # status .
Task examples
I picked two interesting examples for this guide. Or at least I think they're interesting. Note that while I'm trying to use lots of different BERRAIN commands in order to showcase what they can do, sometimes some of this stuff is easier to do manually, provided it's within the buildable area.
Creating a hill from scratch
Begin by selecting two terrain textures to be used as 'drawing' textures - in our world we have eight textures, 31 ~ 38, reserved for this purpose; We'll be using 31 ~ 32 of those here.

Using the first of these textures, let's draw an octogon on the floor:
# tline 10s 6w 13s 3w 31
# tline 13s 3w 17s 3w 31
# tline 17s 3w 20s 6w 31
# tline 20s 6w 20s 10w 31
# tline 20s 10w 17s 13w 31
# tline 17s 13w 13s 13w 31
# tline 13s 13w 10s 10w 31
# tline 10s 10w 10s 6w 31

Now let's flood-fill the octogon; Position yourself in the middle and use the flood-fill command:
# set
# tflood - - 31

Using the same method, let's draw another octogon inside the bigger one. Note that for a bigger mountain, you can have several concentric octogons (or circles or any other shape).

Now let's use height modification to raise the bigger octogon (the cells textured 31 to 32), but not the grass outside it, by 15m:
# sett 31 32
# setnwse 7s 16w 24s 1e
# hmod - - - - 1500

Using the same method, let's raise only the inner octogon by another 10m:
# sett 32 32
# hmod - - - - 1000

Now let's use the smooth command on the whole thing... twice:
# sett none none
# hsmooth - - - - 1
# hsmooth - - - - 1

We're almost done! All there's left is to remove the working textures, and then apply a different texture (just for the heck of it):
# tset - - - - 0
# seth 1000 2500
# tset - - - - 1

Done! We created a good-looking hill with only bot commands. This could have been done beyond the buildable area of the world, and at any scale!
Loading terrain with Andras' dem2rwx without damaging the existing terrain
This is even less time consuming than the hill-making. If you don't know dem2rwx, well - It's a program capable of loading into AW terrain from a variety of formats (it can also create terrain in RWX format, split in modules, but we won't be using that feature). For this demonstration, I have created a small .bmp with some rough terrain. Each pixel represents one cell, and the color is the height - black for 0 and white for maximum (255m unless you use the verticalscale feature in dem2rwx).

First of all, I'm going to save my terrain. We don't want anything bad to happen, after all. The size of the area you save doesn't matter, as long as you're sure it contains the rectangle where you're building the new terrain.
# save 100n 100w 100s 100e myworld

Now it's time to open dem2rwx. In the first tab, click Open Elevation Model and select the picture above (dem.bmp). In the second tab, select Create AW terrain and lots of unnecessary options will disappear. Select also Target world is 4.x and set the vertical scale to 0.2 . Go to the Prop/Build Options tab, tick 'Build With Robot' and fill in the details, including the target coordinates for building. Then click Generate.

This piece of terrain doesn't exactly fit in... Before I can make any changes, I'd better memorize a working rectangle around this mountain. Because of the depression it created in the terrain, it's very easy to see where to set the corners of the rectangle. Note that the SE corner is always the last one inside the newly built terrain, and the NW corner is the first one outside it:

Time for some changes now. I think the mountain turned out a little too tall, and also a little too jagged, so I'm going to use:
# hprod - - - - 0 0.8
# hsmooth - - - - 1

Finally, all that is left to do is to remove the flat square around the mountain. Remember the terrain dump we saved in the beginning of this demonstration? We can load terrain from that file and merge it with the mountain terrain by using the mh loading mode:
# load - - - - myworld 0 0 mh

Afterwards, time to texture the mountain, apply other command and such things that are outside the scope of this example ;-)
Note that this method for integrating new terrain doesn't only work with nearly flat terrain - You can concatenate a string of mountains in order to create a good-looking, seamless mountain range, if you want.
Map generator PHP script
This PHP script, which you can download for free here, will generate a nice-looking map of your world's terrain from a BERRAIN dump file (created with the 'save' command). Please feel free to modify the script. If you make cool changes, send me an e-mail, I'll probably be interested!
The instructions below explain how to pass parameters to the script when calling it from a web browser (or from the create picture command in AW). For running PHP from your shell, search the web for instructions.
In order to call the PHP script, use http://PATH/mapgen.php?ARGUMENTS or create picture PATH/mapgen.php?arguments . The PHP must be hosted in a server with an HTTP daemon (a web server), with PHP installed with GD (the PHP graphics library). Note that GD must be installed before PHP, so if you don't have GD, you can install it right away and then you must recompile PHP, not forgetting the 'with gd' switch when calling the configure script (there are easy instructions with the PHP package).
Texture mode
In texture mode, mapgen will build a map using downsized versions of your terrain textures, with a brightness filter applied on them based on the height of each cell. All the texture###.jpg files that are required must be in the same directory as mapgen.php, which is why this mode works best if you simply upload mapgen.php to the textures folder of your object path.
Note that the larger the terrain dump, the more textures it has and the greater the amount of different heights that are used, the slower mapgen will be, and it can get VERY slow, taking several minutes to run. Which is why I do NOT recommend using this mode for large maps - you should use it for 50x50 cells areas at MOST. And if your area is that big, don't put mapgen.php directly in create picture - instead generate the map first, save it as a static file and use that in create picture. If five minutes isn't enough to generate your map, increase the value in line 9 of the script.
The syntax of ARGUMENTS for texture mode is: fn=FILENAME.btr[&cs=CELLSIZE][&wh=WATERLEVEL][&min=MINROW][&max=MAXROW] ([] denote an optional parameter). The FILENAME is the name of your BERRAIN dump. The CELLSIZE is the size each cell will have in the map - for instance, cs=3 means each terrain cell will be represented in the map as a 3x3 pixels square, so if the BERRAIN dump had 10x10 cells, the resulting map would have 30x30 pixels. The default cell size is 5.
If you set a WATERLEVEL, all the cells whose height is under that level will be textured with the texture mb-water01.jpg, instead of their own textures, which means your sea will be visible on your map. If you want to change the filename of the sea texture, it's in line 26 of the script.
The MINROW and MAXROW parameters allow you to only render one slice of the map instead of the whole thing; This is helpful for very large and complex maps in which PHP times out before the map is complete - you can render the map in 'slices' and then put them together using a graphical editor. Note that the rows are counted from the BOTTOM of the picture, so if you use &min=0&max=9 (for example), your map will have the first 10 rows of cells in the bottom, and the top will be colored black.

Pixel mode
This mode uses a flat color instead of terrain textures to generate the map. It's MUCH faster than texture mode, usually running under 30 seconds even in complex maps, which is why it's best suited for maps of large areas, using small cell sizes. You should also use this mode if you're planning to link directly to mapgen (either on your website or via create picture). Pixel mode also shows underwater topography, unlike texture mode, which uses the same texture brightness for all the water.
The syntax of ARGUMENTS for pixel mode is: mode=pixel&fn=FILENAME.btr&0=R,G,B&1=......&500=R,G,B[&cs=CELLSIZE][&wh=WATERLEVEL&w=R,G,B] . FILENAME is the name of the BERRAIN dump, and then... You have to specify a color for each terrain texture that appears in your map, with the format TEXTURENUMBER=RED,GREEN,BLUE =) Any textures without an assigned color will simply be rendered as black.
The CELLSIZE has the same meaning as in texture mode, as well as the WATERLEVEL, but here, if you specify a WATERLEVEL you should also specify a color for the water, with the format w=RED,GREEN,BLUE (by default it's a saturated blue).

Loadbtr function
You can download this C code if you're interested in adding .btr (BERRAIN dump files) support to your own bot(s). Currently, this code is much more efficient than the one used inside BERRAIN.
To load a terrain dump, create a pointer to 'terrain' and then use it to store the return value of loadbtr ("filename"). Each terrain cell uses 6 bytes, so for a P100 you'd need less than 250k of memory. On the other hand, if your terrain dump goes all the way to 1000 NSEW, this will use about 24mb of memory. If loading fails, a NULL pointer may be returned (if the first line of the file isn't in the expected format), but it's more likely that your program will crash. Feel free to add error trapping to the function if you need, especially for unexisting files.
To obtain the height or texture values for a cell, call terrain_hei or terrain_tex using as arguments the pointer to your terrain (after loading it) and the X and Z coordinates for the desired cell (note that these coordinates are in cells, not in cm). The values returned are in the format that would be returned by the 4.x SDK. To ensure that these functions can be used with any coordinates, they will return 0 for unknown cells (feel free to modify this behavior if you need).
When you are done with your terrain, you should free the memory it's using by calling clearterrain with your pointer as the argument.
Credits and Contacts
BERRAIN was written by Mr Brain (former AW citizen 291813), aka Protected. He can be reached at the e-mail address myshelter ~at~ gmail =dot= com .
Many thanks to Andras for the help with the SDK last year. I also had some tips from DM Mercury. If it wasn't for Mia and Max being so annoying about terrain, the bot wouldn't be this good, so I guess I should thank them as well. I was inspired by the work of MilesTeg, who years ago made a bot for me similar to this one, though with fewer features - it could set and modify the terrain height and set the terrain texture, as well as use the 'paint' tools I reproduced in my bot.