Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Why is window.draw(entity) working?  (Read 1425 times)

0 Members and 1 Guest are viewing this topic.

maniacfish

  • Newbie
  • *
  • Posts: 1
    • View Profile
Why is window.draw(entity) working?
« on: November 24, 2016, 06:33:29 pm »
I'm following the tutorials on SFML, and everything's clear except why this example is actually working.
When creating our own entity, we're suggested to derive a class from Drawable (and possibly from Transformable), and override the pure virtual function sf::Drawable::draw.
The reason for that is so that we can call the draw function through window. Since window is a RenderWindow, and it inherits its draw function form its base class RenderTarget, this will call sf::RenderTarget::draw.

As far as I know sf::RenderTarget::draw does nothing else but call sf::Drawable::draw, so:

void RenderTarget::draw(const Drawable& drawable, const RenderStates& states)
{
    drawable.draw(*this, states);
}

Now here's the problem: sf::Drawable::draw (our overriden version of it has to make a call to sf::RenderTarget::draw as well! According to the tutorial:

    virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const
    {
        // apply the entity's transform -- combine it with the one that was passed by the caller
        states.transform *= getTransform(); // getTransform() is defined by sf::Transformable

        // apply the texture
        states.texture = &m_texture;

        // you may also override states.shader or states.blendMode if you want

        // draw the vertex array
        target.draw(m_vertices, states);
    }

How does it not go into an infinite loop? I've been trying to figure out this for a while and I just can't understand.
Sorry if this has been asked before, I haven't found an answer for it.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11034
    • View Profile
    • development blog
    • Email
Why is window.draw(entity) working?
« Reply #1 on: November 24, 2016, 07:24:19 pm »
The magic lies with the friend keyword: https://github.com/SFML/SFML/blob/master/include/SFML/Graphics/Drawable.hpp#L56

That way the render traget gets access to the draw function of the drawable.

This however only partially answers your question. You probably can get into an infinite loop if you call rendertraget.draw(*this);, but usually you don't do that. Instead you call draw on e.g. a window and pass a drawable. The window then calls the drawables draw function and passes itself as render target. In the drawable's draw function you can then call draw on the render traget to render the sprites, quads etc you drawable holds. :)
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

 

anything