使用std :: future在SFML中加载纹理

时间:2012-12-17 07:11:32

标签: c++ sfml future

Visual Studio Express 2012,CTP1 c ++编译器

以下代码有效。它会加载图像并将其显示在窗口上,直到您将其关闭。

#include <memory>
#include <SFML/Graphics.hpp>
int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600), "hello");

    auto Load = []() -> std::unique_ptr<sf::Texture> {
        std::unique_ptr<sf::Texture> tex_ptr(new sf::Texture);
        tex_ptr->loadFromFile("hello.png");
        return tex_ptr;
    };    
    auto tex_ptr = Load();
    sf::Sprite spr(*tex_ptr);

    while (window.isOpen())
    {
        sf::Event ev;
        while (window.pollEvent(ev))
        {
            if (ev.type == sf::Event::Closed)
                window.close();
        }    
        window.clear();
        window.draw(spr);
        window.display();
    }
}

在以下代码中,我尝试使用std::async异步加载图像。它打印&#34;加载成功&#34;,表示在lambda中加载成功。然后,在我从未来检索纹理之后,我检查纹理的其他属性。尺寸打印正确。但是,没有图像出现。我只是得到一个黑色的窗口,它会按照命令关闭。

#include <future>
#include <memory>
#include <iostream>
#include <SFML/Graphics.hpp>
int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600), "hello");

    auto Load = []() -> std::unique_ptr<sf::Texture> {
        std::unique_ptr<sf::Texture> tex_ptr(new sf::Texture);
        if (tex_ptr->loadFromFile("hello.png"))
            std::cout << "load success\n";
        else
            std::cout << "load failure\n";
        return tex_ptr;
    };

    auto tex_ptr_future = std::async(std::launch::async, Load);

    auto tex_ptr = tex_ptr_future.get();
    sf::Sprite spr(*tex_ptr);

    // Oddly, this prints out exactly what I expect
    auto size = tex_ptr->getSize();
    std::cout << size.x << 'x' << size.y << '\n';

    while (window.isOpen())
    {
        sf::Event ev;
        while (window.pollEvent(ev))
        {
            if (ev.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(spr); // nothin'
        window.display();
    }
}

有人看到我做错了吗?

0 个答案:

没有答案