Jump to content

  • Log In with Google      Sign In   
  • Create Account

Servant of the Lord

Member Since 24 Sep 2005
Offline Last Active Oct 20 2016 09:42 AM

#5231854 [SFML] Infinite space world with random spawns

Posted by on 30 May 2015 - 10:43 AM

Note that the star-spawning I used above is 'pure random' which can give less-than-pleasing results - I was in a hurry. tongue.png

But it's a start in the right direction and can be improved upon later.


Ok so just done a little more messing around with it and got it to draw, however, when my ship moves, the stars arent re drawing


Show me your code.


If it's a single file of code, post it to PasteBin.com and post the link here.

If it's multiple files worth of code, zip it up into a zip file, and upload it to DropBox, OneDrive, GoogleDrive, or any other direct-linkable file hosting service.

(Preferably one that isn't full of ads, and definitely one that doesn't require me to sign up just to download the file)



In videogames, you need to redraw the entire screen, and everything on the screen, every single frame (every single loop of the main loop).


The order is:

 - Clear the screen: window.clear()

 - Draw the objects in the order you want them to appear: window.draw(...whatever...)

 - Apply the changes, so it shows up on the user's monitor: window.display()


See SFML's short example.


You never just draw an image once - you draw it over and over and over and over again, one draw for each frame. You should only call "clear()" and only call "display()" once per frame.

#5231786 [SFML] Infinite space world with random spawns

Posted by on 29 May 2015 - 07:57 PM

int16_t cellX = posInWorldX / WidthOfCell
int16_t cellY = posInWorldY / HeightOfCell

//I'm using bit operations here to cram the two signed 16-bit integers into one unsigned 32 bit integer.
uint32_t randomGeneratorSeed = (cellX << 16) | (cellY & 0xFFFF);


//NOTE: std::srand() and std::rand() are not the best random-number generators to use - their results aren't spread evenly enough.
//      Check the <random> header (see: http://www.cplusplus.com/reference/random/ ) for better tools, but they're slightly more co
//      But you can worry about that out later - srand() will work for starting out.

//To make things interesting, let's have three different types of cells. You can add more later, after you get these working.
enum class CellType {Starfield, Nebula, Asteroids};

struct Asteroid
   sf::Sprite sprite;
   float rotationSpeed = 0.0f; //How fast to rotate the asteroid.

struct CellDetails
    sf::Sprite background;
    std::vector<Asteroid> asteroids;
    std::vector<sf::Sprite> stars;

std::vector<sf::Texture> NebulaTextures;
std::vector<sf::Texture> BasicBackgroundTextures; //Used for asteroid fields and star fields.
std::vector<sf::Texture> StarTextures;

//Decide what kind of cell this is.
int type = (rand() % 1000);

if(type < 10) //Only a 1% chance of a nebula.
   cellType = CellType::Nebula;
else if(type < 35) //Only a 2.5% chance of an asteroid field.
   cellType = CellType::Asteroids;
else //A 96.5% chance of a starfield.
   cellType = CellType::Starfield;

CellDetails cellDetails;

//Once we have our cell type, generate different details for that area.
if(cellType == CellType::Nebula)
    //Set the background by randomly choosing one texture from a pre-chosen vector of possible textures.
    cellDetails.background.setTexture(NebulaTextures.at(rand() % NebulaTextures.size()));
    //Randomize the coloration somewhat, but not too much.
    uint8_t redColor = 192 + (rand() % 64);
    uint8_t greenColor = 192 + (rand() % 64);
    uint8_t blueColor = 192 + (rand() % 64);
    cellDetails.background.setColor(sf::Color(redColor, greenColor, blueColor));
else if(cellType == CellType::Asteroids)
    //Set the background by randomly choosing one texture from a pre-chosen vector of possible textures.
    cellDetails.background.setTexture(BasicBackgroundTextures.at(rand() % BasicBackgroundTextures.size()));
    //Randomize how many asteroids to appear.
    const int MinAsteroids = 3;
    const int MaxAsteroids = 7;
    int numAsteroids = (rand() % (MaxAsteroids - MinAsteroids) + MinAsteroids;
    for(int i = 0; i < numAsteroids; ++i)
        sf::Sprite asteroid;
        asteroid.setTexture(AsteroidTextures.at(rand() % AsteroidTextures.size()));
        //Randomize how large to scale the asteroid, and how much to rotate it.
        float scale = (float(rand() % 150) / 100.0f) + 0.5f;
        asteroid.setScale(scale, scale);
        asteroid.setRotation(float(rand() % 360));
        //Set position.
        float posX = float(rand() % CellWidth - asteroid.getWidth()) +cellPositionInWorldPos.x;
        float posY = float(rand() % CellHeight - asteroid.getHeight()) +cellPositionInWorldPos.Y;
        asteroid.setPosition(posX, posY);
else if(cellType == CellType::StarField)
    //Set the background by randomly choosing one texture from a pre-chosen vector of possible textures.
    cellDetails.background.setTexture(BasicBackgroundTextures.at(rand() % BasicBackgroundTextures.size()));
    //Randomize how many asteroids to appear.
    const int MinStars = 30;
    const int MaxStars = 100;
    int numStars = (rand() % (MaxStars - MinStars) + MinStars;
    for(int i = 0; i < numStars; ++i)
        sf::Sprite star;
        star.setTexture(StarTextures.at(rand() % StarTextures.size()));
        //Set position.
        float posX = float(rand() % CellWidth) + cellPositionInWorldPos.x;
        float posY = float(rand() % CellHeight) + cellPositionInWorldPos.Y;
        star.setPosition(posX, posY);
        //Randomize the coloration somewhat, but not too much.
        uint8_t redColor   = (rand() % RedColorRange)   + RedMinimum;
        uint8_t greenColor = (rand() % GreenColorRange) + GreenMinimum;
        uint8_t blueColor  = (rand() % BlueColorRange)  + BlueMinimum;
        star.background.setColor(sf::Color(redColor, greenColor, blueColor));

#5231775 [SFML] Infinite space world with random spawns

Posted by on 29 May 2015 - 06:17 PM

Wow this seems like a lot to take in hahah, is there a way I can DM you to understand this a bit more? I dont want to spam up the forums


Spam up the forums; my knowledge of procedural generation is very limited - I've only played around the tiniest of bits with it - and there are much more experienced programmers here who live and breath procedural algorithms. smile.png


I can only help you with the basics that I know, but if you ask something that is beyond me, they'll be able to answer, or if I say something incorrect, they can clarify and correct me. This is what the forums exist for - public discussions, where many skilled individuals can pool knowledge and share experience.

#5231749 [SFML] Infinite space world with random spawns

Posted by on 29 May 2015 - 03:59 PM


The harder part is only creating and displaying the parts of the world that is within view, or almost within view. If there are twenty thousand enemies in your game, you only want to run logic for the 200 that are near the player, and only want to draw the 20 that are actually in view.

How exactly can I go about this?

There's several ways to go about doing that. Here's one:
Let's pretend your game has two types of things to generate: Stars in the background, and Enemies to attack the player.
Stars need to be always re-generated in the exact same position. Each time the player moves to a certain location in space, the stars shouldn't re-randomize themselves.
So imagine mentally breaking up your infinite space into "cells" of space, with each cell being... say, 1000.0f by 1000.0f large (everything is still seamlessly scrolling, but we break the infinite universe up invisibly in our code).
We use math to calculate what "cell" the player is in.

int16_t cellX = posInWorldX / WidthOfCell
int16_t cellY = posInWorldY / HeightOfCell

So when the player is in cell (25, 31), you now need some unique ID to use as a seed for your random generator. By using the cell's position as that seed, you guarantee that each time the player visits that cell, the random generator produces the exact same sequence of results, so that cell gets re-generated with the exact same details.

//I'm using bit operations here to cram the two signed 16-bit integers into one unsigned 32 bit integer.
uint32_t seedOfCell = (cellX << 16) | (cellY & 0xFFFF);

We then use this seed to randomly place the stars, and whatever other details we want.
For example, using this seed, we can then decide that 1 out of every 200 cells have a giant nebula in the background, or have asteroids that the player can interact with.
And since the seed is calculated by math - by the fixed location of the cell in space, and since the randomness isn't actually random but calculated, by math, off of the seed we give it, then each and every time the player re-visits that same location in space, the same asteroids, nebula, stars, space stations, and so on get re-generated identically as they were the first time the player visited.
Now, you want to do this not only for the cell the player is on, but also for the cells immediately surrounding the player's current cell, because the player might be at the edge of a cell and there might be multiple cells visible at once.
Since enemies move around, you can fake their generation by just randomly spawning enemies off-screen and making them move toward the player. Then you can just remove them when they go outside the player's current surrounding cells. In some cases, you actually do need to keep track of enemies, because the enemy might be a boss or miniboss.


Or, if you don't care that enemies re-spawn in the same locations each time you visit a portion of space, you can use the cell's seed to place enemies as well.

In your actual game, you might not actually care about the stars getting re-arranged each time a player visits. Most players probably wouldn't notice that. But large objects like nebula would be very noticeable if they are present one moment, and disappear the next time you visit. This is what procedural generation aims to prevent.


Easy way is to use libraries so you don't have to think too much yourself. For example this: http://libnoise.sourceforge.net/tutorials/index.html

well there isnt really any terrain going in, its going to be a space theme


Most examples of Perlin Noise you can find online will be people using it to generate terrain, but it's uses are far greater than that. It can be used, for example, to calculate how much stars you should draw in a cell, and where to put them.


Random is arbitrary. If you randomly roll 100 dice, it's possible that you can get the same result on every dice. Unlikely, but possible.


If you randomly place 100 stars in a square, it's possible that all the stars clump together ontop of each other, or that they all clump to the sides and leave emptiness in the middle, or something equally ugly. Perlin Noise can help provide more interesting and more pleasing distribution of stars, for example. Or you can use distribution algorithms like Poisson or Gaussian to help you generate your stars.


Pure randomness doesn't always give pleasing results - so game developers use the pure randomness to feed into algorithms like Perlin Noise (and other algorithms) to massage the randomness into results that look alot better and are more controllable by us developers to shape into the result we are wanting to present to our users.


Perlin noise was not invented specifically for terrain - it's just popularly used to generate terrain and can easily be used to generate other things as well. People use it for clouds, fire, universes, textures, and all kinds of things.

#5231707 [SFML] Infinite space world with random spawns

Posted by on 29 May 2015 - 12:37 PM

First of all, spawn things in world-space. Secondly, use sf::View to translate world-space to screen space.


Technically, you are already spawning things in world-space. It just so happens that your sf::View is currently set up so screen-space and world-space are identical. As soon as you start to move the view, you'll see that your objects actually are in world-space because they won't move with the screen, they'll stay relative to the world's center.


That's the easy part.


The harder part is only creating and displaying the parts of the world that is within view, or almost within view. If there are twenty thousand enemies in your game, you only want to run logic for the 200 that are near the player, and only want to draw the 20 that are actually in view.


This requires you to stream the universe around the player, generating only the parts that currently need to be available, and un-generating/freeing the parts that are no longer needed at the moment, but then being able to perfectly re-generate those areas when they are needed again.


*When I say "world" I'm not talking about a planet, I'm talking about a coordinate system that spans the entire playable region of the area the player is exploring, even the parts off-screen.


One of the primary differences between procedural generation and random generation is that random generation is random each time you do it, and procedural generation is exactly reproducible, so you can re-generate the same exact pattern multiple times.

#5231672 graphics programming with C++

Posted by on 29 May 2015 - 09:28 AM

But I don't want to do something like sfml apart from the pain in setting it up even though it makes thing easier I don't just want to make games it is more like I want to know how things work. So when I start I will start with some low level api.


Sometimes it helps to use the middle-level APIs, to learn how their interfaces are designed, before jumping to a low level and not knowing what to aim for.


But if that's really what you want to do, my advise would be to use Qt. It provides low level access to mid-level libraries in a cross-platform way, and you'll learn how GUI widgets fit together.

Qt is more for desktop applications rather than games, but it sounds like that's what you are interested in.


If you are interested in low-level 3D or 2D graphics, then you *should* use SFML for managing your windows and events, and use OpenGL for the graphics... but I think that'd dive you too fast into the deep end.


Perhaps a more ideal choice is for you to use SDL, which is probably low enough to satisfy you. I'd suggest starting with SDL, and after a year of using it, decide how you want to proceed from there.

#5231571 How To Do RPG Interiors

Posted by on 28 May 2015 - 05:50 PM

The blended design is an interesting approach, but at that point I kind of wonder what the benefit of maintaining spacial reference to the exterior is. To me, the spacial reference only matters if there's a 1:1 correspondence to the interior space. I can't dismiss the blended approach out of hand, but I'd want to identify some other benefit that carries its weight, otherwise just do a slick transition and let me have my whole screen, thanks.


Yeah, the more I've thought of it, that's kinda the conclusion I came to.


I'm not too huge of a fan of switching to a static/animated full-screen image of the shop - It's not bad, but it's not to my taste. I'm also not too fond of the disappearing roof, unless the building sizes are large enough to make the interiors seem more spacious, or unless the game is stylistically going for a more old-school Dragon Warrior feel (in which case, I actually enjoy it).


So what I'll probably do in my own game is:

  • Buildings that have nothing of interest in, you can't enter. No point wasting the player's time.
  • Buildings you can enter, but only have a single room or two of worthwhile content (i.e. an inn or a shop), I'd use the blended approach.
  • Buildings you can enter that are larger in scope, like a castle or dungeon, transition to an entirely different map.


The reason why I'd use the blended approach, with nigh-fullscreen view but no screen transition, is because it feels "smoother" to me for the player to not loose sight of his avatar, for his avatar to do no teleportation to another location on-screen, when entering smaller buildings. The disappearing roof has this same benefit - the avatar's location, in screen-space, doesn't change. (this is why I'd want the new screen to come "out of the center of the player/door", so the player's avatar is still horizontally/vertically in the same location in screen-space)


I've intuitively felt this on occasion, but wasn't able to put my finger on what was wrong with what was off, until a few months ago when I watched a video about the design of Super Mario Bros 3. When a game screen-transitions, if the avatar jumps to a different location on-screen, the player's eyes (*cough* my eyes) lose track of the avatar for a fraction of a second. Either you need to re-focus on the avatar when the screen-transition finishes (perhaps as part of a fade-in/fade-out effect), or else by removing the screen transition, the player doesn't lose track of the avatar.


So the 'blended' approach and also the disappearing roof approach both avoid the screen transition, keeping the player's eyes on the avatar.

I'd prefer the blended approach, depending on the game style, so to not have crammed-together 3-tile-wide building interiors. I'm fine with smaller building exteriors (though I prefer my buildings to be at least 5 tiles wide, depending on the tile size), but I like the building interiors to seem more roomy, while still not being so expansive that players waste time walking across the room.


I guess really to me, a full screen-transition is fine if it is seamless and the player's avatar still doesn't change location on-screen. The visible exterior around the edges of the screen don't really add anything. It's the avatar jumping around that is the problem.


Any areas that do a full screen transition, visual cues need to re-direct the player's eyes to the new avatar location, or, far more preferably, the avatar never loses its screen-space location. The easiest way to do this is to always fix the avatar to a specific location onscreen (e.g. the center, or slightly lower than the center), but you could also do it by storing the avatar's offset from the center of the screen, and restoring that offset to the camera when entering a different area. Just thinking aloud.

#5231503 Using Celebrities In My Game

Posted by on 28 May 2015 - 10:44 AM

Let's say I want to develop a small filmmaking game, which include real celebs names and photos. Would it be illegal to do without actually permission of this celebrities? And how properly ask them for permission and don't get in law issues, when game actually come out?

Who took the photographs? The photographs themselves are works of art and automatically copyrighted by the person who took them. See the Hope poster lawsuit. Personally, I think the Hope poster was fair use; it was significantly transformative in my opinion. But the case, costing money and time, was too much of a nuisance and was eventually settled, costing more money.
Faces? Celebrities make their livelihood off of their faces and names in addition to their actual skills - there's extra protection for them.
Just using the name "Matt Damon", "Johnny Depp", "Will Smith", or etc... increases the likelihood of success of a major movie. It's serious marketing.
See Right of Publicity:
"By the broadest definition, the right of publicity is the right of every individual to control any commercial use of his or her name, image, likeness, or some other identifying aspect of identity, limited (under U.S. law) by the First Amendment. [...] Because the right of publicity is primarily governed by state (as opposed to federal) law, the degree of recognition of the right of publicity varies significantly from one state to the next."
EASports got sued for trying to put college football stars in their sports game without actually using their names. Instead, they used jersey numbers, statistics, what college they attended, and so on, trying to gain the benefits of having the celebrities without actually using their name. They toed too close to the line, the lawsuit was filed, and probably fearing that they might lose, EA settled.
Celebrities make their money off of using their names and faces. Like EA, you want to benefit from using celebrities without actually paying them. They won't be happy, and they can sue you, and even if they lose, it'd cost you time and money and hassle and lost sleep.
Anyone can sue you for anything, it doesn't mean they'll win. But here, you're waving a flag with specific peoples' names on it, saying 'sue me'. And the people who're going to sue have deep pockets, plenty of lawyers on retainer, and are used to defending their right of publicity because it's their whole business model.
Invent your own "celebrities" - be creative!

#5231371 D3D11 How not to draw the pixel when alpha in texture is 0

Posted by on 27 May 2015 - 06:17 PM

I'm pretty inexperienced at 3D graphics... that said, I'm pretty sure alpha blending is what you are actually looking for.


If you want an alpha of 0.5 to make a pixel 50% transparent, then you should use alpha blending.

#5231349 graphics programming with C++

Posted by on 27 May 2015 - 04:03 PM

Why SFML and not SDL?

SDL is also nice. I like SFML slightly more, but there are parts of SDL I like more than SFML.
SFML is at a slightly higher level of abstraction, which is nice some of the time, and can get in your way at other times.

For example, SFML makes use of RAII in things like images (CPU-side) and textures (GPU-side) and so on.
But at the same time, SFML doesn't provide out of the box lower-level drawing routines to 'just draw' a texture, instead having you use it's 'Sprite' class which has position and other details.

Both libraries are nice. Both are stable, well-documented, have decently-sized communities, are easy to learn, and work well. And since I'm going to build ontop of the libraries regardless, my choice to switch to SFML was basically because at the time (back in 2011 or so) SDL hardware acceleration wasn't easy to do, whereas SFML was hardware-accelerated by default. I think the new 2.x versions of SDL are hardware accelerated though.

Because SDL is C AFAIK, although there is several third-party C++ interfaces available.

SDL is C, but C libraries are usually usable by C++ code; SDL works fine in C++ without any extra porting.

The OP should really take each one for a spin to see which he prefer.


#5231288 graphics programming with C++

Posted by on 27 May 2015 - 11:33 AM

I second SFML. In a year or two, if you decide to play with OpenGL, you can still let SFML manage your window and events for you.


C++ can definitely be confusing. It's a multi-year task to really learn the language, and even then, you'll still keep learning new things year after year.

#5231154 1 (interface) header with 2 cpp (implementation) files?

Posted by on 26 May 2015 - 05:20 PM

In my code, the application class handles the general startup/shutdown and higher level code flow, but game logic (including menus) belong in game states and game objects. It looks like you are starting to implement game states, but aren't yet taking them far enough. The logic and rendering of a game state (like the main menu of a game) should be separated out of your CMainApp.
Though I'm far from a master of software architecture, here's how I'd do it:
These functions:

void SetupMenus();
bool GetUserInputMenu();
bool RenderMenu();

...should be put into their own gamestate.
My 'GameState' class is an abstract class that has virtual functions similar to these: (among other functions)


Then, each actual game state, like "MainMenuState" inherits 'GameState' and overrides the functions.

  • MainMenuState inherits GameState
  • SetupMenus() logic goes into MainMenuState's constructor, or "MainMenuState::Activated() override;" (called when this GameState becomes the current gamestate), or else in response to a 'Screensize changed'-type of event.
  • GetUserInputMenu() logic goes into "MainMenuState::Event(event) override;"
  • RenderMenu() logic goes into "MainMenuState::Render(screen) override;"
  • Any menu animation or other time-based stuff goes into "MainMenuState::Update(delta) override;"


Then you basically do:

     //....any code that always happens, regardless of the current gamestate.
     //The current gamestate's code:



#5230979 Too clever...?

Posted by on 25 May 2015 - 10:27 PM

Yes, you are right.  I was thinking to myself that if I made them unsigned, I wouldn't even need the test for 'less than 0', since that would never happen in that case anyway.


Not only should they be logically unsigned, but they should also be size_t or (if you want to be properly pedantic) std::string::size_type.


The reason for this is because many string functions use std::string::npos as a constant. It's defined as (basically) size_t(-1).*

That is to say, the highest value a size_t variable can hold (since it's unsigned, and the -1 loops back around).


If you do this:

unsigned pos = myStr.find("blah");

if(pos == std::string::npos)
    return false;

...then ya got a bug. 'unsigned' and 'int' are both 32 bits even on 64 bit computers.* But 'size_t' is 64 bit on 64 bit computers.*


So if 'pos' is merely an 'unsigned' variable, it'd never be true.

if(my32BitInteger == TheHighestValueA64BitIntegerCanHold)
     return false;

*Usually, on modern personal computers, using the commonly-used compilers, but not guaranteed.



In my own code, if I'm making assumptions about variable sizes, I use uint32_t, uint64_t, and etc...

But when I'm using std::string's functions, I have to use std::string's assumptions (std::string::size_type - or in my code, I use size_t because it's most likely equivalent).

#5230978 1 (interface) header with 2 cpp (implementation) files?

Posted by on 25 May 2015 - 10:04 PM

Usually my classes have one implementation file and one header file, but on rare occasion I add two or more implementation files if needed. I name them in such a way so it's clear that the two sources are related. But in my own code, it's usually an indication that the class is doing too much and needs to be broken into more classes, and those situations usually eventually get refactored into smaller classes resulting back to the 1-header 1-implementation-file method. 


It's also not uncommon to have a header file, and have the implementation file be platform-dependant (e.g. one .cpp is used if on Windows, and another .cpp is used if compiling for Linux, or whatever).

#5230611 Increased frame time with less workload

Posted by on 23 May 2015 - 03:53 PM

One's taking 2.67 milliseconds, and the other one is taking 3.61 milliseconds. FPS can give misleading measurements. Or rather, FPS makes the measurements seem more dramatic than they already are.


Losing a single frame from 20 FPS to 19 FPS is a much bigger deal than losing a single frame from 100 FPS to 99 FPS.


That said, you're still measuring some difference (one is taking 1 millisecond more per frame).


Your two screenshots look different though. One looks like the blocks are casting shadows (or is that AO?) with some gradient shading and rounded edges, and the other is really sharp with flat shading. They look significantly different, at least to my beginner's eye.


Are you positive you didn't accidentally map your rotation keys also to toggling on/off special effects?