• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Makers_F

Vegetation on tiled-based terrain

11 posts in this topic

Hi everyone,

in my game i already wrote the part that loads the terrain in many tiles, and now i have to wrote the part that puts the vegetation on it.
I need a procedural way to set the coordinates.
I thought of using [code]x = sin(T(x,y))* size_of_the_tile's_side/2[/code] and [code]y = cos(K(x,y))*size_of_the_tile's_side/2[/code] to calculate the position relative to the tile center(in this way i'm sure the coords can't fell out of the tile).
The problems i have are:
1) i can't use any random function (the vegetation must not change, every time you are on a tile the vegetation must be the same)
2) i need to have the T(x,y) and K(x,y) functions a bit vary, since i don't want the vegetation to be much repetitive(since sin & cos are periodic functions)
3) i need an "algorithm" to calculate how much vegetation add (i can't add always 50 trees, i need it to vary, and it should be dependent from the sector(so that the density is quite costant in macro-zones))

Long story short, i need to set how many vegetation to add and where..

Is there any docs, resources, papers to get informations from?

Thank you very much in advance

Ps: i said cos and sin since they are the simplest functions that always return [-1;+1], but i'm open to more complex functions :)
PPs: x and y are the integer index of the tile. Watching from above, the lower-left tile is (0,0) , the upper-right is the ,eg, (300,300)
PPPs: the game is 3D, but the z coord is not a problem, since i'll throw a ray from above and find the intersection with the terrain, and than i'll have the z coord of the hit point and the normal of that face(and then if the terrain is too steep i'll add a different type of vegetation, and i'll load different meshes in base of the height of the terrain)
0

Share this post


Link to post
Share on other sites
[quote name='Makers_F' timestamp='1302217631' post='4795726']
Hi everyone,

in my game i already wrote the part that loads the terrain in many tiles, and now i have to wrote the part that puts the vegetation on it.
I need a procedural way to set the coordinates.
I thought of using [code]x = sin(T(x,y))* size_of_the_tile's_side/2[/code] and [code]y = cos(K(x,y))*size_of_the_tile's_side/2[/code] to calculate the position relative to the tile center(in this way i'm sure the coords can't fell out of the tile).
The problems i have are:
1) i can't use any random function (the vegetation must not change, every time you are on a tile the vegetation must be the same)
2) i need to have the T(x,y) and K(x,y) functions a bit vary, since i don't want the vegetation to be much repetitive(since sin & cos are periodic functions)
3) i need an "algorithm" to calculate how much vegetation add (i can't add always 50 trees, i need it to vary, and it should be dependent from the sector(so that the density is quite costant in macro-zones))

Long story short, i need to set how many vegetation to add and where..

Is there any docs, resources, papers to get informations from?

Thank you very much in advance

Ps: i said cos and sin since they are the simplest functions that always return [-1;+1], but i'm open to more complex functions :)
PPs: x and y are the integer index of the tile. Watching from above, the lower-left tile is (0,0) , the upper-right is the ,eg, (300,300)
PPPs: the game is 3D, but the z coord is not a problem, since i'll throw a ray from above and find the intersection with the terrain, and than i'll have the z coord of the hit point and the normal of that face(and then if the terrain is too steep i'll add a different type of vegetation, and i'll load different meshes in base of the height of the terrain)
[/quote]

Perlin noise.
0

Share this post


Link to post
Share on other sites
You know, people who've been here long enough should get little buttons for these. One that just adds "perlin noise" to a thread. One which adds "OpenGL contexts are NOT threadsafe". One which adds "No, you should not try and write an MMO as your first game, how about you write tetris or breakout to get some practice in first?"
0

Share this post


Link to post
Share on other sites
[quote name='Makers_F' timestamp='1302217631' post='4795726']
Hi everyone,

in my game i already wrote the part that loads the terrain in many tiles, and now i have to wrote the part that puts the vegetation on it.
I need a procedural way to set the coordinates.
I thought of using [code]x = sin(T(x,y))* size_of_the_tile's_side/2[/code] and [code]y = cos(K(x,y))*size_of_the_tile's_side/2[/code] to calculate the position relative to the tile center(in this way i'm sure the coords can't fell out of the tile).
The problems i have are:
1) i can't use any random function (the vegetation must not change, every time you are on a tile the vegetation must be the same)
2) i need to have the T(x,y) and K(x,y) functions a bit vary, since i don't want the vegetation to be much repetitive(since sin & cos are periodic functions)
3) i need an "algorithm" to calculate how much vegetation add (i can't add always 50 trees, i need it to vary, and it should be dependent from the sector(so that the density is quite costant in macro-zones))

Long story short, i need to set how many vegetation to add and where..

Is there any docs, resources, papers to get informations from?

Thank you very much in advance

Ps: i said cos and sin since they are the simplest functions that always return [-1;+1], but i'm open to more complex functions :)
PPs: x and y are the integer index of the tile. Watching from above, the lower-left tile is (0,0) , the upper-right is the ,eg, (300,300)
PPPs: the game is 3D, but the z coord is not a problem, since i'll throw a ray from above and find the intersection with the terrain, and than i'll have the z coord of the hit point and the normal of that face(and then if the terrain is too steep i'll add a different type of vegetation, and i'll load different meshes in base of the height of the terrain)
[/quote]

Hi im really an amateur compared what to most people here, but I have a suggestion to you problem. Like a previous person replying said perlin noise is a good way to make deterministic procedural generation, that is a way of generating something that doesn't change when you look it up again.

Im not sure I understand, but are you using a lattice(2d array) and populating it using a sin/cos function, or are you placing the vegetation on different places inside the tile?

Personal experiences from using noise:
I've not implemented perlin noise as Ken Perlin done it, I took a Xor based pseudo random number generator (prng) and made it seedable with x, y coordinates and a single seed number. Thus I had deterministic noise that i could access one tile at a time. The noise is just a random number but can be used to with conditions to make statistical distribution of trees or terrain or whatever really. Its quite magic comparing to storing and manipulating a lattice. To make something more like Perlin Noise I made another function(method since I use Java) that used linear interpolation of different noise wavelength. This is really just adding an interpolation technique that is used when you access tiles in between high wavelength noise, and also adding different "octaves" that is of different wavelength and amplitude. So the number of octaves defines the number of executions of the noise function. The relation between the octaves was called persistance in a tuturial I read, but I've read conflicting uses of the word. My persistance in making a heigthmap is for example= Each octave -> amplitude / 2 and wavelength / 2. The result is high mountatins with smaller hills, and down to noised ground.

A response to your problem:
I've been thinking of using this to make vegetation also, And in this case I have thought about using a reversed persistance, that is higher amplitude on lower wavelengths. The result should be that trees are spaced apart like white noise on a tv when densely packed and over a bigger area small fluctuations of concentrations will be seen. And then it's up to you to decide how dense the forest or other flora should be.

I have no good solution on how to populate your area with trees. Im just thinking perverse thoughts about using cellular automata and some nifty rules. Like that a tile can only have so many neighbours before its tree dies, and that it needs some neighbors to come alive.


PS: Im using my heightmap to declare biome zones and then aplying varying vegetation depending on these. A climate zone is mostly a combination of height and latitude, since that would affect temperature and precipitation.

//FetDaniel
0

Share this post


Link to post
Share on other sites
Ok, this can be the way to go. I googled it, and found lots of articles about the perlin noise, but quite nothing specific to my problem(the coordinates in which punt the vegetation inside the tile)
I saw your ( JTippetts) answer in [url="http://www.gamedev.net/topic/464272-thoughts-on-random-landscapesoverworlds/page__p__4059396__hl__vegetation+noise__fromsearch__1#entry4059396"]this topic[/url], but it's already too complex for what i need, i'm looking for a solution far more simple(for start from).
I've also seen the link to libnoise (although i'm using python, i can wrap the library to use it), and some functions, but i didn't get how to use them. Usually the program is used to generate planes or volumes of points, but i need only "few" (x,y) points, not a full map of points..

I give the (x,y) couple (integer), and it should return K couple of (x,y) coords(float), where K is variable. If you can post a simple example (pseudo-code is fine to), i'll be really grateful.
(the climate zones map thing is really interesting, but more advanced than i need for this project)
Sorry for the noobness :)

Edit(i haven't seen fatdaniel reply):

here what i'm doing.
http://www.youtube.com/watch?v=Kzqwrmv2-Eg
I'm dynamically loading the terrain (from file, but maybe later i can make it procedural), and now i need to put on it the vegetation. So, each tile, i need a finite number(that is how many trees there will be) of (x,y) coords (that is where the trees will be)
The first problem is that i don't know how to find that finite number
Looking [url="http://paulbourke.net/texture_colour/perlin/"]here[/url], i think i need to set up the function so that for small variation of the input gives small variation of the output, but on a large variation of the input, the output can vary a lot. But i don't really know how to set the parameters(for the wavelength and the amplitude)[ i'm using [url="http://www.fundza.com/c4serious/noise/perlin/perlin.html"]this implementation[/url]]
After solving this problem, i think that just varying the number of summed octaves will give nice coords in with put my plants
0

Share this post


Link to post
Share on other sites
I'm really starting to think you could look at a thread that contains "procedural graphics", reply with "Perlin Noise", and be right 90% of the time...
1

Share this post


Link to post
Share on other sites
Using this code
[code]w , h = 800, 800
image = Image.new("L", (w,h))
pix = image.load()
for i in range(0,w):
for l in range(0,h):
x = i+math.sin(i)
y = l+math.cos(l)
pix[i,l] = 255-round((pnoise(x,y,0)+1)*255/2)
image.save("noise.jpeg")[/code]
(in the link in my previous post there is the python module from which i use pnoise function. This script write in a greyscale image the output of pinoise for each coord)
I obtained the attached immage

But i expected something more like this
http://2.bp.blogspot.com/_jRVUemIYFxY/SzIyeaLoWuI/AAAAAAAAABw/abGefrTdffw/s1600-R/perlin_noise2.jpg
(with areas more divided, while in my image is quite random... )
0

Share this post


Link to post
Share on other sites
You're doing something weird to generate your noise image:

x=i+math.sin(i)
y=l+math.cos(l)

From what I can see, i and l get pretty large (800 and 600, respectively) which isn't really the best way to go about calling a Perlin noise function if you want to see detail. Consider a standard Perlin fBm fractal of 8 octaves, where each octave is *2 the frequency of the previous one. The first layer has a frequency of 1, meaning that the average "feature size" of the hills and valleys is 1 unit. Then a layer of details is added whose feature size is 1/2 unit (Frequency 2), and so on. So as you can see, the feature size is important, because when you sample an area sized 800x600 units, one per pixel, you are essentially sampling 1 hill per pixel, and the result is an image of the fractal in which the features are so small that the whole thing just appears as white noise, or close to white noise. Also, the value of sin(i) is going to be tiny in relation to i as i grows large, so you might as well not even bother with the +sin(i) and +cos(l) terms in this case, although they do serve the useful purpose of moving the i and l coordinates off of the integer boundaries of the units, since gradient Perlin noise sampled at integer boundaries evaluates to 0.

What you need to try is to map a smaller region of noise into your 800x600 buffer. The easiest way to do this is to turn down your frequency. Decide how many hills or features you want in your image, and set the frequency to NumFeatures/ImageWidth. So if you want around 4 "hills" or features per image, you'd set the frequency to 1/200, meaning that you'd get a feature on average every 200 units or pixels.


libnoise is actually pretty simple to use. You have 3 basic types of function: generators (that generate noise), combiners (that add, multiply, etc... noise functions together) and transforms (that modify the input coords to a noise function in some way). Simple building blocks that can produce complex results when they are chained together.

Now, once you have your Perlin noise working to your liking, then consider you have a Perlin noise fractal that covers the map, assigning a value of -1 to 1 to each tile of the map. You can look at that as a density map for vegetation. For example, say a value between -1 and 0 is fully clear of vegetation, and a value between 0 and 1 has some amount of vegetation. You can first take the output of your fractal and clamp it to the range [0,1] so that anything below 0 is considered to be 0. Now say that you want to have up to 6 trees per tile. Just multiply the clamped result by 6 and truncate it to an integer. Areas where the clamped function evaluates to 0 will have no trees, while other areas will have a number of trees dependent upon the "height" of the fractal at their location. You can further modify this by adding small amplitude white noise to each tile location that is non-0, to slightly tweak the number of trees per tile.
0

Share this post


Link to post
Share on other sites
Got it!
Unfortunately, the script i use is really simple (i can't set the frequency and octaves number as input), i'll try using libnoise(maybe swig can do the magic) with python.

Btw now i understood how to generate the vegetation map.

The last question i have is:
once i know how many trees add in a tile, how can i calculate their coordinates(x,y)? I think a method could be iterate for each coord in the tile calling the perlin noise, and if the value is greater the, let's say, 0,5, put there a tree. But this is computationally heavy, i prefer to have a simpler method.. Do you have any idea?

(last time i bother you :) )

Ps: yes, the sin and cos where to change the values from integer
0

Share this post


Link to post
Share on other sites
[quote name='Makers_F' timestamp='1302369844' post='4796413']
Got it!
Unfortunately, the script i use is really simple (i can't set the frequency and octaves number as input), i'll try using libnoise(maybe swig can do the magic) with python.

Btw now i understood how to generate the vegetation map.

The last question i have is:
once i know how many trees add in a tile, how can i calculate their coordinates(x,y)? I think a method could be iterate for each coord in the tile calling the perlin noise, and if the value is greater the, let's say, 0,5, put there a tree. But this is computationally heavy, i prefer to have a simpler method.. Do you have any idea?

(last time i bother you :) )

Ps: yes, the sin and cos where to change the values from integer
[/quote]


Well, the easy way to implement changing frequency is just to multiply your x and y coordinates by frequency before calling pnoise.

As far as determining the coordinates of a tree within a tile, this might not be as simple as calling a noise function, if you have to take into account keeping trees from overlapping each other. This becomes a physical modeling problem, and for this type of situation I like to use a hash of the tile coordinates to generate sequences of pseudo-random numbers that are deterministic per-tile. A simple example might be to use a FNV-1 hash + a basic seedable random number generator:

[code]

// FNV-1a hash
unsigned int fnv_hash(void *data, size_t size, unsigned int hash=2166136261)
{
for(unsigned char *p=(unsigned char *)data; p<(unsigned char *)data+size; ++p)
{
hash ^= *p;
hash *= 16777619;
}
return hash;
}

unsigned int hashTileCoords(unsigned int tx, unsigned int ty)
{
unsigned int tc[2]={tx,ty};
return fnv_hash((void *)tc, sizeof(unsigned int)*2);
}

[/code]

Once you have hashed your tile coords to an unsigned int, use that unsigned int to seed a random number generator (for example, call srand() with the hash, then generate random numbers via rand()). This generates a sequence of random numbers that will always be the same sequence for a given tile coordinate, suitable for a streaming-type setup where you can't just globally seed a random generator and hope for sane results.

With this in hand, you can do something to scatter trees at randomized locations within a tile. You can iterate some number of times, generating randomized locations within the tile and checking for overlap with already-generated positions, until you have enough positions or the procedure fails because it can't find a suitable spot. Or you could place locations at evenly-spaced starting points, then use a series of random numbers, scaled to the range [-1,1] then multiplied by some kind of "wobble factor", to perturb the locations randomly from their starting location.
0

Share this post


Link to post
Share on other sites
Ok, since swig has a bit of problems with c++, i followed another way.

I created a dll using a C implementation of perlin noise (python can load c written dll without any problems. With c++ it has some problems because of the name of the functions, but if them can be exported with extern C there wouldn't be any problem to load libnoise dll, but i haven't tryed)

Here the .c file
[code]/* Coherent noise function over 1, 2 or 3 dimensions */
/* (copyright Ken Perlin) */

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "perlin.h"
#define random rand
static int p[B + B + 2];
static double g3[B + B + 2][3];
static double g2[B + B + 2][2];
static double g1[B + B + 2];
static int start = 1;

double noise1(double arg)
{
int bx0, bx1;
double rx0, rx1, sx, t, u, v, vec[1];

vec[0] = arg;
if (start) {
start = 0;
init();
}

setup(0,bx0,bx1,rx0,rx1);

sx = s_curve(rx0);
u = rx0 * g1[ p[ bx0 ] ];
v = rx1 * g1[ p[ bx1 ] ];

return(lerp(sx, u, v));
}

double noise2(double vec[2])
{
int bx0, bx1, by0, by1, b00, b10, b01, b11;
double rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v;
int i, j;

if (start) {
start = 0;
init();
}

setup(0, bx0,bx1, rx0,rx1);
setup(1, by0,by1, ry0,ry1);

i = p[ bx0 ];
j = p[ bx1 ];

b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];

sx = s_curve(rx0);
sy = s_curve(ry0);

q = g2[ b00 ] ; u = at2(rx0,ry0);
q = g2[ b10 ] ; v = at2(rx1,ry0);
a = lerp(sx, u, v);

q = g2[ b01 ] ; u = at2(rx0,ry1);
q = g2[ b11 ] ; v = at2(rx1,ry1);
b = lerp(sx, u, v);

return lerp(sy, a, b);
}

double noise3(double vec[3])
{
int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
double rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
int i, j;

if (start) {
start = 0;
init();
}

setup(0, bx0,bx1, rx0,rx1);
setup(1, by0,by1, ry0,ry1);
setup(2, bz0,bz1, rz0,rz1);

i = p[ bx0 ];
j = p[ bx1 ];

b00 = p[ i + by0 ];
b10 = p[ j + by0 ];
b01 = p[ i + by1 ];
b11 = p[ j + by1 ];

t = s_curve(rx0);
sy = s_curve(ry0);
sz = s_curve(rz0);

q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
a = lerp(t, u, v);

q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
b = lerp(t, u, v);

c = lerp(sy, a, b);

q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
a = lerp(t, u, v);

q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
b = lerp(t, u, v);

d = lerp(sy, a, b);

return lerp(sz, c, d);
}

void normalize2(double v[2])
{
double s;

s = sqrt(v[0] * v[0] + v[1] * v[1]);
v[0] = v[0] / s;
v[1] = v[1] / s;
}

void normalize3(double v[3])
{
double s;

s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
v[0] = v[0] / s;
v[1] = v[1] / s;
v[2] = v[2] / s;
}

void init(void)
{
int i, j, k;

for (i = 0 ; i < B ; i++) {
p[i] = i;
g1[i] = (double)((random() % (B + B)) - B) / B;

for (j = 0 ; j < 2 ; j++)
g2[i][j] = (double)((random() % (B + B)) - B) / B;
normalize2(g2[i]);

for (j = 0 ; j < 3 ; j++)
g3[i][j] = (double)((random() % (B + B)) - B) / B;
normalize3(g3[i]);
}

while (--i) {
k = p[i];
p[i] = p[j = random() % B];
p[j] = k;
}

for (i = 0 ; i < B + 2 ; i++) {
p[B + i] = p[i];
g1[B + i] = g1[i];
for (j = 0 ; j < 2 ; j++)
g2[B + i][j] = g2[i][j];
for (j = 0 ; j < 3 ; j++)
g3[B + i][j] = g3[i][j];
}
}

/* --- My harmonic summing functions - PDB --------------------------*/

/*
In what follows "alpha" is the weight when the sum is formed.
Typically it is 2, As this approaches 1 the function is noisier.
"beta" is the harmonic scaling/spacing, typically 2.
*/

double PerlinNoise1D(double x,double alpha,double beta,int n)
{
int i;
double val,sum = 0;
double p,scale = 1;

p = x;
for (i=0;i<n;i++) {
val = noise1(p);
sum += val / scale;
scale *= alpha;
p *= beta;
}
return(sum);
}

double PerlinNoise2D(double x,double y,double alpha,double beta,int n)
{
int i;
double val,sum = 0;
double p[2],scale = 1;

p[0] = x;
p[1] = y;
for (i=0;i<n;i++) {
val = noise2(p);
sum += val / scale;
scale *= alpha;
p[0] *= beta;
p[1] *= beta;
}
return(sum);
}

double PerlinNoise3D(double x,double y,double z,double alpha,double beta,int n)
{
int i;
double val,sum = 0;
double p[3],scale = 1;

p[0] = x;
p[1] = y;
p[2] = z;
for (i=0;i<n;i++) {
val = noise3(p);
sum += val / scale;
scale *= alpha;
p[0] *= beta;
p[1] *= beta;
p[2] *= beta;
}
return(sum);
}
[/code]
Here the .h file
[code]#define B 0x100
#define BM 0xff
#define N 0x1000
#define NP 12 /* 2^N */
#define NM 0xfff

#define s_curve(t) ( t * t * (3. - 2. * t) )
#define lerp(t, a, b) ( a + t * (b - a) )
#define setup(i,b0,b1,r0,r1)\
t = vec[i] + N;\
b0 = ((int)t) & BM;\
b1 = (b0+1) & BM;\
r0 = t - (int)t;\
r1 = r0 - 1.;
#define at2(rx,ry) ( rx * q[0] + ry * q[1] )
#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )

#ifdef BUILDING_NOW_DLL
#define DLL_DECLSPEC __declspec(dllexport)
#else
#define DLL_DECLSPEC __declspec(dllimport)
#endif

void init(void);
double noise1(double);
double noise2(double *);
double noise3(double *);
void normalize3(double *);
void normalize2(double *);

double DLL_DECLSPEC PerlinNoise1D(double,double,double,int);
double DLL_DECLSPEC PerlinNoise2D(double,double,double,double,int);
double DLL_DECLSPEC PerlinNoise3D(double,double,double,double,double,int);

[/code]

Here the python module that "wrap" the library

[code]import ctypes

class Perlin_Noise():

#using the implementation described here
# http://paulbourke.net/texture_colour/perlin/
def __init__(self, path_to_library , weight = 2.0, spacing = 2.0, zoom = 10, octaves = 5.0):
self._libc= ctypes.cdll.LoadLibrary(path_to_library)
#Typically it is 2, As this approaches 1 the function is noisier.
self._sum_weight = weight
#It is the harmonic scaling/spacing, typically 2
self._harmonic_spacing = spacing
#The zoom of the generate texture
self._zoom = zoom
#The number of octaves(note: high values can bringh to overflow[caused by python])
self._octaves = octaves

self._libc.PerlinNoise1D.restype = ctypes.c_double
self._libc.PerlinNoise2D.restype = ctypes.c_double
self._libc.PerlinNoise3D.restype = ctypes.c_double

self._last1D = None
self._last2D = None
self._last3d = None

def setSumWeight(self, weight):
self._sum_weight = weight

def setHarmonicSpacing(self, spacing):
self._harmonic_spacing = spacing

def setZoom(self, zoom):
self._zoom = zoom

def setOctaves(self, octaves):
self._octaves = octaves

def getLast1D(self):
if hasattr(self, "_last1D"):
return self._last1D
else:
return None

def getLast2D(self):
if hasattr(self, "_last2D"):
return self._last2D
else:
return None

def getLast3D(self):
if hasattr(self, "_last3D"):
return self._last3D
else:
return None

def noise1D(self, x):
self._last1D = self._libc.PerlinNoise1D(
ctypes.c_double(x / self._zoom),
ctypes.c_double(self._sum_weight),
ctypes.c_double(self._harmonic_spacing),
ctypes.c_int(self._octaves)
)
return self._last1D

def noise2D(self, x , y):
self._last2D = self._libc.PerlinNoise2D(
ctypes.c_double(x / self._zoom),
ctypes.c_double(y / self._zoom),
ctypes.c_double(self._sum_weight),
ctypes.c_double(self._harmonic_spacing),
ctypes.c_int(self._octaves)
)
return self._last2D

def noise3D(self, x , y, z):
self._last3D = self._libc.PerlinNoise3D(
ctypes.c_double(x / self._zoom),
ctypes.c_double(y / self._zoom),
ctypes.c_double(z / self._zoom),
ctypes.c_double(self._sum_weight),
ctypes.c_double(self._harmonic_spacing),
ctypes.c_int(self._octaves)
)
return self._last3D[/code]

Here a script to try if the module works
[code]import perlin_noise
import math
from PIL import Image

w , h = 1000, 1000
new_noise = perlin_noise.Perlin_Noise("perlin.dll", 1, 3, 10, 0)
new_noise.setSumWeight(2)
new_noise.setHarmonicSpacing(200)
new_noise.setZoom(5)
new_noise.setOctaves(1)

image = Image.new("L", (w,h))
pix = image.load()
for i in range(0,w):
for l in range(0,h):
x = i+math.sin(i)
y = l+math.cos(l)
pix[i,l] = ( (new_noise.noise2D(x,y) + 1) / 2 ) * 255
image.save("noise.jpeg")

new_noise.noise1D(new_noise.getLast2D())
new_noise.noise3D(new_noise.getLast1D(), new_noise.getLast2D(), x+y)
new_noise.getLast3D()[/code]

Here part of the code in used to generate the coords of the trees:
[code] sector = square["mysector"]
vegetation = Perlin_Noise(g.expandPath("//") + "Perlin" + os.path.sep + "perlin.dll",2, 1000, 10, 1)
# tree_number = (max_trees_per_square_meter) * size_of_the_tile || in this case max 1 tree per 3 square meter
tree_number = int( abs( vegetation.noise2D( sector[0], sector[1] ) / 3 ) * 16 * 16)
rand = random.Random()
rand.seed(hash(tuple(sector)))
for k in range(0, tree_number):
x = (rand.random() -0.5 ) * bge.size
y = (rand.random() - 0.5) * bge.size
#make it relative to the center of the tile
x = square.worldPosition[0] + x
y = square.worldPosition[1] + y[/code]

I added all this code so that if someone will have the same problem can find here a good way to start from. I managed to create the system for loading the trees, now it will just need polishing and a bit of improvement. I'm sorry i dind't managed to use the libnoise library, it seams well coded and feature complete, if someone have any hints about how to export its functions as C functions let me know :)

Thanks very much to who made this possible helping me, now i'm a little less noob :)
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0