Bienvenue, Invité. Merci de vous connecter ou de vous inscrire. Avez-vous oublié d'activer ?

Voir les contributions

Cette section vous permet de consulter les contributions (messages, sujets et fichiers joints) d'un utilisateur. Vous ne pourrez voir que les contributions des zones auxquelles vous avez accès.


Messages - nicooomg

16
Graphique / Ecran NOIR & loadFromMemory
« le: Octobre 23, 2012, 01:16:11 am »
Petit changement.... Maintenant j'ai un écran noir :/

Voici, la boucle principale:

short SplashScreen::Run()
{

    sf::Sprite splash_screen;

    bool connect_attempt = false, splash_load = false;

    /// Running loading thread
    m_game.runPreloader();

    /// Rendering loop
    while(m_game.getRenderer().getApp().isOpen() && m_game.isRunning())
    {
        /// Clearing the window
        m_game.getRenderer().getApp().clear();
        sf::Event event;

        while(m_game.getRenderer().getApp().pollEvent(event))
        {
            /// Event handling
                /// SFGUI
            m_desktop.HandleEvent(event);
                /// SFML
            if(event.type == sf::Event::Closed)
            {
                /// This will automatically terminate the networker thread & nicely exit the game
                m_game.crash();
            }
        }

        if(!splash_load)
        {
            try
            {
                Memory& memory(m_game.getMemory());
                splash_screen.setTexture(memory.getTexture(static_cast<long>(5)));
                splash_load = true;

                std::cout << "Set Texture!"<<std::endl;
            }
            catch(bool)
            {
                std::cout << "Failed to set texture"<<std::endl;
            }

        }

        /// Drawings (SFML)
            /// The sprite (background)
        if(splash_load)
        {
            m_game.getRenderer().getApp().draw(splash_screen);
        }
        m_game.getRenderer().getApp().resetGLStates();

        /// Displayings
        m_desktop.Update(0.f);
        m_game.getRenderer().display(m_game.getRenderer().getApp());
        m_game.getRenderer().getApp().display();
    }

    return -1;
}

La fonction m_game.runPreloader(); va precharger les images dans l'instance de m_game.getMemory().

Ensuite, voici le header de la classe Memory:
typedef std::pair<long, long> MemoryKey;
                // ID, Offset
template<class S>
class MemoryRessource
{
public:
    MemoryRessource() {}
    MemoryRessource(const std::vector<char>& bytes) :
        m_buffer()
        {
            if(!m_buffer.loadFromMemory(&bytes[0], bytes.size()))
            {
                std::cout << "Failed to load from memory ! " << std::endl;
                throw false;
            }
            else
            {
                std::cout << "loadFromMemory: OK. @ address: " << &m_buffer << std::endl;
            }
        }
    ~MemoryRessource()
    {
        std::cout << "Destroying !"<<std::endl;
    }

    inline S& get() {
        std::cout << "Get texture (width=" << m_buffer.getSize().x << "; height=" << m_buffer.getSize().y << ")" << std::endl;
        return m_buffer;
        }
private:
    S m_buffer;
};

class Memory
{
        public:
                Memory() :
                    m_nodes(),
                    m_loaded_gfx(),
                    m_mtx_loader(PTHREAD_MUTEX_INITIALIZER),
                    m_percent(0)
            {}
                ~Memory()
                {
                    std::cout << "Call ~Memory() " << std::endl;
                }

                void loadPackage(const std::string& pack)
                {
                    Reader* own_reader = new Reader();
                    Node* child = own_reader->Read(pack);

                    m_nodes.insert(std::make_pair(Filesystem::extractFilename(pack),
                                    std::make_pair(own_reader, child)));
                }

                void loadGraphic(const long id)
                {
            try
            {
                Node& node(m_nodes[m_graphicPackage].second->find(id));
                MemoryRessource<sf::Texture>* res = new MemoryRessource<sf::Texture>(node.get(m_nodes[m_graphicPackage].first->stream()));
                m_loaded_gfx.insert(std::make_pair(MemoryKey(node.getId(), node.getOffset()), res));
            }
            catch(bool)
            {
                throw false;
            }
        }

        Node& operator[] (const std::string& key) { return *(m_nodes[key].second); }

        inline sf::Texture& getTexture(const MemoryKey& key) { return m_loaded_gfx[key]->get(); }
        inline sf::Texture& getTexture(const long key)
        {
            for(auto& res : m_loaded_gfx)
            {
                if(res.first.first == key)
                {
                    return res.second->get();
                }
            }
            /// In case we didn't found id... !
            throw false;
        }



                inline bool isLoaded(const MemoryKey& key) { return m_loaded_gfx.find(key) != m_loaded_gfx.end(); }
                inline pthread_mutex_t* getMutex() { return &m_mtx_loader; }
                inline long& getPercent() { return m_percent; }

        private:

                std::map<std::string, std::pair<Reader*, Node*>> m_nodes;

                std::map<MemoryKey, MemoryRessource<sf::Texture>*> m_loaded_gfx;

                pthread_mutex_t m_mtx_loader;
                long m_percent;
                const std::string m_graphicPackage = "Graphics";
};


Le chargement se passe bien.

En tout cas, voici le debug...:


Le truc vraiment etrange, c'est que c'est la meme adresse apres chargement, et quand je tente d'y acceder.
De plus, la taille affichée sur la console est la bonne.

Une idée d'où vient le probleme ?

merci, nico

17
Graphique / Re : Ecran blanc & loadFromMemory
« le: Octobre 18, 2012, 11:52:51 pm »
le probleme venait de find () :

En effet, l'algorithme STL std::for_each() ne prend pas en compte les "return" , du coup mon return marchait pas, d'ou la texture vide.

voila ^^

merci quand meme !

nico

18
Graphique / Re : Ecran blanc & loadFromMemory
« le: Octobre 18, 2012, 02:24:56 pm »
la fonction find() lance une exception si long id n'est pas trouvé, donc c'est pas ca!

19
Graphique / Ecran blanc & loadFromMemory
« le: Octobre 18, 2012, 02:35:34 am »
Bonjour,

j'essaye de precharger des textures en memoire, pour un chargement plus dynamique.
Voici ma classe qui va garder tout en memoire...
class Memory
{
        public:
                Memory() {};
                ~Memory()
                {
                    std::cout << "Call ~Memory() " << std::endl;
                }

        /// Pas important.
                void preload(const std::string& pack)
                {
                    Reader* own_reader = new Reader();
                    Node* child = own_reader->Read(pack);

                    m_nodes.insert(std::make_pair(Filesystem::extractFilename(pack),
                                    std::make_pair(own_reader, child)));
                }

        /// Ceci, marche a merveille ! Aucune exception levée
                void loadGFX(const std::string& pack, const long id)
                {
                    try
                    {
                        Node& node(m_nodes[pack].second->find(id));
                        MemoryRessource<sf::Texture>* res = new MemoryRessource<sf::Texture>(node.get(m_nodes[pack].first->stream()));
                m_loaded_gfx.insert(std::make_pair(MemoryKey(node.getId(), node.getOffset()), res));
                    }
                    catch(...)
                    {
                        throw false;
                    }
                }


                Node& operator [] (const std::string& key) { return *(m_nodes[key].second); }
        Node& operator [] (const char* key) { return *(m_nodes[std::string(key)].second); }

                inline bool isLoaded(const MemoryKey& key) { return m_loaded_gfx.find(key) != m_loaded_gfx.end(); }

        template<class S>
                static inline S& getGFX(const long id) /// longer to perform ...!
                {
                    std::for_each(std::begin(m_loaded_gfx), std::end(m_loaded_gfx), [&](std::pair<MemoryKey, MemoryRessource<sf::Texture>*> res)
            {
                if(res.first.first == id) { return res.second->get(); }
            });
                }

        /// Retournera un sf::Texture
        template<class S>
                static inline S& getGFX(const MemoryKey& key)
                {
                    return m_loaded_gfx[key]->get();
                }

        private:

                static std::map<std::string, std::pair<Reader*, Node*>> m_nodes;

                static std::map<MemoryKey, MemoryRessource<sf::Texture>*> m_loaded_gfx;
};

En premier, je fais un void preload(), pas important, cela va remplir le membre m_nodes.
Ensuite, je vais faire loadGFX() avec un identifiant. Cela va charger une sf::Texture dans m_loaded_gfx.
Voici la classe MemoryRessource:

template<class S>
class MemoryRessource
{
public:
    MemoryRessource() {}
    MemoryRessource(const std::vector<char>& bytes) :
        m_buffer()
        {
            if(!m_buffer.loadFromMemory(&bytes[0], bytes.size()))
            {
                std::cout << "Failed to load from memory ! " << std::endl;
                throw false;
            }
            else
            {
                std::cout << "Loaded " << bytes.size() << std::endl;
            }
        }
    ~MemoryRessource()
    {
        std::cout << "Destroying !"<<std::endl;
    }

    inline const S& get() const { return m_buffer; }
private:
    S m_buffer;
};

On remarquera que si le loadFromMemory est mauvais, une exception est levée, et attrapée dans loadGFX.
Jusqu'ici , tout va bien.
Voici maintenant le main :

short SplashScreen::Run()
{


    /// Preloading archives
    std::for_each(std::begin(Config::ARCHIVES), std::end(Config::ARCHIVES), [&](const std::string& pack)
    {
        std::string full_name = pack;
        full_name += Config::EXT;
        m_game.getMemory().preload(full_name); // Tout va bien ...
    });

    Memory mem;

    Node& gfx(mem["Graphics"]);

    std::vector<long> ids_to_load = {2, 5};

    std::for_each(std::begin(ids_to_load), std::end(ids_to_load), [&](long id)
    {
        try
        {
            mem.loadGFX("Graphics", id);
        }
        catch(...)
        {
            std::cout << "Could not load: " << "Graphics:" << id << std::endl;
        }
    });
/// Aucune exception levée, nous avons donc nos sf::Texture chargés en mémoire

    std::cout << "loading texture into sprite ......."<<std::endl;
    sf::Sprite s_sprite(mem.getGFX<sf::Texture>(static_cast<long>(2)));
    std::cout << "OK loaded"<<std::endl;


    /// Rendering loop
    while(m_game.getRenderer().getApp().isOpen() && m_game.isRunning())
    {
        /// Clearing the window
        m_game.getRenderer().getApp().clear();
        sf::Event event;

        while(m_game.getRenderer().getApp().pollEvent(event))
        {
            /// Event handling

                /// SFML
            if(event.type == sf::Event::Closed)
            {
                /// This will automatically terminate the networker thread & nicely exit the game
                m_game.crash();
            }
        }

        /// Drawings (SFML)
            /// The sprite (background)
        m_game.getRenderer().getApp().draw(s_sprite);

        /// Displayings
        m_game.getRenderer().getApp().display();

    }

    return -1;
}

Bref, aucune erreur d'affichée malgrès les nombreuses conditions et try{}, pourtant: écran blanc :|

Une idée quelqu'un ?

Merci d'avance, nico

20
Graphique / Fade in & Fade out
« le: Août 27, 2012, 05:54:58 am »
Bonjour,

Mon jeu possede plusieurs ecrans differents deja en place, et j'aimerais faire un bel effet de transition avec Fade in & fade out.

L'appel de la transition se fait en dehors du thread de rendu graphique.

Voici la classe:

#ifndef FADE_H_INCLUDED
#define FADE_H_INCLUDED

/// Used for screen fading.
#include <SFML/Graphics.hpp>

class Fade
{
public:
    Fade() : m_fadein(false), m_fadeout(false), m_started(false), m_rect(sf::RectangleShape()), m_alpha(0), m_goal(0) {  };
    ~Fade() {  }

    /// Called by the secondary thread
    void FadeOut() {
        /// Setting the flag to true, so the rendering thread knows that he has to fade out the screen
        /// Regular screen to full black screen.
        m_fadeout = true; m_alpha = 0; m_goal = 255;
        m_rect.setFillColor(sf::Color(0,0,0,0));
    }
    /// Called by the secondary thread
    void FadeIn() {
        /// Setting the flag to true, so the rendering thread knows that he has to fade in the screen
        m_fadein = true; m_alpha = 255; m_goal = 0;
        //m_rect.setFillColor(sf::Color(0,0,0,255));
    }

    /// Simply returns the shape for displaying
    inline sf::RectangleShape& getShape() { return m_rect; }

    /// Used by the main loop, if this returns true, the thread will draw it
    inline bool doFade() {
        if(m_fadein && (m_alpha > m_goal)) // black > screen
        {
            m_alpha--;
            m_rect.setFillColor(sf::Color(0,0,0,m_alpha));
            return true;
        }
        else if(m_fadeout && (m_alpha < m_goal)) // screen > black
        {
            m_alpha++;
            m_rect.setFillColor(sf::Color(0,0,0,m_alpha));
            return true;
        }
        else { return false; }
    }
   
    /// Used by the secondary thread, if this is true, it means the main thread is fading. Some sort of mutex :P
    inline bool Fading() const { return (m_started); }
   
    /// Used by the main thread to know if he has to perform a fade
    inline bool requestFade() const { return (m_fadein | m_fadeout); }

    /// Both used by the main thread to change the flags, so the secondary thread will know that he is fading. (cf: Fading())
    void startFading() { m_started = true; }
    void doneFading() { m_started = false; m_fadein = false; m_fadeout = false; }
    inline static const unsigned int fadingTime() { return fading_time; }

private:

    /// Flag: Fade in action
    bool m_fadein;
    /// Flag: Fade out action
    bool m_fadeout;
    /// Flag: if theres a fade processing
    bool m_started;

    /// SFML's shape
    sf::RectangleShape m_rect;

    /// Current alpha.
    unsigned int m_alpha;
    /// Alpha to reach
    unsigned int m_goal;

    static const unsigned int fading_time = 10; // in ms

};



#endif // FADE_H_INCLUDED


Quand je veux faire un fade, de mon thread secondaire, je fais ceci:
    m_gameui.getRenderer().getFader().FadeOut(); // Appel a fade out : ecran > ecran noir
    nextScreen(); // Simple routine qui permet a l'ecran de se mettre a jour sous l'ecran noir
    while(m_gameui.getRenderer().getFader().Fading()) {} // On attend pendant que le fade se termine (donc ecran noir
    m_gameui.getRenderer().getFader().FadeIn(); // Et hop on retourne au nouvel ecran


Et mon thread principal:

short LoginScreen::Run()
{
    m_desktop.GetEngine().LoadThemeFromFile("Data/css/login.css");

    /// Add the UI to the window
    m_desktop.Add(getScreen());
    /// Rendering loop
    while(m_game.getRenderer().getApp().isOpen() && m_game.isRunning())
    {
        /// Clearing the window
        m_game.getRenderer().getApp().clear();


        sf::Event event;
        while(m_game.getRenderer().getApp().pollEvent(event))
        {
            /// Event handling
                /// SFGUI
            m_desktop.HandleEvent(event);
                /// SFML
            if(event.type == sf::Event::Closed)
            {
                /// This will automatically terminate the networker thread & nicely exit the game
                m_game.crash();
            }
        }
        m_game.getRenderer().getApp().resetGLStates();
        /// Drawings (SFGUI)
            /// UI
        if(changeScreen())
        {
            oldScreen()->Show(false);
            m_desktop.Remove(oldScreen());
            getScreen()->Show(true);
            m_desktop.Add(getScreen());
        }

        /// Fading out (screen to black)
        if(m_game.getRenderer().getFader().requestFade())
        {
            m_game.getRenderer().getFader().startFading();
        }
        if(m_game.getRenderer().getFader().Fading())
        {
            if(m_game.getRenderer().getFader().doFade())
            {
                m_game.getRenderer().getApp().draw(m_game.getRenderer().getFader().getShape());
            }
            else
            {
                m_game.getRenderer().getFader().doneFading();
            }
        }

        /// Displayings
        m_desktop.Update(0.f);
        m_game.getRenderer().display(m_game.getRenderer().getApp());
        m_game.getRenderer().getApp().display();

    }

    return -1;
}

Le probleme ?
L'ecran devient tout noir d'un coup, et j'ai acces a l'ecran caché derriere ce noir.
Comment faire pour avoir une belle transition ?

Merci d'avance,

nico

21
Graphique / Probleme de conception
« le: Août 23, 2012, 05:31:38 pm »
Bonjour,

Je cherche a faire ceci:
- Un sprite, avec un texte en dessous, et que le tout soit clickable, et meme double-clickable.

J'utilise SFML 2 ainsi que SFGUI. Et je me demande s'il n'est pas possible de combiner les deux.
Peut etre une classe qui à sf::Sprite plus un sfg::Button (invisible) en tant que membre, et de plus, qui hérite de sfg::Widget publiquement pour pouvoir l'ajouter au conteneurs de SFGUI !

Est-ce une bonne facon de faire?

Merci, nico

22
Graphique / Re : Affichage d'une partie d'un sprite
« le: Juin 29, 2012, 12:37:06 am »
Attend ya un probleme la ! C'est forcement possible.
Je m'explique avec la SDL.

int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect);

grace a srcrect, on peut clipper une surface de telle sorte a selectionner uniquement une partie de la surface !
donc utiliser une feuille de sprite !

Ca je vais en avoir besoin.

Le deuxieme besoin, qui peut etre emuler aussi comme si cetait une feuille de sprite, cest que jai une image qui sert de fond decran, qui est donc gigantesque par rapport a la taille de la fenetre et je dois la deplacer (ou deplacer le viewport(??)) sur limage, pour effectuer un scroller dans toutes les directions, a ma guise, comme si cetait le fond decran du jeu mario !

Je suis peu etre plus clair sur ce que jrecherche maintenant :)

23
Graphique / Re : Affichage d'une partie d'un sprite
« le: Juin 28, 2012, 06:11:24 pm »
La sfml est simple, mais alors cette fonctionnalité est plus simple sur la SDL.
J'ai une fenetre de taille 800*600.
Une texture de taille 3000*1200.

Je veux afficher la partie de la texture de
x:0
y:600 (donc, texture.y - window.y)
largeur: 800
hauteur: 600.

Comment faire?

24
Graphique / Re : Affichage d'une partie d'un sprite
« le: Juin 28, 2012, 05:42:11 pm »
Non je comprend tres bien a quoi ca sert ! C'est justement ce que jessaye de faire !
Mais, maptexture.getSize().y-winsz.y retourne 600. (*c'est simple, ma texture fait 3000*1200).
Donc mon carré: debut: 0, 600. taille: 800,600 (ma fenetre.. !)

Pourtant je suis toujours en haut a droite de mon image :(

J'aimerais afficher le carré en bas a gauche.
Au final c'est une image 2D et je vais bouger le rectangle de gauche a droite.

25
Graphique / Re : Affichage d'une partie d'un sprite
« le: Juin 28, 2012, 04:20:00 pm »
Bonjour.. malheureusement, ton code ne change rien... enfin je crois
j'essaye:

void MapScroller::setViewport(const sf::IntRect& camera)
{
    std::cout << "viewport"<<std::endl;
    mapsprite.setTextureRect(sf::IntRect(0, maptexture.getSize().y-winsz.y, winsz.x, winsz.y));
    mapsprite.setPosition(0, maptexture.getSize().y-winsz.y);
}

Je suis toujours en haut a gauche...

26
Général / Re : [segfault] Appel de RenderWindow::create()
« le: Juin 27, 2012, 06:21:38 pm »
Oui j'avais oublié de la rajouter, mais ce systeme etait justement fait pour egalement faire la destruction automatique !
Je vais voir par la suite si ca me retombe dessus, mais la j'avance doucement mais bien ^^

merci lg !

nico

27
Graphique / Affichage d'une partie d'un sprite
« le: Juin 27, 2012, 06:19:40 pm »
Bonjour :)

Alors voici ma fonction:
void MapScroller::setViewport(const sf::IntRect& camera)
{
    mapsprite.setTextureRect(sf::IntRect(0, maptexture.getSize().y-winsz.y, winsz.x, winsz.y));
}
 

Le probleme: He bien, le rectangle d'affiche est toujours en haut a gauche ... !
Alors que normalement , je devrais avoir: sf::IntRect(0, 600, 800, 600);

Comment faire pour afficher simplement une partie ?

merci d'avance, nico

28
Général / Re : [segfault] Appel de RenderWindow::create()
« le: Juin 27, 2012, 05:35:02 pm »
Le contexte:
- Avoir plusieurs ecrans differents dans une meme RenderWindow, tres utile pour un jeu ! (splash screen, menu, jeu, options, etc.)

int main()
{
    // sfml window
    sf::RenderWindow App(sf::VideoMode(800, 600), "Game");

    std::vector<Screen*> Screens;
    Screens.push_back(new SplashScreen());

    int current_screen = SplashScreen::ID;
    int temp_screen;

    while(current_screen >= 0)
    {
        // On lance l'affichage
        temp_screen = Screens[current_screen]->Run(App);
        if(temp_screen != current_screen)
        {
            current_screen = temp_screen;
        }
    }
    return EXIT_SUCCESS;
}


// SplashScreen
class SplashScreen: public Screen
{
    public:
        SplashScreen()
        {

        }
        ~SplashScreen() {}
        int Run (sf::RenderWindow& App);

        static const int ID = 0;
};




int SplashScreen::Run(sf::RenderWindow& App)
{
    // Splash Screen loading
    sf::Texture splash;
    if(!splash.loadFromFile("Data/gui/splash/splashscreen.jpg"))
    {
        exit(0);
    }
    sf::Sprite spr(splash);

    while(App.isOpen()) {
        // Clearing out the window
        App.clear();
        // Event processing.
        while(App.pollEvent(m_event) ) {
            // If window is about to be closed, leave program.
            if(m_event.type == sf::Event::Closed) {
                App.close();
            }
        }


        App.draw(spr);

        App.display();
    }
    return -1;
}


Et maintenant, Screen

class Screen
{
    public :
        Screen() {};
        ~Screen() {};
        virtual int Run (sf::RenderWindow& App) {};

        static sf::Event m_event;
        static sf::Clock m_clock;

};

Sans le static, j'ai un ecran noir. :)

J'ajoterais que c'est le meme probleme en ajoutant SFGUI pas en static, ecran noir :)

voila !

nico

29
Général / Re : [segfault] Appel de RenderWindow::create()
« le: Juin 27, 2012, 03:35:16 pm »
Eh bien je pouvais egalement en creer plusieurs quand j'avais gcc 4.4.
Une fois passer a 4.7, et avoir recompiler sfml. J'avais un ecran noir avec le meme code.
Le passage de sf::Event unique pour chaque ecran resolvait le probleme.

Tu veux quoi exactement LG?

30
Général / Re : [segfault] Appel de RenderWindow::create()
« le: Juin 27, 2012, 03:08:51 am »
Voici la solution !

En fait la SFML n'accepte pas de doublons sf::Event !
Donc avoir plusieurs classes qui servent d'écrans, avec chacune son propre membre sf::Event = aucun affichage.

Donc, pour avoir plusieurs ecrans, comme sur ce tutorial, avec gcc 4.7 (apparement !) https://github.com/SFML/SFML/wiki/TutorialScreens

Il faut utiliser une classe mere de ce type:


class Screen
{
    public :
        Screen() {};
        ~Screen() {};
        virtual int Run (sf::RenderWindow& App) {};

        static sfg::SFGUI m_sfgui;
        static sfg::Desktop desktop;
        static sf::Event event;
        static sf::Clock clock;
};

@LaurentGomila:
Merci de noter dans les tutoriels que plusieurs variables de type sf::Event fait foirer le code.
Est-ce un probleme interne ? Si oui, tu devrais mettre une protection sur les types qui ne doivent surtout pas exister plusieurs fois !

nico :)

anything