mardi 4 août 2015

c++ writing and reading text file is very slow, any alternatives?

I am currently writing code for a game and I'm a little bit stuck on saving and loading the level. For writing I use this piece of code:

    bool WorldGen::GenerateNewWorld(unsigned int seed, int width)
{
    std::cout << "World generating..." << std::endl;
    int heigth = 1; //2D perlin noise instead of 3D
    m_WorldSizeX = width;
    m_WorldSizeY = 1800; //add a int height if implementing different world sizes

    // Create a PerlinNoise object with a random permutation vector generated with seed
    PerlinNoise(seed);

    std::vector<byte> arrMaxHeight;

    // looping through all the x locations and deciding the y value
    for (unsigned int i = 0; i < heigth; ++i) {     // y
        for(unsigned int j = 0; j < width; ++j) {  // x
            double x = (double)j / ((double)width);
            double y = (double)i / ((double)heigth);

            // Typical Perlin noise
            double n = noise(10 * x, 10 * y, 0.8);

            //n is the ground added on top of the base layer (n = highest peak at point j)
            arrMaxHeight.push_back((int)(n * 255));
        }
    }

    std::wofstream fileStream;
    fileStream.open(L"GameSave/world/World.txt");

    if (fileStream.fail())
    {
        return false;
    }

    //fileStream << L"[I could put something up here but that's still in development!]" << std::endl;

    byte blockType = 0;
    std::vector<byte> arrBlockType;

    for (int i = 0; i < m_WorldSizeX; i++)
    {
        for (int j = 0; j < m_WorldSizeY; j++)
        {
            if (j > arrMaxHeight.at(i))
            {
                //block is not air
                blockType = 1;
            }
            else
            {
                //block is air
                blockType = 0;
            }

            arrBlockType.push_back(blockType);
            fileStream << blockType << "/n";
        }
    }

    fileStream.close();

    return true;
}

Now this not too bad, generates the world in around 5 minutes and sends it to world.txt without any issues, my loading(reading world.txt line per line) however takes ages. Around 30+ minutes to fully read all the lines from the text file using std::wifstream and its getline() function. It reads all the lines and adds them to a std::vector and later creates "blocks" from this vector. The creation of the blocks is done in a few seconds but the wifstream is really slow.

Any idea on how to optimise this? I was thinking about only reading blockTypes around the player but that would still require me putting all the blocks into a vector before being able to operate on them.

Kind regards, Jannes

PS: if you need the loading snippet as well I will edit it in later.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire