SFML community forums

General => SFML projects => Topic started by: Nexus on March 19, 2012, 05:40:54 pm

Title: Thor 2.0 released!
Post by: Nexus on March 19, 2012, 05:40:54 pm
(http://www.bromeon.ch/thor/thor.png)

Thor 2.0 released!

Thor is an open-source and cross-platform C++ library. It extends the multimedia library SFML with higher-level features such as:
Links


(click to show/hide)
Title: Thor 2.0
Post by: eXpl0it3r on March 21, 2012, 08:54:50 am
Looking forward to it! :D

Btw does Thor 2.0 depend up on Aurora, I mean do I have to checkout Aurora too if I want to use Thor 2.0?

Edit: Oh I just saw that Aurora is included in the extlib folder. :)
Title: Thor 2.0
Post by: Laurent on March 21, 2012, 09:05:29 am
Quote
Aurora is included in the extlib folder

Nexus, do you know that you can add it as a Git submodule instead of copying it? A submodule is a link/shortcut to an external repository, at a given revision. As a result, the submodule appears as if it was directly included in the main repo, but in fact you get its files from its own repo directly.
Title: Thor 2.0
Post by: Nexus on March 21, 2012, 11:29:56 am
Yes, I originally wanted to do it like this. However I've had some trouble setting it up with local repositories, and I've read at different places that submodules wouldn't be a very mature concept (for example, one cannot easily delete them). If I remember correctly, a Git clone doesn't clone submodule directories, leaving more work to the user. Currently I use the subtree approach described here (http://progit.org/book/ch6-7.html).

Or have you made other experiences and can you recommend Git submodules?
Title: Thor 2.0
Post by: Laurent on March 21, 2012, 11:53:56 am
Quote
If I remember correctly, a Git clone doesn't clone submodule directories, leaving more work to the user.

Instead of
Quote
git pull

one would have to do
Quote
git pull
git submodule update

(same with "init" instead of "update" for the initial cloning)

Quote
Or have you made other experiences and can you recommend Git submodules?

We're using it when working on multiple interconnected projects, and so far it has always been ok for us.
However I've never tested the subtree approach so I cannot compare.
Title: Thor 2.0
Post by: Ceylo on March 21, 2012, 01:59:02 pm
With submodules :
- you can't just do git clone (have to add --recursive)
- the zip archive provided by GitHub won't include the submodules
- you still have to manually update the submodule head against which you want your own sources to be updated (if modifications are done in SFML repo, they won't be automatically transferred to your repo for example)
Title: Re: Thor 2.0
Post by: Nexus on March 25, 2012, 10:48:13 am
Thanks for the information, Ceylo. I have switched to the git-subtree (https://github.com/apenwarr/git-subtree) tool, it works good so far. And the advantage over git merge -s subtree is that I can have one commit and a merge (because in subtree merge, --squash  hides the merge message). And of course it's easier, I don't need a separate branch.
Title: Re: Thor 2.0
Post by: pierreyoda on March 25, 2012, 11:06:12 am
Hello, I switched to Thor 2.0 (after hours of pain with boost::python in order to make aur::CopiedPtr work...  :-X ) but I get a std::logic_error when loading an image : "No copy allowed".
Same error in the Resources example.

I should note that I disabled C++11 support (commenting "aur/Config.hpp", as it provoked compile errors in cmath (MinGW build : , i.e. TDM-GCC 4.6.1), I guess the problem is there  ???
Title: Re: Thor 2.0
Post by: Nexus on March 25, 2012, 11:25:38 am
Yes, that's the problem. A little bit on the background:

In some cases, aur::CopiedPtr doesn't have to be copied, for example when you pass a temporary object to a function or return an object from a function. In C++11, this is very easy to achieve with move semantics. In C++98, I hoped that compiler optimisations (like RVO) could lead to the same result, but in fact it's too unreliable to make semantics depend on it. The std::logic_error approach is an interim solution, it's not my style to throw exceptions upon logic errors.

Unfortunately, there is no elegant way to transfer ownership in C++98. In Thor 1, MovedPtr was designed to achieve this, but I realized the whole design got too complicated and unintuitive (a user didn't know when to use which smart pointer, had to invoke thor::Copy() manually in some cases, and was surprised by implicit ownership transfer). That's why I simplyfied the Aurora.SmartPtr module a lot -- and interestingly -- made it far more powerful at the same time.

I see two solutions to deal with the problem:
You say C++11 support provoked compile errors, can you give more details?
Title: Re: Thor 2.0
Post by: pierreyoda on March 25, 2012, 12:34:53 pm
Well, I just updated and rebuild Thor and... it works!  ???
The only visible difference is the "THOR_USE_CPP11" option in cmake (CXX_FLAGS was already set to "-std=c++0x")... Whatever, It works  :P

PS : the error was in cmath, on a "using :..." line.
Title: Re: Thor 2.0
Post by: Nexus on March 25, 2012, 05:19:06 pm
The first bigger refactoring has been done, it concerns the design of the particle emitters. I wrote the new UniversalEmitter class, which is far more powerful than the existing emitters. As the name implies, you can set every initial particle attribute using a functor. That is, you specify a function that is called every time a particle is emitted. For example, you can specify a random distribution for the initial position. Or set the position according to the mouse or another game object. Hereby, the predefined distributions in Math/Distributions.hpp may be of help.
thor::UniversalEmitter::Ptr emitter = thor::UniversalEmitter::create();
emitter->setEmissionRate( 20 );
emitter->setPosition( thor::Distributions::circle(center, radius) );
emitter->setRotation( thor::Distributions::uniform(0.f, 360) );

Using the aur::Distribution class template, you can also specify constants, so the syntax is still simple if you don't need the flexibility:
emitter->setColor( sf::Color::Red );
emitter->setLifetime( sf::seconds(4) );

This new design also has an impact on other parts of the library, namely:
Title: Re: Thor 2.0
Post by: Astrof on March 28, 2012, 07:00:59 am
I'm having a problem trying to compile Thor with CMake.  Specifically I'm getting the same SFML_DIR-NOTFOUND error (whether I change SFMLDIR or SFML_DIR it always comes out with the same error). I have SFML installed from the git tutorial. 

EDIT: I got it fixed; for some reason the FindSFML.cmake file wasn't copied to the Modules folder in CMake.  Copying it over seemed to fix it.  While compiling however I get an error when trying to compile the examples:

Code: [Select]
C:\Thor\examples\Particles.cpp: In function 'int main()':
C:\Thor\examples\Particles.cpp:111: error: no matching function for call to 'sf:
:RenderWindow::convertCoords(unsigned int&, unsigned int&)'
C:/Program Files (x86)/SFML/include/SFML/Graphics/RenderTarget.hpp:152: note: ca
ndidates are: sf::Vector2f sf::RenderTarget::convertCoords(const sf::Vector2i&)
const
C:/Program Files (x86)/SFML/include/SFML/Graphics/RenderTarget.hpp:177: note:
              sf::Vector2f sf::RenderTarget::convertCoords(const sf::Vector2i&,
const sf::View&) const
mingw32-make[2]: *** [examples/CMakeFiles/Particles.dir/Particles.cpp.obj] Error
 1
mingw32-make[1]: *** [examples/CMakeFiles/Particles.dir/all] Error 2
mingw32-make: *** [all] Error 2
Title: Re: Thor 2.0
Post by: DJuego on March 28, 2012, 02:16:49 pm
I'm having a problem trying to compile Thor with CMake.  Specifically I'm getting the same SFML_DIR-NOTFOUND error (whether I change SFMLDIR or SFML_DIR it always comes out with the same error). I have SFML installed from the git tutorial. 

EDIT: I got it fixed; for some reason the FindSFML.cmake file wasn't copied to the Modules folder in CMake.  Copying it over seemed to fix it.


Yep! I confirm the problem and the solution (thanks Astrof!) with Bromeon-Thor-9b4b3d9.tar.gz.

On the other hand I can not meta-build the examples with CMake-2.8.7

Code: [Select]
CMake Error at CMakeLists.txt:38 (thor_link_thor):
  Unknown CMake command "thor_link_thor".
Call Stack (most recent call first):
  CMakeLists.txt:51 (thor_example)


CMake Warning (dev) in CMakeLists.txt:
  No cmake_minimum_required command is present.  A line of code such as

    cmake_minimum_required(VERSION 2.8)

  should be added at the top of the file.  The version specified may be lower
  if you wish to support older CMake versions for this project.  For more
  information run "cmake --help-policy CMP0000".
This warning is for project developers.  Use -Wno-dev to suppress it.

Configuring incomplete, errors occurred!


Thanks in Advance!!

DJuego

P.S: Fantastic complement, Nexus. Thank you very much!!!  :P

Windows 7 64b
Visual Studio 2010
Title: Re: Thor 2.0
Post by: pierreyoda on March 28, 2012, 05:54:19 pm
By the way, the Airport download links are broken  :P
Title: Re: Thor 2.0
Post by: Nexus on March 29, 2012, 05:52:40 pm
I'm having a problem trying to compile Thor with CMake.  Specifically I'm getting the same SFML_DIR-NOTFOUND error (whether I change SFMLDIR or SFML_DIR it always comes out with the same error). I have SFML installed from the git tutorial.
I think you have to install SFML, not just build it (the CMake install command copies the FindSFML file). You have to type make install (using g++) or compile the INSTALL project (Visual Studio).

On the other hand I can not meta-build the examples with CMake-2.8.7
What do you mean with meta-build? The examples/CMakeLists.txt file cannot be used autonomously, it is invoked by the top-level CMakeLists.txt.

By the way, the Airport download links are broken  :P
Thanks, I'll fix them.
Title: Re: Thor 2.0
Post by: DJuego on March 29, 2012, 07:34:20 pm
I'm having a problem trying to compile Thor with CMake.  Specifically I'm getting the same SFML_DIR-NOTFOUND error (whether I change SFMLDIR or SFML_DIR it always comes out with the same error). I have SFML installed from the git tutorial.
I think you have to install SFML, not just build it (the CMake install command copies the FindSFML file). You have to type make install (using g++) or compile the INSTALL project (Visual Studio).

Correct.  I am not accustomed "to install" libraries. I don't like. Perhaps it will be enough relocating the folder 'cmake/Modules/findSMFL' to the 'installation directory'.

On the other hand I can not meta-build the examples with CMake-2.8.7
What do you mean with meta-build? The examples/CMakeLists.txt file cannot be used autonomously, it is invoked by the top-level CMakeLists.txt.


Forget it! I am a *noob* with CMake.  :'(  My problem...

Code: [Select]
1>------ Build started: Project: ZERO_CHECK, Configuration: Release Win32 ------
2>------ Build started: Project: Particles, Configuration: Release Win32 ------
2>  Particles.cpp
2>W:\Librerias-VS2010\SFML\Bromeon-Thor-9b4b3d9\examples\Particles.cpp(111): error C2664: 'sf::Vector2f sf::RenderTarget::convertCoords(const sf::Vector2i &,const sf::View &) const' : cannot convert parameter 1 from 'unsigned int' to 'const sf::Vector2i &'
2>          Reason: cannot convert from 'unsigned int' to 'const sf::Vector2i'
2>          No constructor could take the source type, or constructor overload resolution was ambiguous
========== Build: 1 succeeded, 1 failed, 1 up-to-date, 0 skipped ==========

Sorry! You need update the git snapshot Thor to the new *SFML* commits.  ;D

Thank you for your dedicated attention, Nexus!

DJuego
Title: Re: Thor 2.0
Post by: Astrof on March 29, 2012, 07:40:14 pm
I'm having a problem trying to compile Thor with CMake.  Specifically I'm getting the same SFML_DIR-NOTFOUND error (whether I change SFMLDIR or SFML_DIR it always comes out with the same error). I have SFML installed from the git tutorial.
I think you have to install SFML, not just build it (the CMake install command copies the FindSFML file). You have to type make install (using g++) or compile the INSTALL project (Visual Studio).


I did use make Install to install it (I even did a clean then install and it didn't work; for some reason the .cmake file wasn't being copied to the modules folder (even with all admin privileges and everything set)).  Manually copying the file over however did fix it.  If it helps I was using mingw and Codeblocks and not Visual Studio as I don't have Visual Studio installed on this computer. 


Also are the tutorials outdated on your website? I tried some of the tutorials (specifically the particles one) and it seems certain classes have changed.  Overall everything is awesome I just have to play around with it a bit more.
Title: Re: Thor 2.0
Post by: Laurent on March 29, 2012, 08:39:21 pm
FindSFML.cmake is no longer automatically copied to the CMake install directory, you need to do it manually, or add the path where it is to the CMAKE_MODULE_PATH CMake variable so that it can find it.
Title: Re: Thor 2.0
Post by: Nexus on March 30, 2012, 06:10:06 pm
I am not accustomed "to install" libraries. I don't like.
Why not? I think it's the best option to setup everything automatically and correctly.

Also are the tutorials outdated on your website?
Yes, the tutorials for the new version have not been written yet, since several things may still change.

Overall everything is awesome I just have to play around with it a bit more.
Thanks! If you have some ideas, just tell me! :)

FindSFML.cmake is no longer automatically copied to the CMake install directory
Why have you changed that? This was an easy way to use SFML in other projects. I fear this problem is going to come up often in the future, since people are usually not very familiar with CMake. And I'm glad about every single step the user needn't do on his site to compile a project...
Title: Re: Thor 2.0
Post by: Laurent on March 30, 2012, 08:47:41 pm
Quote
Why have you changed that?
It could require admin rights.
I think it's generally a good idea to avoid copying stuff outside the SFML install dir, because the user doesn't have much control on that.

Quote
I fear this problem is going to come up often in the future, since people are usually not very familiar with CMake
People playing with CMake are usually not beginners, there are public releases for them ;)
Title: Re: Thor 2.0
Post by: Astrof on March 31, 2012, 06:10:12 am
Thanks! If you have some ideas, just tell me! :)

For sure! Though I'm a bit rusty on my programming with med school and all.  Once SFML (and Thor) 2.0 get "finalized" I'd love more/new tutorials!
Title: Re: Thor 2.0
Post by: Nexus on March 31, 2012, 10:11:06 am
People playing with CMake are usually not beginners, there are public releases for them ;)
There are still many people following the development version, and for that no in-depth CMake knowledge has been required up to now. The current need to manually copy files is not standing to reason, especially if it's undocumented. I think this might also be difficult to document, since the CMake module directory is different depending on how CMake has been installed.

Was it really a problem, did many users have issues with admin rights? What about an optional checkbox in SFML's CMakeLists configuration, so that the user could choose whether FindSFML should be copied?

Once SFML (and Thor) 2.0 get "finalized" I'd love more/new tutorials!
I'll certainly update the old tutorials, do you have concrete parts of the library in mind for which I should write new ones? Animation might be such a candidate, others?
Title: Re: Thor 2.0
Post by: Laurent on March 31, 2012, 10:32:27 am
Quote
Was it really a problem, did many users have issues with admin rights?
It happens, yes. A typical configuration is a Linux where you have rights only in your home folder; in this case users will try to install SFML to, let's say, /home/laurent/libs/sfml but it will fail because it will attempt to install something to /usr/share/CMake/modules.

Quote
What about an optional checkbox in SFML's CMakeLists configuration, so that the user could choose whether FindSFML should be copied?
I don't even know if it's the right solution; don't forget that there's another option which is to tell CMake where FindSFML.cmake is located.
Title: Re: Thor 2.0
Post by: Astrof on March 31, 2012, 08:09:21 pm
I'll certainly update the old tutorials, do you have concrete parts of the library in mind for which I should write new ones? Animation might be such a candidate, others?

Right now I'm mainly using the Particle Systems part of Thor, along with any Aurora things with it.  What confused me, at least initially, was going from different emitters to a UniversalEmitter. 

As for the cmake file and admin rights, what I (and maybe other Windows users) do is just run everything as administrator, especially when running install commands (as without it the install command doesn't work).  Horrible practice but it works. 
Title: Re: Thor 2.0
Post by: Laurent on March 31, 2012, 08:17:06 pm
Quote
As for the cmake file and admin rights, what I (and maybe other Windows users) do is just run everything as administrator, especially when running install commands (as without it the install command doesn't work).
My point was that sometimes you can't have the admin rights.
Title: Re: Thor 2.0
Post by: Astrof on April 01, 2012, 12:25:16 am
My point was that sometimes you can't have the admin rights.

Ah true then I like the idea of pointing cmake to the FindSFML file. 
Title: Re: Thor 2.0
Post by: Nexus on April 02, 2012, 05:44:06 pm
What confused me, at least initially, was going from different emitters to a UniversalEmitter.
But do you like the new approach? And is the documentation detailed enough to understand how it works? I uploaded a first version of an updated tutorial not to leave users in the dark, however there are still some parts to improve.

By the way, I am probably going to enforce C++11 in Thor, as it makes a lot really simpler. Especially move semantics, lambda expressions and the smart pointers are extremely useful. And in the end, it's also better for the users because there are less wheel reinventions in my library ;)
Title: Re: Thor 2.0
Post by: Astrof on April 02, 2012, 08:46:41 pm
I do like the new approach; I like how it's more customizable however it does require the user to do more work themselves (yes I'm lazy lol).  The documentation is also really well done so it just takes a bit of reading to learn.  Again something that threw me off was the PolarVector; I've never used a polar vector to draw before (except on a TI-83). 


If I have any specific questions on functionality/how to do something should I just message you directly (instead of posting everything on this thread)?
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 02, 2012, 09:03:34 pm
Laurent changed tha API again (no more getHeight getWidth on textures)...  ::)

So we can't compile Thor 2.0 anymore.
Title: Re: Thor 2.0
Post by: Nexus on April 03, 2012, 02:21:38 pm
however it does require the user to do more work themselves (yes I'm lazy lol).
I thought it became easier ;)
What do you have to do in addition at the moment?

TAgain something that threw me off was the PolarVector; I've never used a polar vector to draw before
thor::PolarVector2 is just another representation of sf::Vector2, using polar coordinates. It's not mandatory, you can also use sf::Vector2 and the functions thor::rotate() and thor::rotatedVector() to turn them, PolarVectors just make some parts easier (and partially more efficient and precise)...

If I have any specific questions on functionality/how to do something should I just message you directly (instead of posting everything on this thread)?
Yes. If the questions are rather general (design, API, ...), you can post them here ;)

Laurent changed tha API again (no more getHeight getWidth on textures)...  ::)

So we can't compile Thor 2.0 anymore.
Thanks, I'll fix it as soon as possible.
Title: Re: Thor 2.0
Post by: Astrof on April 03, 2012, 06:43:22 pm
I thought it became easier ;)
What do you have to do in addition at the moment?

It's easier in the sense that if we want to make custom emitters we just have to pass functions instead of creating our own custom class; however it takes more work to do the simple emitters (Directional, etc) as now we have to "think" and figure out for ourselves what to do.  I know; it's so hard. 
Title: Re: Thor 2.0
Post by: Nexus on April 03, 2012, 07:13:20 pm
The main thing you can't do like before is this:
emitter->setParticleVelocity(v);
emitter->setEmissionAngle(a);
It's now
emitter->setVelocity( thor::Distributions::deflect(v, a/2) );
With the new approach, it is clearer which attribute (velocity) is modified. But I see it may look more complicated if you're used to the DirectionalEmitter :)

By the way, I've adapted Thor to the SFML modification.
Title: Re: Thor 2.0
Post by: Astrof on April 03, 2012, 07:21:51 pm
Ah I get it now; my problem was I was taking the same line of code to change the velocity and was throwing in random Distributions (like circle, rect, etc) so i was confused how that distribution was changing everything. 
Title: Re: Thor 2.0
Post by: DJuego on April 03, 2012, 09:50:05 pm
By the way, I've adapted Thor to the SFML modification.

Thank you Nexus!  :-* The particle system cast a spell on me...

I am sure that you would encourage your addon (and SFML) by means of youtube videos with guides/samples for smoke, fire, water, snow/sand torments. It will be instructive and a exhibition of magic power  ;D

DJuego

Sorry for muy defective English.
Title: Re: Thor 2.0
Post by: Nexus on April 06, 2012, 04:56:32 pm
That's a good idea, but I'll probably focus on such things if most of the functionality for the next version has been implemented ;)
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 07, 2012, 12:17:13 pm
I have two question about the resource manager.

1. When I had the resource key K and now acquire the resource with two diffrent resource pointers, do I get now twice a 'reference' to the resource or is it more like copying one resource pointer to another?

thor::ResourceManager<sf::Texture> Mgr;
thor::Resource::TextureKey K thor::Resource::TexutreKey::fromFile("image.png");
thor::ResourcePtr<sf::Texture> ptr1 = Mgr.acquire(K);
thor::ResourcePtr<sf::Texture> ptr2 = Mgr.acquire(K);
// What's the difference to this
thor::ResourcePtr<sf::Texture> ptr3 = Mgr.acquire(K);
thor::ResourcePtr<sf::Texture> ptr4 = ptr3;
 

2. If I had a LoadSprites() function with which I'd initialize all my sprites and I'd now go and acquire every resource I'd need and safe it in resource pointers which are local to that function, hand the resource over to the sprite object and then leave this function, will the resources now get freed (since the resource pointer get destroyed at the end of the function) and thus the sprites will have an invalid texture?
Maybe the question could also be ask like, do I have to store the resource pointers in the class, if I want to use it from diffrent functions?

sf::Sprite S;
void LoadSprites()
{
        thor::ResourceManager<sf::Texture> Mgr;
        thor::Resource::TextureKey K thor::Resource::TexutreKey::fromFile("image.png");
        thor::ResourcePtr<sf::Texture> ptr = Mgr.acquire(K);
        S.setTexture(*ptr);
}
void Draw()
{
        // ...
        window.Draw(S);
        // ...
}
}

I hope I made my questions enough clear...
Title: Re: Thor 2.0
Post by: Nexus on April 07, 2012, 12:31:16 pm
1. When I had the resource key K and now acquire the resource with two diffrent resource pointers, do I get now twice a 'reference' to the resource or is it more like copying one resource pointer to another?
Using the same key, acquire() returns the same resource, so yes, you could as well copy the resource pointer. But sometimes you don't already have a resource pointer, only a filename or something (which is stored in the key).

2. If I had a LoadSprites() function with which I'd initialize all my sprites and I'd now go and acquire every resource I'd need and safe it in resource pointers which are local to that function, hand the resource over to the sprite object and then leave this function, will the resources now get freed (since the resource pointer get destroyed at the end of the function) and thus the sprites will have an invalid texture?
Yes, the resources would be released. To ensure your resource stays alive, keep a resource pointer to it. I know the integration to SFML's classes is not seamless (since sf::Sprite only takes raw pointers), there's not much I can do about it except to provide an own sprite class, but that would only pay out if it combined other improvements (like thor::BigSprite).

By the way, the Resources module is probably the next part I'm going to refactor. The basic concept remains the same, but there will be std::shared_ptr and different resource keys. And I think I can no longer postpone the decision of C++11 support, I'll make it a prerequesite.
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 07, 2012, 02:25:28 pm
Thanks for the answers!

By the way, the Resources module is probably the next part I'm going to refactor. The basic concept remains the same, but there will be std::shared_ptr and different resource keys.

What do you mean with diffrent resource keys?

And I think I can no longer postpone the decision of C++11 support, I'll make it a prerequesite.
I think it's okay to prerequesite C++11 as long as the common compiler (MSVC 2010 and GCC 4.8+) can compile it.

Since you're gonna refractor it, I wanted to asked if it was somehow possible to combine the resource manager into one class or provide another class which combines the other ones. It's just kinda of annoying if you have to keep track of three or more diffrent resource managers (one for loading fonts, one for loading textures, one for loading sounds, etc). I don't know how one would do this the best way but maybe you do! ;D

Title: Re: Thor 2.0
Post by: Nexus on April 07, 2012, 02:56:37 pm
What do you mean with diffrent resource keys?
I thought about a single class template thor::ResourceKey<R>, where R is the resource. For example, thor::ResourceKey<sf::Texture> replaces thor::Resources::TextureKey. It can be initialized from a function returning a pointer to a resource (maybe unique_ptr) and a string representation to compare different keys. It also provides methods to actually load a resource and to get debug informations. Resource keys are more constrained (one must use thor::ResourceKey), but custom ones are easier to construct.
template <class R>
class ResourceKey
{
    public:
                             ResourceKey(std::function<R*()> loader, std::string key);
        std::unique_ptr<R>   load() const;
        std::string          getInfo() const;
};

Furthermore, there are free functions that create a resource key, for example:
template <class R>
thor::ResourceKey<R> thor::Resources::fromFile(std::string filename);

Note that it is a template. It should be able to load every class providing a method
bool R::loadFromFile(std::string filename);
Unfortunately, I would have to create a special case for sf::Music because of its openFromFile() function ;)

thor::ResourceManager<Resource> itself doesn't require a second template argument, keys are always thor::ResourceKey<Resource>. Loading looks like this:
thor::ResourceManager<sf::Texture> manager;
manager.acquire( thor::Resources::fromFile<sf::Texture>("image.png") );
The thing I currently don't like is the need to specify sf::Texture again. I could avoid that by complicated return types with implicit conversions, but that's probably not good either :)

What do you think?


Since you're gonna refractor it, I wanted to asked if it was somehow possible to combine the resource manager into one class or provide another class which combines the other ones. It's just kinda of annoying if you have to keep track of three or more diffrent resource managers (one for loading fonts, one for loading textures, one for loading sounds, etc). I don't know how one would do this the best way but maybe you do! ;D
Yes, I've already thought about this in Thor 1, but I haven't found a clean solution so far. However I'll reflect about it again, thanks for the feedback :)
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 08, 2012, 01:00:26 am
The thing I currently don't like is the need to specify sf::Texture again. I could avoid that by complicated return types with implicit conversions, but that's probably not good either :)

What do you think?
I like getting rid of the diffrent resource key classes.
I'm not sure what the resource key class contains, but it basically should only hold the information on how to load the resource, so wouldn't it be possible to just have one resource key class without the template, which holds that information. Since the resource manager know with which class he's dealing with, he only needs to know how to load the data, meaning which function to call on the template class.
The problem with that idea is that maybe someone would try to load a image with the music manager, since the keys no longer hold the type information.

Yes, I've already thought about this in Thor 1, but I haven't found a clean solution so far. However I'll reflect about it again, thanks for the feedback :)
Since you want to remove the type from the keys, removing it from the manager won't really work, except moving it to the manager functions, which would produce not so nice function calls mgr.acquire<sf::Texture>(reskey). Althought if you look at them they're very verbose (Manager acquire a texture with the reskey!)... ???
Title: Re: Thor 2.0
Post by: Nexus on April 08, 2012, 01:15:01 am
Apparently, generic functions like fromFile() are more difficult than thought, as I didn't expect the SFML resource loading functions to have so different signatures :P

I hoped to provide at least the 3 basic functions to load from a file, stream and memory uniformly, however:So I currently tend to go towards the old approach... At the moment I'm experimenting with a class template which is specialized for the single SFML resource classes. Although the difference to independent key classes is not big. I don't know if template is even a good approach, since it suggests a genericity which is not really there...
thor::ResourceKey<sf::Texture> key = thor::Resources::Loader<sf::Texture>::fromFile(...)

On the other side, I don't think non-templated resource keys are a good idea, because you lose type safety. Since load() returns a pointer to the resource, it's better to know the type. I don't like to introduce casts or runtime checks and the corresponding error-proneness because I currently don't see the advantage of type erasure here ;)
Title: Re: Thor 2.0
Post by: Nexus on April 08, 2012, 08:55:48 pm
Okay, I have pushed a first draft of the new resource API. Changes:
Example:
thor::ResourceManager<sf::Texture> mgr;

std::shared_ptr<sf::Texture> ptr =
    mgr.acquire( thor::Resources::fromFile<sf::Texture>("image.png") );
Title: Re: Thor 2.0
Post by: MorleyDev on April 09, 2012, 04:02:04 am
So each Resource has it's own manager? Huh, different to my approach where I centralised it so a single resource manager can load any resource, even user defined.

Basically stores
-map of loaders for each type
-map of type/object pair for each name.

Internally it stores things as std::shared_ptr<void>. The awesome thing about std::shared_ptr<void> is it still calls the correct destructor.

Internally it then uses some form of templated Type-to-Identifier to determine which loader to use and make sure it's casting things back to the right type. This defaults to either RTTI or a really simple fake RTTI.

Externally a function like template<typename Type> std::shared_ptr<Type> getResource<Type>("filename") is exposed to the user.

Ideally this lets me store all resources in a central location, whilst keeping the end result type safe.
Title: Re: Thor 2.0
Post by: Nexus on April 09, 2012, 09:18:32 am
Thank you! I've already thought about a centralized manager, the thing I had in mind was indeed similar to your approach, namely
std::map< TypeInfo, PointerToTypeErasedBaseClass >

The general resource manager would have the same API as the current one, just that the functions taking resource keys would be templates (for arbitrary keys). Maybe I'll still provide the specialized managers for full type information (they would probably be used internally anyway)... Or do you consider them useless?


Internally it stores things as std::shared_ptr<void>. The awesome thing about std::shared_ptr<void> is it still calls the correct destructor. It uses some form of templated Type-to-Identifier to determine which loader to use and make sure it's casting things back to the right type. This defaults to either RTTI or a really simple fake RTTI.
It doesn't use RTTI. It creates a deleter at initialization, where the dynamic type is known. Using type erasure, it can call it later. I've also implemented this technique in Aurora's CopiedPtr.
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 09, 2012, 10:33:18 am
The general resource manager would have the same API as the current one, just that the functions taking resource keys would be templates (for arbitrary keys). Maybe I'll still provide the specialized managers for full type information (they would probably be used internally anyway)... Or do you consider them useless?

I'd still vote for uniform manager too, because what I now do is packing three managers into one class, since I don't want to hand around three diffrent references to the manager, I now can rather just hand out the reference to this one resource class.

If the overhead of the uniform manager is quite bigger than that of a type specific manager, it would be good to provide the older ones too, otherwise it's kind of unnessesary.
Title: Re: Thor 2.0
Post by: MorleyDev on April 09, 2012, 08:10:43 pm
Quote
It doesn't use RTTI. It creates a deleter at initialization, where the dynamic type is known. Using type erasure, it can call it later. I've also implemented this technique in Aurora's CopiedPtr.

Sorry I meant my Resource Manager uses RTTI or fake RTTI internally, not shared_ptr does xD Shoulda been more clear about that, my bad. I always try and provide a way around using built-in C++ RTTI simply because I know people don't like it due to the overhead.

A simplistic fake rtti can reduce the overhead from 40-bytes per class to 1-byte per class that is checked. Don't use it, no overhead. Though it doesn't have the benefits of being able to tell the super class of a reference...You may even be able to take that overhead out if with some template specialisation tricks.
Title: Re: Thor 2.0
Post by: Haikarainen on April 09, 2012, 10:58:38 pm
Nevermind, apparently nullptr is a new 0x feat wich GCC 4.4.1 doesnt support. It's a problem to me since that's the version that the "Codeblocks MinGW-bundle" comes with, and any other version of mingwgcc isnt supported by codeblocks.

So it's codeblocks or thor :/ there should be some kind of workaround. GCC 4.6.x and higher supports nullptr.

Just reformatted my computer, so I needed to recompile all libs etc. Having some trouble compiling Thor.

Compiler log:


Code: [Select]
||=== thor, all ===|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\Detail\PtrOwner.hpp||In member function 'virtual void aur::detail::PtrOwner<T, U, C, D>::dismiss()':|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\Detail\PtrOwner.hpp|85|error: 'nullptr' was not declared in this scope|
<ThorPath>\extlibs\aurora\include\Aurora\Tools\SafeBool.hpp|64|error: 'nullptr' was not declared in this scope|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp||In constructor 'aur::CopiedPtr<T>::CopiedPtr()':|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp|62|error: 'nullptr' was not declared in this scope|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp|93|error: 'nullptr' was not declared in this scope|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp||In constructor 'aur::CopiedPtr<T>::CopiedPtr(aur::CopiedPtr<U>&&)':|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp|116|error: 'nullptr' was not declared in this scope|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp||In member function 'aur::CopiedPtr<T>::operator void (aur::detail::SafeBoolHolder::*)()() const':|
<ThorPath>\extlibs\aurora\include\Aurora\SmartPtr\CopiedPtr.hpp|185|error: 'nullptr' was not declared in this scope|
||=== Build finished: 6 errors, 0 warnings ===|


I understand the compilers whine, the code:

Code: [Select]
virtual void dismiss()
{
pointer = nullptr;
}

nullptr is never defined. Should I define it as NULL somewhere?


Title: Re: Thor 2.0
Post by: Nexus on April 09, 2012, 11:50:15 pm
@MorleyDev: How can you get a unique ID for a class without RTTI? You need to register the types manually or require a special interface, don't you?


@Haikarainen: Yes, it's quite annoying that nullptr requires g++ 4.6. Concerning other features, the g++ developers were very fast, already in 4.3 they had a first version of variadic templates, while the next version of Visual Studio will still not support them. For nullptr they needed long however, although they already have a builtin __null with similar meanings.

Anyway, NULL won't work because it isn't convertible to the smart pointer types. There is a partial workaround:
#include <memory>

struct nullptr_t
{
        template <typename T>
        operator T* () const
        {
                return 0;
        }

        template <typename C, typename T>
        operator T C::* () const
        {
                return 0;
        }

        template <typename T>
        operator std::shared_ptr<T> () const
        {
                return std::shared_ptr<T>();
        }

        template <typename T>
        operator std::unique_ptr<T> () const
        {
                return std::unique_ptr<T>();
        }
};

const nullptr_t nullptr;
However, it doesn't work for other classes taking std::nullptr_t arguments and some special cases. And I actually hoped to use clean C++11 features, I don't like to start writing workarounds again ;)

Are you sure you can't replace your g++ with a newer version?
Title: Re: Thor 2.0
Post by: Haikarainen on April 10, 2012, 12:34:53 am
I could try, tried to run the bundled version of mingw-gcc with a separate standalone one before, but codeblocks sure didn't like it. Wish me luck :D

EDIT: Meant cmake didnt like it, remember now I had to change the pathvar every time i was going to generate makefiles. Successfully compiled, will try to restore that fireparticle effect now ;)
Title: Re: Thor 2.0
Post by: MorleyDev on April 10, 2012, 01:14:48 am
For GCC 4.6, well 4.7 now, you can download it with Mingw for windows at http://nuwen.net/mingw.html

@MorleyDev: How can you get a unique ID for a class without RTTI? You need to register the types manually or require a special interface, don't you?

You can essentially "hash" a type/class like this:

Code: [Select]
template<typename T> std::size_t get_id()
{
static char id;
return reinterpret_cast<std::size_t>(&id);
}

The address of id will be the same for the same values of T, but different for different values of T. It has some problems with dll boundaries, but so does the built in C++ RTTI.

If you wanna cross DLL boundaries, use a functor and provide specialisations with unique ids for each specialisation.
Title: Re: Thor 2.0
Post by: Nexus on April 10, 2012, 04:16:03 am
Thank you both! MorleyDev, that's a really great idea :)
Title: Re: Thor 2.0
Post by: Silvah on April 10, 2012, 01:34:51 pm
It's a problem to me since that's the version that the "Codeblocks MinGW-bundle" comes with, and any other version of mingwgcc isnt supported by codeblocks.
Untrue. Download a newer GCC, extract it, change the paths in Code::Blocks settings, ???, profit.

It has some problems with dll boundaries, but so does the built in C++ RTTI.
The C++ RTTI doesn't. It's 2012 now, most significant compilers fixed it long ago. That is, assuming you don't have multiple copies of runtime library in the program (if you do, though, you should fix that anyway).

You can essentially "hash" a type/class like this:

Code: [Select]
template<typename T> std::size_t get_id()
{
static char id;
return reinterpret_cast<std::size_t>(&id);
}
Wouldn't it be better to use void* instead of size_t? You don't care about the value, it's just a magic cookie, so void* will work fine, and you avoid an implementation-defined cast.
Title: Re: Thor 2.0
Post by: MorleyDev on April 10, 2012, 04:27:22 pm
I was under the impression that with Windows DLLs it's still an issue, in that the comparisons can only reliably be done on the name and not the address of what is returned by typeid(X). I'd consider this a problem, especially if you're using it somewhere that performance matters. If I'm wrong that's great, now they just need to find a way to propagate exceptions across DLLs...

Either way, the purpose of avoiding RTTI tends to be how RTTI still adds ~40bytes of overhead per virtual destructor. As opposed to this, which only adds 1byte of overhead to the static memory per class actually checked. Especially on an embedded system that could really make a difference. And then some programmers just switch it off and refuse to work with it, so whilst you could just say "well screw them then", ideally would want to be able to do something in that situation if you're making a library.

Sure, you could use void*. You could use char*. It's just that makes it clear you're dealing with a pointer, not some magic number. Usually if you return a pointer, then in my opinion it should be expected to do some pointer things to that pointer. Here you aren't and never would need to, unless you were stretching for single bytes to use in the worst possible way in which case the drawing board is over there, go back to it.

The Windows API hides this via a typedef (such as HANDLE), I hide it inside an integer. It's not a problem on any compiler I know of, as one of the requirements of std::size_t is that it is large enough to hold the value of a pointer and casting a pointer to an integer is one of the main uses of reinterpret_cast.
Title: Re: Thor 2.0
Post by: Silvah on April 11, 2012, 08:57:58 pm
I was under the impression that with Windows DLLs it's still an issue, in that the comparisons can only reliably be done on the name and not the address of what is returned by typeid(X). I'd consider this a problem, especially if you're using it somewhere that performance matters.
That's exactly how they implement it, but it's not a problem at all. Performance doesn't matter unless you can prove it does. And if a program spends significant amount of time doing RTTI, it's very likely that the performance is the least concern, because the first thing code should get then is some serious refactoring, not a microoptimization.

they just need to find a way to propagate exceptions across DLLs...
Again, we're not in the nineties anymore. Exceptions fly across DLLs just fine (but see the caveat in my previous post).

Especially on an embedded system that could really make a difference.
On an embedded system, you probably wouldn't use RTTI at all, because there you wouldn't run into a problem that requires (as opposed to "allows, but there are alternatives that work as well") the use RTTI.
Oh, and on some embedded systems, one byte per class is still quite a lot of memory ;)

Usually if you return a pointer, then in my opinion it should be expected to do some pointer things to that pointer.

[...]
The Windows API hides this via a typedef (such as HANDLE)
Handles happen to be represented as pointers, so... how many times did you try to make something pointerish with a handle?

It's not a problem on any compiler I know of, as one of the requirements of std::size_t is that it is large enough to hold the value of a pointer
No, that's a requirement of std::(u)intptr_t. std::size_t is required only to be able to store the size of any object. Because of that, on some systems, mainly those with segmented memory, size_t can be much smaller than a pointer.

And yes, such systems still exist. They're rare nowadays, but they can be found sometimes somewhere in the embedded world nonetheless. Remember that it's you who started talking about embedded platforms ;)

casting a pointer to an integer is one of the main uses of reinterpret_cast.
Yes, but this doesn't invalidate the fact that it's still left implementation-defined by the standard.
Title: Re: Thor 2.0
Post by: MorleyDev on April 11, 2012, 09:49:19 pm
Well it's not 1-byte per class, it's one byte per class which has the get_info function used on it. Still not ideal.

Ah, my bad about the std::size_t. In the actual implementation I use I specifically define a set of integrals such as int32, int64, and I have one defined which is guaranteed to be at least the same size as a void*.

Basically I did a bunch of template specialisations for each possible size and it's all checked by static_asserts at compile-time so if you did try and use it on a system that has issue with it, it'll just not compile. But then that can be overriden by a define and providing the correct specialisations and...I'll never win one of those "small program" challenges since I do way too much template metaprogramming xD

My point about HANDLE was it does hide the fact that it's a void pointer from the user. How many times do you think people even notice it's void*? I could of done typedef void* typekey. I mostly went with std::size_t to demonstrate the concept and because here it works fine and gets across the "not a void*, not to be treated as a void*" concept.

I used reinterpret_cast because it's a copy bit-for-bit into an integer. That's when you use reinterpret_cast.

My actual implementation does some things to hide this inside a class, and has macros and functions to let you completely ignore whether you're using the built in RTTI or this system...again, never gonna win a smallest program contest.

As for string comparisons, I'm of the opinion that if you can avoid string comparisons, avoid them as a matter of design. Especially since a map is going to be a common place to store a typeinfo which means a lot of string comparisons. Heck, my wrapper for standard C++ works by hashing the name first, and comparing that to reduce the number of string comparisons greatly.

Anyhoo, getting waaaaaaaaaay off-topic xD
Title: Re: Thor 2.0
Post by: Nexus on April 12, 2012, 11:08:18 am
Meanwhile, I have thought about an implementation of a combined resource manager, and it probably won't be a big problem. The old managers are further used in the implementation, and maybe I'll provide them also in the API.

By the way, does the name "ResourceManager" please you? It is somehow unprecise, I also thought about "ResourceCache". In case I provide the specific managers, the general one might be called "MultiResourceCache", although this sounds strange... Do you have other ideas? :)
Title: Re: Thor 2.0
Post by: Lo-X on April 12, 2012, 12:39:33 pm
I've seen a lot of people saying that a class with "Manager" in its name is bad designed.

IMO, that's not always linked and in the case of a RessourceManager it mean exactly what it mean and everybody knows what it is exactly.

If my voice can count, I prefer the "RessourceManager" name.
Title: Re: Thor 2.0
Post by: Laurent on April 12, 2012, 12:54:56 pm
Some minor thoughts:

- "Provider" would be a slightly more precise name than "Manager"

- If you provide an all-in-one manager, you must still provide the individual ones in the public API, for people who split audio and graphics into independant modules

- Don't bother with sf::Music and its openFromFile function, it's not a candidate for being managed by your class. It would be wrong to share sf::Music instances, you need a new instance everytime you want to play a music. And nothing's pre-loaded anyway, audio data is streamed, so there's no point keeping unused musics.
Title: Re: Thor 2.0
Post by: Silvah on April 12, 2012, 09:02:45 pm
I used reinterpret_cast because it's a copy bit-for-bit into an integer. That's when you use reinterpret_cast.
I assure you I understand why you're using reinterpret_cast. Still, the standard defines the mapping performed by this operator to be implementation-defined. You can't change it. I can't change it. Even the committee would be very loath to change it, as it would take some freedom  from the implementors. What if that freedom makes the code faster on some platform? What if taking it away would make it impossible to implement that operator in a meaningful way?

Heck, my wrapper for standard C++ works by hashing the name first, and comparing that to reduce the number of string comparisons greatly.
Did you check it's actually worthwhile to do that? You know, typically comparing the names is just a fallback, if the pointers are the same there's no string comparison involved. Thus you could be in fact pessimizing the type_info comparison.
Title: Re: Thor 2.0
Post by: Lo-X on April 12, 2012, 10:29:14 pm
- Don't bother with sf::Music and its openFromFile function, it's not a candidate for being managed by your class. It would be wrong to share sf::Music instances, you need a new instance everytime you want to play a music. And nothing's pre-loaded anyway, audio data is streamed, so there's no point keeping unused musics.

Interesting part, I just have to think about how to handle music now  ::)
Title: Re: Thor 2.0
Post by: Nexus on April 13, 2012, 05:21:06 pm
Thank you a lot for all the feedback! :)

IMO, that's not always linked and in the case of a RessourceManager it mean exactly what it mean and everybody knows what it is exactly.
Yes, "resource manager" is a spread term, nevertheless one could describe the mechanics more clearly. For example, thor::ResourceManager doesn't own the resources (the smart pointers do), it just provides an interface to acquire resources without the need to check if it has already been acquired. That's also why I like the name ResourceCache.

Are there further ideas about how to name the all-in-one manager? Is "multi" an acceptable prefix? The alternative would also be to name the generic one only "ResourceCache" and find another identifier for the specific ones.


- "Provider" would be a slightly more precise name than "Manager"
That's also an option, thanks. It doesn't express the cache semantics either, but maybe that's obvious anyway...


- If you provide an all-in-one manager, you must still provide the individual ones in the public API, for people who split audio and graphics into independant modules
I'm not sure if I've understood that correctly. The all-in-one manager won't be a merge of the single SFML resource managers (like thor::ResourceManager<sf::Texture>), but rather a frontend to interact with multiple resource types of any kind. For example, if one loads the first time a sf::Texture, a corresponding resource manager is created internally, to which the acquire() call is forwarded.

That is, one can actually do everything with the all-in-one manager that is possible with the single specializations, only that the API isn't constrained to one type.


- Don't bother with sf::Music and its openFromFile function, it's not a candidate for being managed by your class. It would be wrong to share sf::Music instances, you need a new instance everytime you want to play a music. And nothing's pre-loaded anyway, audio data is streamed, so there's no point keeping unused musics.
That's true, I remember this statement some time ago. The only reason to manage sf::Music instances would be the uniformity with other resources (for example, the same exception is thrown at loading failure). But it's probably not worth to unify sf::Music at all costs, in this respect it's a nice feature that thor::ResourceManager<sf::Music> won't compile ;)

And are there particular practices to consider at sf::Shader? I have to admit I'm not familiar with shader use cases...
Title: Re: Thor 2.0
Post by: Laurent on April 13, 2012, 05:29:14 pm
Quote
And are there particular practices to consider at sf::Shader? I have to admit I'm not familiar with shader use cases...
Hmm no, as long as you forward all the available loadFromXxx functions, everything should be ok.
Title: Re: Thor 2.0
Post by: Hiura on April 14, 2012, 09:49:52 pm
I wish I had time to play with this lib! Looks really cool!

One remark though : you should use spaces instead of tabulation 'cause it looks ugly on github.  ;)
Title: Re: Thor 2.0
Post by: kkiikki on April 15, 2012, 05:34:53 am
Okay, so for the past three days now I've been trying to build Thor 1.1 and just can't get it to work. Whenever I click configure the "SFML_INCLUDE_DIR" option gives me an error. I've set that option to C:\SFML\SFML2\include (that where its stored on my computer) and it always just says its not found . :-\

So could ya help tell me what mistakes I'm making? Also I am using SFML 2.0 and followed this tutorial
 http://sfmlcoder.wordpress.com/2011/06/15/building-sfml-2-nmake/ (http://sfmlcoder.wordpress.com/2011/06/15/building-sfml-2-nmake/)
 Sorry for being incompetent  :'(
Title: Re: Thor 2.0
Post by: Astrof on April 15, 2012, 07:33:57 am
Make sure to copy the FindSFML.cmake file to the cmake modules folder (search earlier in this thread for more details on this). 
Title: Re: Thor 2.0
Post by: Nexus on April 15, 2012, 11:35:21 am
I wish I had time to play with this lib! Looks really cool!
Thank you :)
I know the problem, there are so many interesting projects out there... I hope I'm able to experiment with them one day ;)

One remark though : you should use spaces instead of tabulation 'cause it looks ugly on github.  ;)
No, I don't like spaces. It is sad enough I often do ugly things in my code to create a clean Doxygen output, I won't do the same with GitHub. It should rather provide an option to set the tab width :P

Okay, so for the past three days now I've been trying to build Thor 1.1 and just can't get it to work.
What generator do you use? For Visual Studio 2010 and g++ there are precompiled libraries, so there's no need to build.

In case you want to use the newest SFML, you should rather checkout the Thor 2.0 development version. For Thor 1.1, you must use the SFML revision provided with Thor.
Title: Re: Thor 2.0
Post by: kkiikki on April 15, 2012, 07:09:29 pm
Quote
Make sure to copy the FindSFML.cmake file to the cmake modules folder (search earlier in this thread for more details on this).
I found the post thanks.


Quote
What generator do you use? For Visual Studio 2010 and g++ there are precompiled libraries, so there's no need to build.

In case you want to use the newest SFML, you should rather checkout the Thor 2.0 development version. For Thor 1.1, you must use the SFML revision provided with Thor.

and I do use Visual Studio so yeah, guess I'll be getting Thor 2.0 instead.

Thanks for your help  :D
Title: Re: Thor 2.0
Post by: MorleyDev on April 16, 2012, 09:53:00 pm
Don't most IDEs have an option to treat n spaces as a tab when editing but stored as n spaces when saving?
Title: Re: Thor 2.0
Post by: guiguizmo91 on April 26, 2012, 09:24:37 pm
Hi ! :)

First of all, this library is really interesting.

Now for the noob question... I followed the tutorial about how to install Thor, I'm based on the last version of SFML (from Github), same for Thor. Everything went fine, it's just that I can't figure how to link the Thor library... I tried to compile by myself one of the examples:
Code: [Select]
g++ Action.cpp -o Action -std=c++0x -<thor> -lsfml-window -lsfml-system
So, my question is, what am I supposed to type to link correctly thor? I'm running an up to date xubuntu.

Thanks.

EDIT: Okay, it was -lthor, makes sense. :)

I tried to compile on Windows Seven, but even though I have set SFML with the path of my fresh SFML install (also made with Cmake), Cmake cannot locate the SFML to generate Thor makefiles. :/ Any idea ?
Title: Re: Thor 2.0
Post by: Nexus on April 27, 2012, 07:49:41 pm
So, my question is, what am I supposed to type to link correctly thor?
It is explained in the tutorial. I know the one for version 1.1 is slightly outdated, but most parts have remained the same. I'll write one for 2.0 as soon as possible.

I tried to compile on Windows Seven, but even though I have set SFML with the path of my fresh SFML install (also made with Cmake), Cmake cannot locate the SFML to generate Thor makefiles. :/ Any idea ?
First, update to the newest SFML and Thor revisions, I have just changed some CMake code. If SFML isn't found, an error will appear (which should describe what to do, unless its one of the confusing error messages of CMake itself).

In short, define SFML_ROOT to the directory of SFML (containing "include", "lib", "examples" etc.).
Title: Re: Thor 2.0
Post by: guiguizmo91 on April 30, 2012, 09:01:32 pm
Thanks, it worked like a charm.

About the Windows part, everytime I quit the examples, I get the "Example.exe has stopped functionning." message. I don't really care as I am just toying around for now, but I like things clean.

Any idea why I get the message ?
Title: Re: Thor 2.0
Post by: eXpl0it3r on May 04, 2012, 01:27:07 am
It seems you're kinda busy but I still want to point out:

Quote
Meanwhile, I have thought about an implementation of a combined resource manager, and it probably won't be a big problem. The old managers are further used in the implementation, and maybe I'll provide them also in the API.
Is this coming any time soon? :D

Also an updated version of the resource tutorial could've been usefull but I got it in the end. ;D
Title: Re: Thor 2.0
Post by: Nexus on May 04, 2012, 05:35:07 pm
Hey, I've already written the combined resource manager implementation, but haven't had much time to test it yet. But even before I read your post, I had planned to push it today... I hope I can keep this promise ;)
Title: Re: Thor 2.0
Post by: eXpl0it3r on May 04, 2012, 05:44:56 pm
Hey, I've already written the combined resource manager implementation, but haven't had much time to test it yet. But even before I read your post, I had planned to push it today... I hope I can keep this promise ;)

Looking forward to it!
Although it means I'll 'have to' refractor my application. ::)
Title: Re: Thor 2.0
Post by: fallahn on May 05, 2012, 11:26:14 am
Hey there!
I downloaded Thor yesterday and have been playing with it for a while, it's a great lib :) One thing that struck me though was that I felt it was a bit inflexible to render particle systems to a RenderWindow only, so I changed
Code: [Select]
ParticleSystem::draw(sf::RenderWindow& renderWindow) to
Code: [Select]
ParticleSystem::draw(sf::RenderTarget& renderTarget, sf::RenderStates& renderStates)This way I can render a particle system to a RenderTexture as well as a RenderWindow, change the BlendMode and use shaders for post FX during off screen rendering. Sorry if I've missed something and there's already a better way to do this, but I've only been using Thor for a few hours. I will definitely being using this lib a lot :D
Title: Re: Thor 2.0
Post by: Nexus on May 05, 2012, 12:09:26 pm
Yesterday, I pushed the new thor::MultiResourceCache class. Meanwhile, the tutorial for Thor.Resources has been updated, too.

Quote from: exploit0r
Although it means I'll 'have to' refractor my application. ::)
You only have to change thor::ResourceCache<X> to thor::MultiResourceCache, the interface is exactly the same ;)

Quote from: fallahn
IOne thing that struck me though was that I felt it was a bit inflexible to render particle systems to a RenderWindow only
Hehe, I have planned to derive the thor::ParticleSystem from sf::Drawable, too. At the beginning of Thor, I didn't like this approach, because sf::Drawable contained many methods like GetPosition() that were useless for particles, but now the situation has changed.

By the way, am I supposed to just ignore the sf::RenderStates::texture attribute and to override it with the specified particle texture?
Title: Re: Thor 2.0
Post by: Laurent on May 05, 2012, 01:01:25 pm
Quote
By the way, am I supposed to just ignore the sf::RenderStates::texture attribute and to override it with the specified particle texture?
Yes :)
Title: Re: Thor 2.0
Post by: fallahn on May 05, 2012, 05:51:00 pm
I was just wondering - is it possible to tie emitters to particles? For example if I wanted to explode a vehicle could I use a particle system to emit 4 or 5 particles as 'chunks' of the vehicle, then have each of those particles emit their own smoke and flame? Perhaps this is a reason to use GetPosition() on particles? :) I really like the idea of Distributions by the way, I've created some really good looking (if I say so myself ;) ) smoke effects this afternoon
Title: Re: Thor 2.0
Post by: Nexus on May 05, 2012, 06:45:46 pm
Recursion is currently not possible. You could add 4 or 5 emitters, which emit a single chunk once at beginning, and smoke/fire over time. I'm also planning an option for user-specific data per particle, that should help in many situations. I'm considering aurora::CopiedPtr<void> for this.

Good to hear that you like the distribution concept! How did you use the distributions, did you define own ones?


There is now a progress list  (http://www.bromeon.ch/libraries/thor/progress.html) on my homepage that shows the features that are planned for version 2.0 and 2.1. It is not definitive, but you should be able to get a rough overview about what's planned :)
Title: Re: Thor 2.0
Post by: fallahn on May 05, 2012, 09:20:43 pm
OK, I shall have a think about how I might do it. I didn't define any of my own distributions (yet) but I like the concept - it's a great way to quickly and easily add variations to a particle system. It definitely beats any of my personal solutions which would involve things like
#define RANDOM_SPREAD rand() % screenWidth, rand() % screenHeight
(ok not a great example but you see what I mean) which I'd normally come up with - I'm a C programmer really, mainly doing embedded software and I'm using SFML to write *fun* things and learn C++ :)  It's a very elegant solution.
Title: Re: Thor 2.0
Post by: fallahn on May 08, 2012, 05:06:04 pm
I've been thinking about passing RenderStates via the draw method, and I thought maybe it would be better to pass a pointer to a RenderStates object at construction of a particle system (like you currently do with a texture). That way you can set the texture/blendmode/shader once for the whole particle system, and don't have to worry about overriding the texture when drawing. For instance I use BlendAdd for fire particles, BlendMultiply for a smoke particle system and I could also create a system with a glow shader for making lasers and things. Just an idea.

I'm going to try deriving my own affector tonight too... I had an idea for one which scales particles based on their velocity so slower particles look smaller and therefore further away - a kind of fake 'depth' effect.  We'll see how it goes :)
Title: Re: Thor 2.0
Post by: Nexus on May 08, 2012, 05:53:24 pm
OK, I shall have a think about how I might do it. I didn't define any of my own distributions (yet) but I like the concept - it's a great way to quickly and easily add variations to a particle system.
True, it gets especially interesting in combination with lambda expressions:
emitter->setParticleRotation( [] () { return anyValue; } );

I've been thinking about passing RenderStates via the draw method, and I thought maybe it would be better to pass a pointer to a RenderStates object at construction of a particle system (like you currently do with a texture). That way you can set the texture/blendmode/shader once for the whole particle system
That's not a bad idea, however the current draw() method has the advantage that I can keep the sf::Drawable inheritance and therefore integrate thor::ParticleSystem better with SFML. I don't know however how users want to use the particle system, but probably rather the way you describe.

and don't have to worry about overriding the texture when drawing.
The texture specified with sf::RenderStates is ignored. By the way, that might also be a small indicator that there is a better approach. Also the sf::RenderStates::transform attribute is questionable, since my particle system doesn't represent a 2D entity.

What's the usual idiom to create own drawable objects with custom shader or blendmode? I thought sf::Drawable was made for exactly this stuff, but now I'm confused :-\
Title: Re: Thor 2.0
Post by: Fugan on May 08, 2012, 06:17:41 pm
As an extension of the event system and custom actions, what about creating a simple console? I envision something that you can bring up on screen and type commands. The console class would parse the input, then go to a data structure that contains all the commands. Commands would basically be a function pointer with a string for the command name.

You implement your own custom commands, then push command objects onto the console. I think it would be really useful for people to be able to quickly add a command console to their game, rather than using key code combinations or other stuff when testing. It would also promote better software design, since people wont be tempted to "hack" something into their code to test some aspect of their game, since they can write a console command class instead.
Title: Re: Thor 2.0
Post by: Laurent on May 08, 2012, 06:45:56 pm
Quote
What's the usual idiom to create own drawable objects with custom shader or blendmode? I thought sf::Drawable was made for exactly this stuff, but now I'm confused
States that make sense at the object level are usually set in its public API, stored as members and used in draw(), overwriting the user supplied states.
Other states are just passed to the RenderTarget::draw function and produce the expected result.

So, if it makes sense for a particle system to define a blend mode, just add setBlendMode/getBlendMode in the corresponding class and use that in your draw().

To me, the only thing that is not clear is how states should be applied when both the object and the user provide explicit values for them. The transform is combined, which seems like a intuitive behaviour, but for blend mode, texture and shader, maybe it would be more intuitive the other way round, ie. if the user supplied states override the object states? Note that it would be more complicated to apply (how to know if a state is a default value, or has explicitely been set by the user?).

If you have other ideas, I'd be glad to discuss them, but don't forget that any design modification won't happen before SFML 3 :)
Title: Re: Thor 2.0
Post by: Nexus on May 08, 2012, 08:17:55 pm
As an extension of the event system and custom actions, what about creating a simple console?
"Extension" is an understatement, a console is a full-fledged interactive GUI element ;)

It is an interesting feature, but as a GUI element, it is quite specific: I need to define a graphical layout (colors, font, metrics), the user's events must be caught, and a tiny parser interprets the input. I find it too complex for Thor at the moment, but maybe I'll think about it again in the future. Thanks for the suggestion!

Otherwise, what do you think about the Events module? Have you already looked at the generic thor::EventSystem, do you consider it useful? It works similar as a restricted Boost.Signals, in case you know this library.


So, if it makes sense for a particle system to define a blend mode, just add setBlendMode/getBlendMode in the corresponding class and use that in your draw().
I haven't questioned the current SFML approach yet, but it looks like I'll have enough time until SFML 3 ;)

How the sf::RenderStates attributes behave in my concrete use case:
It looks like single attributes might be more convenient, but I'm sure that if I change this, tomorrow there's another user requesting an SFML-compatible interface taking sf::RenderStates :P
Title: Re: Thor 2.0
Post by: Laurent on May 08, 2012, 08:27:42 pm
Quote
transform: Not very meaningful, because the system itself is no transformable entity.
Does this mean that I can't attach a smoke particle system to a car, for example? Or is it handled differently (ie. you can transform the emitter)?

Quote
shader/custom blend modes: No idea, I haven't used them a lot yet. But fallahn's point sounds right: One probably wants the particles to be drawn with the same shader/blend mode again and again.
I don't think that shaders are a specific attribute of particle systems, but blend mode would totally make sense. It's quite common to use a multiply or add blend mode with particles.

Quote
It looks like single attributes might be more convenient, but I'm sure that if I change this, tomorrow there's another user requesting an SFML-compatible interface taking sf::RenderStates
For shaders, probably. But the blending mode is really a property of the particle system: I can't see any use case where it would have to be chosen at draw time.
Title: Re: Thor 2.0
Post by: Nexus on May 12, 2012, 11:21:06 am
Does this mean that I can't attach a smoke particle system to a car, for example? Or is it handled differently (ie. you can transform the emitter)?
Yes, I intended the emitter to be a transformable entity. Like this, e.g. a plane can have a single particle system (one smoke texture), but two emitters with different positions and smoke emission directions.

However, the emitters currently don't have a draw() method, the whole transformations are purely logic-based. That is, particles have a global position etc. Physics (like repelling particles) and general interactions with the environment should be easier to handle this way.

But I know, there should be a possibility to attach an emitter to an object. I've even thought about a scene graph, but there are currently too many questions open. The current approach is:
auto emitter = thor::UniversalEmitter::create();
emitter->setParticlePosition( [&] () { return object.getPosition(); } );
emitter->setParticleVelocity( [&] () { return -object.getVelocity(); } ); // towards rear

Something that would be nice were:
auto emitter = thor::SceneEmitter::create(object); // Take object as parent
But I think only position, rotation and scale would be taken from the parent object. Although it might be handy to adapt also velocity, I think it's difficult to allow this in a general way...

Originally I've even planned to use sf::Transform, but since it is expensive and ambiguous to extract the single transform components, I've left the direct position/rotation/scale.

Any ideas concerning this are very welcome :)


For shaders, probably. But the blending mode is really a property of the particle system: I can't see any use case where it would have to be chosen at draw time.
Ok, so you suggest to provide corresponding get/set methods and ignore the sf::RenderStates::blendMode attribute in ParticleSystem::draw()?
Title: Re: Thor 2.0
Post by: Laurent on May 12, 2012, 12:25:32 pm
Quote
But I know, there should be a possibility to attach an emitter to an object.
When I say "attach to an object" I simply mean "have a way to set the same transform as the object". Really attaching to an object is another subject, and yes it's probably not easy to design without a scenegraph-based world.

Quote
Ok, so you suggest to provide corresponding get/set methods and ignore the sf::RenderStates::blendMode attribute in ParticleSystem::draw()?
Yes.
Title: Re: Thor 2.0
Post by: Nexus on May 19, 2012, 08:30:12 pm
Another big step is taken: The fundament of the new Animation API. I have reflected quite a long time on how to make everything more flexible without adding unnecessary complexity. I've come to the conclusion to diverge from the shared-ownership and inheritance approach, towards generic functors.

The core part is still thor::Animator, it has become a class template.
template <class Animated, typename Id>
class Animator;
The class thor::Animation was removed, there is no inheritance hierarchy anymore. The concrete animation class thor::FrameAnimation is now a functor with a templated operator(). The template parameter Animated can be any class supporting setTextureRect(). Mostly, this will be sf::Sprite.
template <class Animated>
void operator() (Animated& animated, float progress) const;

In fact, everything that can be called with an object reference and a float is now an animation. This includes normal functions and lambda expressions. For instance, it requires a single line to define an animation reverse that plays another animation anim backwards:
auto reverse = [anim] (sf::Sprite& s, float pr) { return anim(s, 1.f - pr); };
(Imagine the amount of code for the same functionality with a traditional java-style class hierarchy)

Code that has looked like this:
thor::FrameAnimation::Ptr explosion = thor::FrameAnimation::create();
explosion.addFrame(1.f, sf::IntRect(...));
explosion.addFrame(1.5f, sf::IntRect(...));

thor::Animator animator;
animator.addAnimation("expl", explosion, sf::seconds(3));
now looks like this:
thor::FrameAnimation explosion;
explosion.addFrame(1.f, sf::IntRect(...));
explosion.addFrame(1.5f, sf::IntRect(...));

thor::Animator<sf::Sprite, std::string> animator;
animator.addAnimation("expl", explosion, sf::seconds(3));
The module is currently quite small, I have planned to add more animations (such as color gradients) as well as operational primitives (reverse, concatenate). However I'm not sure how much of this will be done before 2.0.
Title: Re: Thor 2.0
Post by: Klaim on May 23, 2012, 04:33:10 pm
Hi I just wanted to point this discussion where I suggested an additional library to SFML and Laurent thinks (and I agree) that it would be a good addition to Thor : http://en.sfml-dev.org/forums/index.php?topic=8010


By the way, do you plan to change the website soon? The textures and colors are really agressive for my eyes...
Title: Re: Thor 2.0
Post by: mateandmetal on May 25, 2012, 02:43:40 pm
Hi... I'm getting some errors trying to compile Thor with CMake-gui and MinGW

It can´t find SFML. I specified the path manually and works.

It compiles the entire library, but in the animation example:

e:/Programacion/Thor2.0/include/Thor/Animation/Detail/Animation.inl: 52:2
need ´typename´before ´thor::Animator<Animated, Id>::AnimationMap::iterator´ because ´thor::Animator<Animated, Id>::AnimationMap´is a dependent scope

52:25 expected ´;´ before ´itr´
55:16 ´itr´was not declared in this scope
...

using latest SFML2 and Thor2 snapshots dowloaded today from github

and, a weird thing...  the libthor.dll and libthor.dll.a files are created in the Thor2.0/src directory.. shouldnt be in a /lib dir?


(sorry for the bad english)  :o
Title: Re: Thor 2.0
Post by: Nexus on May 25, 2012, 08:24:20 pm
Thanks. I hate it, VS 2011 Beta still doesn't recognize these typename errors. Unfortunately, I cannot compile with g++ at the moment, so I hope it works now...

Concerning the "lib" folder, you have to install Thor (make install).
Title: Re: Thor 2.0
Post by: mateandmetal on May 26, 2012, 07:52:17 am
Concerning the "lib" folder, you have to install Thor (make install).

Thanks!
Title: Re: Thor 2.0
Post by: mguerriero on June 09, 2012, 07:31:49 pm
Hi Nexus, this is my first post here and I'd like to know a thing about Thor and SFML.

I installed SFML 2.0 and the latest Thor from git. The installation of the two libs went well but when I try to compile some files using Thor I get the following errors
In file included from /usr/local/include/Thor/Animation.hpp:32:0,
                 from /home/mario/revenge/revenge-test/src/Character.cpp:1:
/usr/local/include/Thor/Animation/Animator.hpp:59:11: error: ‘function’ in namespace ‘std’ does not name a type
/usr/local/include/Thor/Animation/Animator.hpp:73:46: error: ‘AnimationFunction’ does not name a type
/usr/local/include/Thor/Animation/Animator.hpp:99:39: error: ‘AnimationFunction’ does not name a type
/usr/local/include/Thor/Animation/Animator.hpp:105:21: error: ‘AnimationFunction’ was not declared in this scope
/usr/local/include/Thor/Animation/Animator.hpp:105:48: error: template argument 1 is invalid
In file included from /usr/local/include/Thor/Animation/Animator.hpp:129:0,
                 from /usr/local/include/Thor/Animation.hpp:32,
                 from /home/mario/revenge/revenge-test/src/Character.cpp:1:
/usr/local/include/Thor/Animation/Detail/Animator.inl: In constructor ‘thor::Animator<Animated, Id>::Animator()’:
/usr/local/include/Thor/Animation/Detail/Animator.inl:35:21: error: ‘nullptr’ was not declared in this scope
/usr/local/include/Thor/Animation/Detail/Animator.inl: At global scope:
/usr/local/include/Thor/Animation/Detail/Animator.inl:43:63: error: ‘AnimationFunction’ does not name a type
/usr/local/include/Thor/Animation/Detail/Animator.inl: In member function ‘void thor::Animator<Animated, Id>::stopAnimation()’:
/usr/local/include/Thor/Animation/Detail/Animator.inl:62:24: error: request for member ‘first’ in ‘((thor::Animator<Animated, Id>*)this)->thor::Animator<Animated, Id>::mDefaultAnimation’, which is of non-class type ‘thor::Animator<Animated, Id>::ScaledAnimation {aka int}’
/usr/local/include/Thor/Animation/Detail/Animator.inl:65:23: error: ‘nullptr’ was not declared in this scope
/usr/local/include/Thor/Animation/Detail/Animator.inl: In member function ‘void thor::Animator<Animated, Id>::update(sf::Time)’:
/usr/local/include/Thor/Animation/Detail/Animator.inl:76:51: error: request for member ‘second’ in ‘((thor::Animator<Animated, Id>*)this)->thor::Animator<Animated, Id>::mPlayingAnimation->’, which is of non-class type ‘const ScaledAnimation {aka const int}’
/usr/local/include/Thor/Animation/Detail/Animator.inl: In member function ‘void thor::Animator<Animated, Id>::animate(Animated&) const’:
/usr/local/include/Thor/Animation/Detail/Animator.inl:93:22: error: request for member ‘first’ in ‘((const thor::Animator<Animated, Id>*)this)->thor::Animator<Animated, Id>::mPlayingAnimation->’, which is of non-class type ‘const ScaledAnimation {aka const int}’
/usr/local/include/Thor/Animation/Detail/Animator.inl: At global scope:
/usr/local/include/Thor/Animation/Detail/Animator.inl:105:56: error: ‘AnimationFunction’ does not name a type
/usr/local/include/Thor/Animation/Detail/Animator.inl: In member function ‘void thor::Animator<Animated, Id>::setDefaultAnimation(const int&, sf::Time)’:
/usr/local/include/Thor/Animation/Detail/Animator.inl:109:23: error: ‘nullptr’ was not declared in this scope
/usr/local/include/Thor/Animation/Detail/Animator.inl:112:20: error: request for member ‘first’ in ‘((thor::Animator<Animated, Id>*)this)->thor::Animator<Animated, Id>::mDefaultAnimation’, which is of non-class type ‘thor::Animator<Animated, Id>::ScaledAnimation {aka int}’
/usr/local/include/Thor/Animation/Detail/Animator.inl:113:20: error: request for member ‘second’ in ‘((thor::Animator<Animated, Id>*)this)->thor::Animator<Animated, Id>::mDefaultAnimation’, which is of non-class type ‘thor::Animator<Animated, Id>::ScaledAnimation {aka int}’
I am on Ubuntu 12.04 and I use gcc 4.6.3 to compile. Can you help me solve this problem?
Title: Re: Thor 2.0
Post by: MorleyDev on June 09, 2012, 07:53:39 pm
You need to compile with the flag -std=c++0x to enable the new C++11 features Thor uses, such as nullptr.
Title: Re: Thor 2.0
Post by: mguerriero on June 10, 2012, 08:54:14 am
ok thanks, I forgot to add C++11 flag
Title: Re: Thor 2.0
Post by: Nexus on June 10, 2012, 11:32:08 am
I implemented a modifiaction already requested some time ago: To make triangulations work with arbitrary vertex types. While I originally thought it would require to transform all functions of the algorithm to templates, I later found a way to avoid this. Type erasure is really an uncomparable abstraction mechanism, I use it quite a lot meanwhile.

Concerning the API, this means that there is no more thor::Vertex class, thus you don't have to derive from it for your own vertices. When you have a custom vertex, all you have to do is to specialize the thor::TriangulationTraits template to say Thor how it knows the position of the vertex:
class MyVertex { ... };

namespace thor
{
    template <>
    struct TriangulationTraits<MyVertex>
    {
        static sf::Vector2f getPosition(const MyVertex& vertex);
    }
};

There are still some optimizations possible, and maybe I find a way to reduce the template bloat a little bit.
Title: Re: Thor 2.0
Post by: Tank on June 10, 2012, 05:07:34 pm
To be honest I've never used a single line of code of Thor, but I'm always having a great time reading your code design and especially the refactorings. Keep it up, very interesting (and I think also useful for those using it ;)).
Title: Re: Thor 2.0
Post by: Nexus on June 10, 2012, 05:57:36 pm
Thank you! Good to know that there are interested readers :)
Title: Re: Thor 2.0
Post by: DJuego on June 10, 2012, 06:07:57 pm
He/She is not the only one.  :-X

DJuego

Title: Re: Thor 2.0
Post by: eXpl0it3r on June 11, 2012, 12:19:29 am
He/She is not the only one.  :-X

Tank is defently male. xD


Not sure if you've already see those warnings and they aren't a problem or something, but I'll post them anyways.

VS 2010 @ Debug & Release
2>  ConcaveShape.cpp
2>D:\Programming\Libraries\Thor\src\ConcaveShape.cpp(137): warning C4267: 'return': Konvertierung von 'size_t' nach 'unsigned int', Datenverlust möglich
2>  InputNames.cpp
2>  Shapes.cpp
2>  Triangulation.cpp
2>D:\Programming\Libraries\Thor\src\Triangulation.cpp(188): warning C4267: 'Initialisierung': Konvertierung von 'size_t' nach 'unsigned int', Datenverlust möglich
2>D:\Programming\Libraries\Thor\src\Triangulation.cpp(194): warning C4267: 'Initialisierung': Konvertierung von 'size_t' nach 'unsigned int', Datenverlust möglich
Title: Re: Thor 2.0
Post by: mguerriero on June 11, 2012, 10:27:01 pm
Nexus can you implement the function isAnimating() in Animator? It should return bool and should be used to know if there is an animation in progress or not
Title: Re: Thor 2.0
Post by: Nexus on June 12, 2012, 05:57:34 pm
expl0it3r, I haven't seen them, thanks. I don't like std::size_t because although it is intended to be the size type, it is difficult to use it consistently (see here (http://en.sfml-dev.org/forums/index.php?topic=7303.msg49641#msg49641)). I want to have a uniform API -- that is, no coexistence of unsigned int, unsigned long, std::size_t (unless it should be consistent with SFML, such as in sf::Image::loadFromMemory()). Because it misleads users when different types are used for the same/extremely similar use case.

mguerriero, that's a good idea, thank you.
Title: Re: Thor 2.0
Post by: eXpl0it3r on June 13, 2012, 12:28:29 am
I fully agree. To be honest I didn't even look at the source code, just thought maybe you have overlooked them.
Title: Re: Thor 2.0
Post by: Nexus on June 16, 2012, 08:19:25 pm
Some days ago, I improved the implementation of the type-erasure vertex approach. Nothing changes for the user, however I have drastically reduced the per-vertex overhead (virtual function calls, dynamic allocations, amount of template instantiations).

Furthermore, I added Animator::isPlayingAnimation() to check if an animation is being played. I eliminated some compiler warnings, but with VS and warning level 4, there is this annoying "assignment operator couldn't be generated". I'll probably deactivate it throughout the whole project (and maybe leave a macro for the people who still need this warning).
Title: Re: Thor 2.0
Post by: Laurent on June 16, 2012, 08:26:05 pm
Quote
with VS and warning level 4, there is this annoying "assignment operator couldn't be generated". I'll probably deactivate it throughout the whole project (and maybe leave a macro for the people who still need this warning).
This means that your class is not copyable, so you could just make it explicit (inherit from sf::NonCopyable, or do it directly).
Title: Re: Thor 2.0
Post by: Nexus on June 16, 2012, 08:39:16 pm
This means that your class is not copyable, so you could just make it explicit (inherit from sf::NonCopyable, or do it directly).
Not assignable, to be exact. The warning occurs mainly at places where I use reference members. For example, my aurora::CopiedPtr can handle copyable, non-assignable classes, so making them noncopyable can be a limitation. But yes, in some cases it would work.

Actually, I could just use a pointer instead of a reference, but then I lose expressiveness and safety, since pointers can be changed and initialized with NULL. I don't really like the fact of doing that only for a useless compiler warning telling me what I already know... :P

By the way, I slightly changed the colors of my website, I hope it appears less aggressive now.
Title: Re: Thor 2.0
Post by: Laurent on June 16, 2012, 09:50:37 pm
Quote
I don't really like the fact of doing that only for a useless compiler warning telling me what I already know...
It's not useless, it warns you about something that is supposed to be done automatically but which cannot. Therefore the behaviour may not be what you expect, and an explicit handling of assignment might be required.

The clean solution to this warning is to explicitely write the behaviour that you want: either an assignment of the reference's value (if not rebinding the reference is what you want), changing it to a pointer (if you want to rebind the reference) or disabling the assignment operator (if none is correct).
Title: Re: Thor 2.0
Post by: eXpl0it3r on June 23, 2012, 10:48:14 am
With the newst commit I run into the cmake-error (even with the newest 2.8.8 CMake version):

Since I know you understand German, I post the original German output rather as trying to translate it first.
Quote
12>  CMake Error at cmake_install.cmake:57 (FILE):
12>    file Internal CMake error when trying to open file:
12>    D:/Programming/Libraries/Thor/install_manifest.txt for writing.
12> 
12> 
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: Der Befehl "setlocal
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: "C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" -DBUILD_TYPE=Release -P cmake_install.cmake
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: if %errorlevel% neq 0 goto :cmEnd
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :cmEnd
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: endlocal & call :cmErrorLevel %errorlevel% & goto :cmDone
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :cmErrorLevel
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: exit /b %1
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :cmDone
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: if %errorlevel% neq 0 goto :VCEnd
12>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :VCEnd" wurde mit dem Code 1 beendet.

Also the feature request for the animation class described here  (http://en.sfml-dev.org/forums/index.php?topic=8331.0)sounds interesting.
Title: Re: Thor 2.0
Post by: Nexus on June 23, 2012, 12:44:08 pm
It's not useless, it warns you about something that is supposed to be done automatically but which cannot. Therefore the behaviour may not be what you expect, and an explicit handling of assignment might be required.
There is no unexpected behavior. In case the operator= is used, a compile error occurs.

But yes, it's probably the simplest if I just use pointers, although I don't completely like this approach.


With the newst commit I run into the cmake-error (even with the newest 2.8.8 CMake version)
It doesn't sound like a Thor problem. Are you sure you have the rights to write into the mentioned file? Are there error messages preceding the ones you posted (like compile/link errors)?

I just built Thor with CMake for VS 2010 and installed it without problems... What VS version do you use?
Title: Re: Thor 2.0
Post by: eXpl0it3r on June 23, 2012, 12:53:48 pm
It doesn't sound like a Thor problem. Are you sure you have the rights to write into the mentioned file? Are there error messages preceding the ones you posted (like compile/link errors)?

I just built Thor with CMake for VS 2010 and installed it without problems... What VS version do you use?

Nevermind...
It seems like there were some bad temporary files. Just cloned the repository again and rebuild from scratch without problems. Even the compile/linker errors mentioned previously are now gone.

Thanks a lot for your constant work on this awesome library! ;)
Title: Re: Thor 2.0
Post by: Silvah on June 24, 2012, 04:39:58 pm
I was pretty bored, so I wrote a PKGBUILD for the git version of Thor and uploaded it to AUR (https://aur.archlinux.org/packages.php?ID=60302). Now all Arch Linux users should be able to install the package globally the proper way, with all its files managed by pacman.
Title: Re: Thor 2.0
Post by: Nexus on June 24, 2012, 05:11:11 pm
Wow, thanks a lot! I included the link on the Thor download site.
Title: Re: Thor 2.0
Post by: aNewHobby on June 28, 2012, 11:38:03 am
REQUESTS

I used thor for my last project an thought it was great.. I  pretty much only used the animation class though. Anyway.. from that experience.. I would like to suggest 2 things.

1) aniamtion.getFrameNumber(); ---- It would be cool to be able to test witch frame the animation is on at any give refresh for the window. This could be used for a lot of stuff.. say syncing audio ques for example.

2) When adding a animation you use a std::string as the identity key. Would be great if this could be over loaded to also be able to use simple int. Unless I am misunderstanding things (witch is very possible) it was kind of a pain to build animation assignment code as you couldn't use incrementing loops or anything to call the new animations with out using code to add ints to strings and stuff. While a string name is fine for manually calling .. I think using ints, maybe enums for readability would be a better way to go.

Thanks for all your work on this project.. I'll have to have a closer look at what else is in thor.
Title: Re: Thor 2.0
Post by: Nexus on June 28, 2012, 07:50:26 pm
1) aniamtion.getFrameNumber(); ---- It would be cool to be able to test witch frame the animation is on at any give refresh for the window. This could be used for a lot of stuff.. say syncing audio ques for example.
As already mentioned in the other thread (http://en.sfml-dev.org/forums/index.php?topic=8331.0), I plan to improve the module to implement such functionality more easily. What this implies concretely -- I don't know yet.

2) When adding a animation you use a std::string as the identity key. Would be great if this could be over loaded to also be able to use simple int.
Are you using Thor 1.1? Because the Thor 2.0 Git version allows you to use any type as identifier (thor::Animator is a class template).
Title: Re: Thor 2.0
Post by: aNewHobby on June 29, 2012, 04:08:07 am
1) aniamtion.getFrameNumber(); ---- It would be cool to be able to test witch frame the animation is on at any give refresh for the window. This could be used for a lot of stuff.. say syncing audio ques for example.
As already mentioned in the other thread (http://en.sfml-dev.org/forums/index.php?topic=8331.0), I plan to improve the module to implement such functionality more easily. What this implies concretely -- I don't know yet.

Awesome!

2) When adding a animation you use a std::string as the identity key. Would be great if this could be over loaded to also be able to use simple int.
Are you using Thor 1.1? Because the Thor 2.0 Git version allows you to use any type as identifier (thor::Animator is a class template).

Ahh sweet.. yeah I was just going off the demo example, and it used strings.. cool that it can use ints.. I'll prob switch to that for my next one.
Title: Re: Thor 2.0
Post by: Tresky on July 09, 2012, 05:43:22 am
I'm new to Thor and I love what I see so far. I'm trying to wrap my head around the resource manager though. I think I'm beginning to understand how it works, but I have a question.

Would you think it would be better to make a ResourceSystem class with one ResourceCache inside of it to load ALL of the resources throughout the program? Or... Would it be better to have every thing that needs a resource have a ResourceCache and load it's own resources?
Title: Re: Thor 2.0
Post by: Nexus on July 09, 2012, 10:53:09 am
You have to reflect why you need a resource cache. The main purpose is to delegate lifetime managment and checks for already loaded resources. Having a separate cache everywhere you need resources doesn't make much sense, you could as well load the resources directly.

This doesn't imply that one centralized thor::MultiResourceCache is always the best solution, but it's probably a good one in many cases. If you like a more modular design (e.g. sound and graphics completely uncoupled), specialized thor::ResourceCache<R> instances are more appropriate.
Title: Re: Thor 2.0
Post by: Tresky on July 09, 2012, 06:57:09 pm
Oh okay, that makes sense.
Thanks! Have you considered opening a forum for Thor? It would make finding questions that have already been asked sooooo much easier.

EDIT: I have a question about the thor::Action system. I put a thor::ActionMap in a class and I can't get it to work as a pointer.
class MyClass
{
public:
    MyClass(sf::RenderWindow* window) {
        map = new thor::ActionMap<UserActions>(*window); // This work with no error
        map[Action1] = thor::Action(sf::Keyboard::A); // This gives me an error with the operator=.
        // Unmatched types. Is there a workaround?
    }

private:
    thor::ActionMap<UserActions>* map;
};
Title: Re: Thor 2.0
Post by: Nexus on July 09, 2012, 07:48:08 pm
Another case where manual memory management is absolutely unnecessary and misleading ;)
Don't use raw new and delete, there are hardly any justified use cases.

Just use automatic objects instead of pointers. And work with the constructor initializer list, it should always be preferred for member initialization. Additionally, your constructor should probably be explicit.
class MyClass
{
public:
    explicit MyClass(sf::RenderWindow* window)
    : map(*window)
    {
        map[Action1] = thor::Action(sf::Keyboard::A);
    }

private:
    thor::ActionMap<UserActions> map;
};

An own forum for Thor is currently out of question, but maybe this will change one day :)
Title: Re: Thor 2.0
Post by: Tresky on July 09, 2012, 11:50:20 pm
Were the Thor smart_ptrs taken out of the library? I can't find them.
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 10, 2012, 12:38:50 am
Were the Thor smart_ptrs taken out of the library? I can't find them.
Yes!
You now should use the official C++11 std::shared_ptr<T>.
Title: Re: Thor 2.0
Post by: Tresky on July 10, 2012, 06:04:09 am
My compiler isn't compatible with C++11. :( Unless there was a MSVS2010 update I'm not aware of.

EDIT: I take that back. Finally found them. Just had to do the right search. :P
Title: Re: Thor 2.0
Post by: Nexus on July 10, 2012, 07:44:30 pm
Were the Thor smart_ptrs taken out of the library? I can't find them.
Depends, which one do you mean? The following points have changed from Thor 1.1 to Thor 2.0 (and the library Aurora on which Thor depends):
Title: Re: Thor 2.0
Post by: Nexus on August 01, 2012, 03:45:30 pm
Most important changes in July:
For the swiss national day, I developed a new Fireworks example today. It shows how to write custom particle emitters and affectors and combines them with various utilities like thor::CallbackTimer or thor::PolarVector2f. I hope you like it.
Title: Re: Thor 2.0
Post by: eXpl0it3r on August 01, 2012, 06:57:16 pm
For the swiss national day, I developed a new Fireworks example today. It shows how to write custom particle emitters and affectors and combines them with various utilities like thor::CallbackTimer or thor::PolarVector2f. I hope you like it.
Awesome! :D
Are you Swiss too or was the more of a coincident?

I should defently take a look at particles at one point. ;)
Title: Re: Thor 2.0
Post by: Hiura on August 02, 2012, 10:48:54 am
Hahaha this is awesome !  ;D
Title: Re: Thor 2.0
Post by: Nexus on August 02, 2012, 08:41:02 pm
Thank you both! Yes, I am Swiss :)

Here is a small screenshot of the fireworks. To see them in action, build the Thor examples of the latest Git revision.
(http://www.bromeon.ch/libraries/thor/v2.0/thor-fireworks.png)
Title: Re: Thor 2.0
Post by: Tresky on August 10, 2012, 07:47:54 am
Hey! I've begun using the Animation classes for Thor to help animate the ground on a map (water flowing, grass moving, etc). I was wondering, would it be best to have one Animator animating every single tile of grass (its a tile map), or to have each tile have its own Animator and just update them all?

It seems like the second method would be memory intensive, but I'm not expert with Thor yet, so I'm not sure how it goes about doing things.
Title: Re: Thor 2.0
Post by: Nexus on August 10, 2012, 08:24:04 am
It depends on whether the animations are synchronized. If for all grass tiles, the same frame is shown at the same time, you can use a single animator and call animate() multiple times. If each tile has its own animation state, store separate animators.
Title: Re: Thor 2.0
Post by: Tresky on August 10, 2012, 08:25:42 am
Ah! That makes sense. Thank you.
Title: Re: Thor 2.0
Post by: Tank on August 10, 2012, 08:46:55 pm
I think 50% of all SFML users are from Switzerland. I feel oppressed. :( ;)

The fireworks look nice. I tried the other examples too for the first time (not only reading through the sources this time) and discovered a bug in the triangulation example. See attached file for a screenshot. The lower right point was added last. Besides of that I reaaally love the triangulation.

Are there any plans on your side to add the 3rd dimension? Imho it's easier to stick to 3D for the library and just ignore the Z component everywhere in 2D games instead of using 2D everywhere, which makes it impossible to use Thor in 3D games.

[attachment deleted by admin]
Title: Re: Thor 2.0
Post by: Nexus on August 10, 2012, 10:09:10 pm
The fireworks look nice.
Thanks! First I just used single particles (like in the Particles example), but it didn't look good and I spent some time to make "tails" :)

I tried the other examples too for the first time (not only reading through the sources this time) and discovered a bug in the triangulation example. See attached file for a screenshot. The lower right point was added last.
Assuming you mean the lines that exceed the convex hull: This is not a triangulation bug, but a SFML shape issue. I noticed this behavior already when I tested the triangulation, but considered it a SFML-given limitation and didn't think anymore about it. But I opened a thread (http://en.sfml-dev.org/forums/index.php?topic=8841.new#new) now.

Are there any plans on your side to add the 3rd dimension?
Generally, Thor as an SFML extension doesn't really provide 3D functionality (apart from basic vector operations that might be useful for SFML sound spatialisation). I don't know if the generalization would complicate the algorithm a lot. If not, I might indeed reflect about it, but there are many more important points to be done before.

Thor's triangulation functionality was originally needed for thor::ConcaveShape, but I thought there might be more applications and as I already implement it anyway, I could put it into the API. But I'm not a graph theorist, so there are certainly more optimized implementations out there. Maybe LEMON (http://lemon.cs.elte.hu/trac/lemon) (a very nice graph library I use) has something, I also heard that Delaunay triangulation might be a candidate for Boost.Geometry.
Title: Re: Thor 2.0
Post by: Tank on August 11, 2012, 10:53:25 am
Quote
Assuming you mean the lines that exceed the convex hull: This is not a triangulation bug, but a SFML shape issue.
Okay I see. Just thought it's worth mentioning.

Quote
I don't know if the generalization would complicate the algorithm a lot.
More complicated? No. Different? Yes. :P

Quote
But I'm not a graph theorist, so there are certainly more optimized implementations out there.
I do know nearly nothing about any triangulation algorithms, and yours already looks quite good. Of course I don't know how good it performs etc., but I guess it's enough for a lot of cases, especially in the 2D area.
Title: Re: Thor 2.0
Post by: frapa on August 11, 2012, 09:52:41 pm
I tried to compile thor on my linux machine with g++ and I got this error:

Code: [Select]
/home/francesco/Downloads/Bromeon-Thor-05b0078/src/InputNames.cpp: In function ‘thor::{anonymous}::StringBimap<sf::Keyboard::Key> thor::{anonymous}::InitMap(aurora::Type<sf::Keyboard::Key>)’:
/home/francesco/Downloads/Bromeon-Thor-05b0078/src/InputNames.cpp:86:3: error: ‘Unknown’ is not a member of ‘sf::Keyboard’
make[2]: *** [src/CMakeFiles/thor.dir/InputNames.cpp.o] Error 1
make[1]: *** [src/CMakeFiles/thor.dir/all] Error 2
make: *** [all] Error 2

I tried to remove the line 86 and the compilation went fine.
Title: Re: Thor 2.0
Post by: eXpl0it3r on August 11, 2012, 10:41:15 pm
Thor 2.0 works only with the latest SFML 2.0 version (directly from GitHub). sf::Keyboard::Unknow was introduced after the RC release. Of course you can change/delete that line yourself if you don't want to build SFML. ;)
Title: Re: Thor 2.0
Post by: frapa on August 12, 2012, 09:31:44 pm
Oh, that's why... I got the RC release... waiting for the official 2.0 release to rebuild SFML  :-[
Title: Re: Thor 2.0
Post by: Nexus on August 13, 2012, 09:23:44 pm
You can just pull the latest Git revision of SFML, no need to wait for the release.

By the way, please read my installation tutorial, it explicitly states that you need a recent SFML revision in order to compile the latest Thor ;)
Title: Re: Thor 2.0
Post by: frapa on August 13, 2012, 11:29:32 pm
I thought that RC was quite recent... It dates back to April... and since it is an RC there should be just bug fixes right? I did not expect an API change (if this can be considered API change...).
Title: Re: Thor 2.0
Post by: eXpl0it3r on August 14, 2012, 12:15:52 am
In an active development 4 month is quite a lot of time. Also RC does not mean there can't be any changes to the API, it's just a tag that implies that there won't be any major changes, like going back to the CamelCase naming convention or similar. Additionally if you want to get picking the adding of sf::Keyboard::Unknown isn't a change but an addition. :P

If you want to wait for the release you maybe waiting two weeks but you could also be waiting half a year, Laurent doesn't set a fix date and since it's so simple to compile it yourself, it doesn't really bother me (anymore). :)
Title: Re: Thor 2.0
Post by: frapa on August 14, 2012, 11:48:09 am
Yeah, actually it is very simple to compile it... and since Ubuntu sucks as long as packages update is concerned, we have to compile it ourselves! Archlinux is much better in this aspect (for developers and pro users!).

Anyway I compiled SFML only a month ago I think, and I'm not going to compile it every week!!!
Title: Re: Thor 2.0
Post by: eXpl0it3r on August 14, 2012, 12:01:05 pm
Anyway I compiled SFML only a month ago I think, and I'm not going to compile it every week!!!
Suit yourself. ;)
I don't mind to type every now end then:
git pull
cmake ./
make install

:D
Title: Re: Thor 2.0
Post by: Orwel on August 29, 2012, 08:08:35 pm
Hello,

i have problem to compil Thor in dynamic.

In tutorial, i dont have make this action :
Quote
Important: Do not only compile SFML, but also install it. That means, you have to build the install target. You do that as follows:

But it is not problem i think, because i can compil Thor in static.

I cut error message, because he are long and repeat same sentence :
...
CMakeFiles\thor.dir/objects.a(StopWatch.cpp.obj):StopWatch.cpp:(.text+0xfd): und
efined reference to `_imp___ZN2sf5Clock7restartEv'
CMakeFiles\thor.dir/objects.a(Timer.cpp.obj):Timer.cpp:(.text+0x7a): undefined r
eference to `_imp___ZN2sf4Time4ZeroE'
CMakeFiles\thor.dir/objects.a(Timer.cpp.obj):Timer.cpp:(.text+0xf8): undefined r
eference to `_imp___ZN2sfmiENS_4TimeES0_'
CMakeFiles\thor.dir/objects.a(Timer.cpp.obj):Timer.cpp:(.text+0x106): undefined
reference to `_imp___ZN2sf4Time4ZeroE'
CMakeFiles\thor.dir/objects.a(Timer.cpp.obj):Timer.cpp:(.text+0x120): undefined
reference to `_imp___ZN2sfltENS_4TimeES0_'
CMakeFiles\thor.dir/objects.a(Timer.cpp.obj):Timer.cpp:(.text+0x162): undefined
reference to `_imp___ZN2sfgeENS_4TimeES0_'
collect2: ld returned 1 exit status
mingw32-make[2]: *** [src/libthor.dll] Error 1
mingw32-make[1]: *** [src/CMakeFiles/thor.dir/all] Error 2
mingw32-make: *** [all] Error 2
 

I think this problem is file's name of dynamic SFML library. See :
libsfml-audio.a
libsfml-graphics.a
libsfml-main.a
libsfml-system.a
libsfml-window.a
 

In debug, replace ".a" by "-d.a".

Result is :
libthor.dll.a
 

But not ".dll"  :(

If you need other information, dont hesitated  ;)
Title: Re: Thor 2.0
Post by: Nexus on August 29, 2012, 09:53:26 pm
In tutorial, i dont have make this action :
Then please try it now. Do everything as described in the tutorial, install SFML also in dynamic release mode (the same configuration as Thor). There is a reason why I wrote the tutorial ;)

If this doesn't work, describe exactly each step you performed. I have tested MingW dynamic release just now, there have been no problems.
Title: Re: Thor 2.0
Post by: Ceylo on September 08, 2012, 04:35:23 pm
I don't know whether this has already been reported but... I get a crash with the Events module with Visual Studio 2010. I built Thor and SFML with the latest sources from the Git repositories. It crashes when leaving the handleEvents() function if I use an action that is registered in the ActionMap (ie. press Escape to crash in this example). I wasn't getting any crash when using Thor on OS X though.

From the call stack I saw in the original program it looks like it crashes on a temporary object destruction. However with this sample program I get a "naked" call stack so I'll post the one from the other program.

#include <SFML/Graphics.hpp>
#include <Thor/Events.hpp>

sf::RenderWindow window(sf::VideoMode(640, 480), "window");
thor::ActionMap<std::string>::CallbackSystem m_callbackSystem;
thor::ActionMap<std::string> m_actionsTable(window);
bool run = true;

void someAction(void)
{
        run = false;
}

void handleEvents(void)
{
        m_actionsTable.update();
        m_actionsTable.invokeCallbacks(m_callbackSystem);
}

int main(int argc, char **argv)
{
        m_actionsTable["exit"] = thor::Action(sf::Keyboard::Escape, thor::Action::PressOnce) || thor::Action(sf::Event::Closed);
        m_callbackSystem.connect("exit", std::bind(&someAction));
       
        while (window.isOpen() && run)
        {
                handleEvents();
               
                window.clear();
                window.display();
        }
       
        return 0;
}

(http://f.cl.ly/items/053P3z1f0B372u0u1i15/thoractions.png)
Title: Re: Thor 2.0
Post by: eXpl0it3r on September 08, 2012, 05:07:50 pm
Does it happen in debug mode as well as in release mode?
Have tried to wrap things into a class rather than having everything in the global scope (for me any application with sf::RenderWindow or sf::Texture crashes at the beginning in debug mode VS10 x64 ATI)?
Title: Re: Thor 2.0
Post by: Ceylo on September 08, 2012, 05:12:30 pm
Yes it happens in both modes, although it can needs a few more times (key presses) in release mode before it crashes.

And everything was originally wrapped in a class. I put everything like that to shorten the source code as much as possible. And I'm not using an ATI graphics card so it can't be related. Moreover the crash does not happen if I press keys that don't match any registered action.
Title: Re: Thor 2.0
Post by: Nexus on September 08, 2012, 05:18:02 pm
At me, in static debug mode, even the pure SFML code
#include <SFML/Window.hpp>

sf::Window window(sf::VideoMode(640, 480), "window");

int main() {}
crashes before reaching main(). That's why I always avoid globals, and you should try it without, too.

Does this code, where I moved all the class instances to local scope, work for you?
#include <SFML/Graphics.hpp>
#include <Thor/Events.hpp>

bool run = true;

void someAction()
{
        run = false;
}

int main()
{
        sf::RenderWindow window(sf::VideoMode(640, 480), "window");
        thor::ActionMap<std::string>::CallbackSystem m_callbackSystem;
        thor::ActionMap<std::string> m_actionsTable(window);

        m_actionsTable["exit"] = thor::Action(sf::Keyboard::Escape, thor::Action::PressOnce) || thor::Action(sf::Event::Closed);
        m_callbackSystem.connect("exit", std::bind(&someAction));

        while (window.isOpen() && run)
        {
                m_actionsTable.update();
                m_actionsTable.invokeCallbacks(m_callbackSystem);

                window.clear();
                window.display();
        }
}

Do you link SFML and Thor statically or dynamically?
Title: Re: Thor 2.0
Post by: Ceylo on September 08, 2012, 05:48:22 pm
Your code crashes when I try it, without changing anything. I don't think I did anything special except maybe enabling static stdlib in both SFML and Thor. I also added /MT flag for code generation in order to build against Intel TBB, but this is already the default for SFML with static stdlib. SFML and Thor are both built and linked dynamically though. And I'm running Visual Studio 2010 on Windows 7 x64.

In debug mode I link against debug libraries only (sfml-graphics-d.lib, sfml-window-d.lib, sfml-system-d.lib, sfml-main-d.lib, thor-d.lib) and release libraries for release mode.


Edit: I rebuilt both SFML and Thor without static stdlib and thus removed the /MT flag (and corresponding flag in debug mode) and now it works fine. I thought I had to specify /MT because of Intel TBB (against which I was linking my program) but as a matter of fact it was because I had enabled static stdlib. I'm still wondering why I can't use Thor with static stdlib enabled though.
Title: Re: Thor 2.0
Post by: Nexus on September 09, 2012, 12:30:10 pm
I'm still wondering why I can't use Thor with static stdlib enabled though.
Me too.

I have built SFML and Thor with static standard libraries and I have reproduced your error. I have absolutely no idea why it occurs though, but I think it's rather a configuration/link problem than code...

Has anyone encountered similar issues with static standard library linkage? I have often heard that it is not recommended since different runtime versions might conflict. But when SFML, Thor and the end-user project all use /MT (or /MTd in debug mode), this should be ok, shouldn't it? Are the external libraries used by SFML a possible cause of trouble?
Title: Re: Thor 2.0
Post by: Nexus on September 11, 2012, 07:27:21 pm
I have again tried to find out the reason of this crash, to no avail so far. Interestingly, the problem only occurs when Thor/SFML are linked dynamically (in either debug or release mode). The application also crashes without the m_callbackSystem.connect() call (I also omitted operator|| and replaced sf::RenderWindow with sf::Window). I haven't been able to further reduce the code:
#include <SFML/Window.hpp>
#include <Thor/Events.hpp>

int main()
{
        sf::Window window(sf::VideoMode(640, 480), "window");
        thor::ActionMap<std::string>::CallbackSystem m_callbackSystem;
        thor::ActionMap<std::string> m_actionsTable(window);

        m_actionsTable["exit"] = thor::Action(sf::Keyboard::Escape, thor::Action::PressOnce);

        while (window.isOpen())
        {
                m_actionsTable.update();
                m_actionsTable.invokeCallbacks(m_callbackSystem);

                window.display();
        }
}

There occurs a heap corruption at the destruction of the result variable in thor::ActionMap::invokeCallbacks(). To be more precise, the operator delete deallocation in std::vector fails.

From my experience, heap corruptions most often occur when something is deleted twice or incorrectly. Since Thor uses zero direct delete operations in its code (everything is encapsulated), this is very improbable. I even changed the thor::Action implementation to use std::unique_ptr instead of aurora::CopiedPtr, just to exclude bugs in my smart pointers. The result remained the same.

As mentioned earlier, I still guess it is a configuration/library issue, furthermore this is enforced by the fact that Thor with dynamically linked runtime runs well. I have checked the verbose linker output and apparently, SFML, Thor and the project use the same runtime DLLs (libcmt.dll and libcmtd.dll, respectively).

So the only thing I could imagine is that there are specific compiler flags that are incompatible to each other. Does SFML change specific VS project properties, except for /MT or /MTd flags? Or maybe CMake? I will also try with a CMake-generated application.
Title: Re: Thor 2.0
Post by: Laurent on September 11, 2012, 08:00:29 pm
Quote
Does SFML change specific VS project properties, except for /MT or /MTd flags? Or maybe CMake?
I don't think so.

You should check the final executable dependencies, and make sure that there's no VC++ DLL there.
Title: Re: Thor 2.0
Post by: Nexus on September 11, 2012, 08:48:18 pm
I will also try with a CMake-generated application.
Didn't work either.


You should check the final executable dependencies, and make sure that there's no VC++ DLL there.
I already did that with Dependency Walker, and the project doesn't link any VC++ DLL directly. However, msvcrt.dll is referenced from various other dynamic libraries, such as OpenGL32.dll.

Multiple runtime versions result in different heaps, maybe allocation and deallocation don't take place in the same one. The relevant code itself is defined in the header, but other operations on result (like a push_back() which needs the allocator) occur in a Thor .cpp file.

In fact that sounds like a reasonable theory, but if I have multiple runtime versions, how can I avoid them? I'm going to compare compiler flags manually now...

The C libraries upon which SFML depends are not an issue?
Title: Re: Thor 2.0
Post by: Nexus on September 12, 2012, 11:55:20 pm
Okay, the problem is indeed that both .exe and .dll have their own CRT instance, and thus a separate freestore/heap. This is also why the issue doesn't happen when Thor is linked statically: A static library doesn't have its own CRT, so the final .exe only uses a single runtime environment.

In order to avoid undefined behavior, code that invokes common allocation/deallocation routines (or that accesses other shared global data) must remain inside the same CRT. This implies that corresponding functions must be either defined completely in the .dll or completely in the .exe. Inline functions (and compiler-generated member functions) are a special case, it depends on the compiler whether their binary code is placed into the .dll or the .exe file. Therefore, the only reliable way to avoid mixed CRT access is to define every function in the .cpp file.

This wouldn't be such a huge issue if it didn't include the Big Three (or Big Five in C++11). In Thor, they are almost always compiler-generated, often thanks to aurora::CopiedPtr. I have only two classes that define a copy constructor, one of them is internal and the other is never used ;)

Alas, the only way to fix this consists of writing masses of boilerplate-code. This is not only a pain, but is likely to introduce bugs and places an additional maintenance burden. I will not do this for the sake of a configuration that is almost never used. Note that even if I fixed everything, SFML would still have the same problem.

In conclusion, I am going to forbid the combination of static CRT linkage and dynamic Thor linkage. I believe this decision is reasonable, considering that people who link CRT statically usually do it because they want to have everything in the .exe, so they can as well link Thor statically.
Title: Fewer affectors, more animations
Post by: Nexus on September 13, 2012, 10:51:13 pm
It is time to announce again something interesting, after many boring updates of bugs with specific configurations.

I have implemented an idea the user gavintlgold gave me a long time ago (http://en.sfml-dev.org/forums/index.php?topic=4646.msg34471#msg34471), namely to combine animations and particle affectors. And thor::FrameAnimation is no more alone! :) What has changed:
This effectively allows users to write an animation which animates sprites, texts, particles and other interface-conforming classes. Since thor::Particle and sf::Sprite have completely different APIs, I provide basic adapter functions in Graphics/UniformAccess.hpp (there are more to come).

I don't know whether the Animation and Particles modules are going to remain unchanged until the Thor 2.0 release. I have already considered std::function for particle emitters and affectors. To define a new affector or emitter, one could take a simple function or lambda expression, no class hierarchy is required.
Usage is also simpler because affectors and emitters have value semantics.

On the downside, I lose shared ownerhip semantics, which has some drawbacks:
Maybe there is a way to combine the advantages from both worlds, something towards std::ref(). In case I should come across a solution, it is probable that affectors and animations are even further unified.
Title: Re: Thor 2.0
Post by: thePyro_13 on January 14, 2013, 10:41:18 am
So I've been hooking as much of my game up with thor::Action as possible over the past few days and have run into an issue.

When subscribing joystick buttons, we provide the joystick ID and the button. However, the joystick axis movement seems like it can only be subscribed with the JoyMoved Event. I had hoped that I'd be able to subscribe specific axis from specific joysticks, but this doesn't appear to be possible with the current thor::Action API.

This isn't a problem with MouseMove events, as their can only be one logical mouse cursor, but that isn't the case with joysticks and their axis.

Is a more specific subscription available for joystick axis? Or does Thor not currently provide anything like this?
Title: Re: Thor 2.0
Post by: Nexus on January 14, 2013, 08:18:04 pm
Thanks for your feedback :)

At the moment, you can only create an action associated with joystick axis as follows:
thor::Action action(sf::Event::JoystickMoved);

If you use callbacks, you can then react in this way:
void callback(thor::ActionContext<X> context)
{
    sf::Event::JoystickMoveEvent = context.event->joystickMove;
    // do something
}

It is not possible to connect a specific axis and joystick ID directly to a callback, but it would be a good idea. Some parts of the Thor.Events module can be improved, for example a similar action for mouse wheels would be appropriate. If you have further ideas or reports, for example whether the callback system is easy enough to use, don't hesitate to tell me! Just note that I probably won't have time to implement a lot in the next few weeks.
Title: Re: Thor 2.0
Post by: Tank on March 22, 2013, 04:56:18 pm
Long time no news from Thor! :)

I've always stated that I want to give Thor a try, and the time finally came: I'm doing a neat little 2D game for getting back into C++ after weeks full of annoying must-do work in other crappy languages.

Just wanted to say thanks for a nice library. It makes a lot of things much easier and game creation more fun. Here's a little demo of what I'm using it for (for now at least ;)):

http://www.youtube.com/watch?v=mnJ8r_PbQCY
Title: Re: Thor 2.0
Post by: Nexus on March 22, 2013, 06:13:12 pm
Cool demo! What parts of Thor have you used? I assume the clouds have been created with the particle system?

In about a month, I should again have more time to work on Thor. I already have some important changes in mind :)
Title: Re: Thor 2.0
Post by: FRex on March 23, 2013, 01:45:07 am
Could you please add default constructor to ActionMap and let me connect the window later/just use pushing?
Title: Re: Thor 2.0
Post by: Tank on March 23, 2013, 01:56:47 am
Exactly, the particle module and the distribution stuff from the math module.
Title: Re: Thor 2.0
Post by: Nexus on March 23, 2013, 11:23:30 am
Could you please add default constructor to ActionMap and let me connect the window later/just use pushing?
The problem is, you pay a high price for some convenience of default constructors: You take invalid objects into account. A thor::ActionMap without a window is not fully functional. Its update() can't poll the events, and thor::ActionContext in the callbacks can't be initialized correctly. I am sure that people would run into runtime errors (update() failing, or dereferencing null pointers), while at the moment I provide compile-time safety.

May I ask why you can't initialize the ActionMap only when you have a window available? To convince me, I always need use cases ;)
Title: Re: Thor 2.0
Post by: FRex on March 23, 2013, 01:28:45 pm
Quote
May I ask why you can't initialize the ActionMap only when you have a window available?
Because I was using it as a member, now I have member std::unique_ptr to it instead and init it later with a method. Also, the pain of cascading init lists:

I have a game class that has in it a controller class that has action map in it. If I have to pass a window to there, I'd have to pass the reference to game class constructor(which I didn't write because every member is smart enough to have default constructors), then pass it to controller constructor(which I'd have to write too) in the init list, then in the controller init list I need to pass it to action map. That's a lot of work for tiny action map class. ;)
Title: Re: Thor 2.0
Post by: Nexus on March 23, 2013, 04:34:00 pm
That's a lot of work for tiny action map class. ;)
True, but only very simple classes don't need a constructor. As soon as you have scalar members or perform an actual initialization, the constructor needs to be there. At least if you want the object to be completely operational after the constructor call, and don't rely on other methods to be invoked.

Anyway, I have an idea for a potential solution: Making the sf::Window no longer a part of thor::ActionMap's state. If the window is only used to poll events, one possibility comprises that the window is passed to ActionMap::update(), and the ActionContext::window member variable is removed. Then I might get around the invalid object issue. I have to investigate this...
Title: Re: Thor 2.0
Post by: Nexus on March 25, 2013, 07:32:24 pm
As planned in my previous post, I decoupled the window from the object state. ActionMap can now be used as follows. Thanks for the feedback, FRex.
thor::ActionMap<...> map;
...

map.update(window);
map.invokeCallbacks(callbackSystem, &window);

Furthermore, I renamed the Events module to Input. This is more general, the name "Events" comes from the beginnings of Thor where only functionality for SFML events was provided. Now the module covers also real-time input and conversions from and to SFML's enums (like sf::Mouse::Left).

I updated the Action tutorial and the online documentation correspondingly.
Title: Re: Thor 2.0
Post by: FRex on March 26, 2013, 11:15:10 pm
Quote
Thanks for the feedback, FRex.
Don't thank me for whining. ;)
Title: Re: Thor 2.0
Post by: Silvah on April 12, 2013, 01:48:34 pm
I disowned the Thor package (https://aur.archlinux.org/packages/thor-git/) in AUR. It's still there, but I don't maintain it anymore, it'd be good if somebody picked it up from there.
Title: Re: Thor 2.0
Post by: The Terminator on April 14, 2013, 08:28:20 pm
Hi there. I successfully compiled and linked Thor 2.0 into my current project, and I'm using actions to rework some of my buttons, key commands, etc. However, whenever you click once on mouse or whatever, it does the action atleast 5 times, and it's getting extremely annoying. Here's some example code:

I initialize the actions:

thor::Action m_exitAction;
thor::Action m_mouseClickedAction;
thor::Action m_fpsShortcut;

Init them with the constructor:

m_exitAction(sf::Event::Closed),
m_mouseClickedAction(sf::Mouse::Left),
m_fpsShortcut(sf::Keyboard::F)

I've also tried thor::Action::PressOnce, and that makes the key or mouse button click infinitely.

And set them to the corresponding enumators:

m_actions[EXITACTION] = m_exitAction;
m_actions[LMOUSECLICKACTION] = m_mouseClickedAction
m_actions[FPSSHORTCUTACTION] = m_fpsShortcut;

Then I actually use it:

void CIntroState::update() {
    while(m_game.screen.pollEvent(event))
        m_game.getActionMap().pushEvent(event);

        if (m_game.getActionMap().isActive(CGameEngine::Actions::EXITACTION))
        m_game.quit();

    else if (m_game.getActionMap().isActive(CGameEngine::Actions::LMOUSECLICKACTION))
    {
        if (m_play.isHoveredOver(m_game.screen))
            m_next = m_game.build<CIntroState>(true);
        else if (m_options.isHoveredOver(m_game.screen))
            m_next = m_game.build<CSettingsState>(true);
        else if (m_exit.isHoveredOver(m_game.screen))
            m_game.quit();
    }

    else if (m_game.getActionMap().isActive(CGameEngine::Actions::FPSSHORTCUTACTION))
    {
        if (m_game.getFPSOn())
            m_game.setFPSOn(false);
        else
            m_game.setFPSOn(true);

        m_game.saveOptions();

        std::cout << "FPS has the value: " << m_game.getFPSOn() << " now." << std::endl;
    }
}

I appreciate any answers.
Title: Re: Thor 2.0
Post by: Nexus on April 14, 2013, 08:49:19 pm
I disowned the Thor package (https://aur.archlinux.org/packages/thor-git/) in AUR. It's still there, but I don't maintain it anymore, it'd be good if somebody picked it up from there.
Okay. I don't really have the experience with AUR packages, so if anybody is willing to maintain it, feel free to do so :)

However, whenever you click once on mouse or whatever, it does the action atleast 5 times, and it's getting extremely annoying.
Without a second argument to the Action constructor, you choose real-time input (Action::Hold). That means the action is active all the time a button is pressed down. You want to use Action::PressOnce.

I've also tried thor::Action::PressOnce, and that makes the key or mouse button click infinitely.
You forgot to call ActionMap::clearEvents(). But you can directly call ActionMap::update() with the window, see here (http://www.bromeon.ch/libraries/thor/v2.0/doc/classthor_1_1_action_map.html#a1fb7507f79952f586632d5278f478d33) for its semantics.

Keep in mind that there may be more than a single action active per frame, so your else if should be if. Or you directly use callbacks.

By the way, you can keep your action and event variables local, there is no need to make them class members. In the case of event, you don't need the variable anyway if you call ActionMap::update().
m_actions[EXITACTION] = thor::Action(sf::Event::Closed, thor::Action::PressOnce);
...
sf::Event event;
while (m_game.screen.pollEvent(event));
Title: Re: Thor 2.0
Post by: The Terminator on April 15, 2013, 11:32:25 pm
Thanks a lot for the help. You fixed my other problem, but I'm sort of confused on animations. I followed the example from the latest version (with the soldiers), but I'm having a problem with one thing. Whenever I try to add a frame, it'll crash the executable. Here's my code:

m_animation1.addFrame(1.0f, sf::IntRect(m_game.getEntityManager()("player")->getSprite().getTextureRect()));

m_animation2.addFrame(2.0f, sf::IntRect(m_game.getEntityManager()("platform1")->getSprite().getTextureRect()));

Thanks
Title: Re: Thor 2.0
Post by: Nexus on April 16, 2013, 09:03:59 am
With this information, I can't say where the problem is. Is the access to your entity manager defined (e.g. no dereferenced nullptr or similar)? What if you hardcode a sf::IntRect directly?

Have you already tried to debug your code, or maybe even to minimize it and track down the error? If you had a minimal and complete example, I could take a look at it...
Title: Re: Thor 2.0
Post by: Tank on April 16, 2013, 09:09:58 am
I'm having a problem with Thor's particle module regarding rendering: As far as I understand, all the particles use 2D positions and are rendered in one go. That however makes it impossible to render particles between objects I render myself.

For example let's say there are 3 layers. Layer 0 is the background, layer 1 holds objects, layer 2 is the sky. Because neither SFML nor Thor allow me to use custom z values for effectively making use of the z buffer, I'm not able to both render particles between layers 0/1 and 1/2. I can workaround that by creating 2 separate particle emitters/systems, but the example with 3 fixed layers is just a simple one.

Indeed I'm currently writing a game where aircrafts fly towards you. Some aircrafts are faster than others, so all of them have a "dynamic z ordering". For explosion effects I wanted to use Thor, but I can't see a way to properly render the particles at specific z positions, i.e. between aircrafts.

Any ideas? Is it even possible with SFML's current layout?
Title: Re: Thor 2.0
Post by: Nexus on April 16, 2013, 09:23:50 am
This is currently not possible. Z ordering could be achieved in two ways:
Particle systems are only one of many situations where Z ordering is meaningful. I already thought about Z buffer functionality in Thor, but haven't found a good way to implement it generically, especially since SFML natively doesn't support it. How do you implement Z ordering for your own airplanes? You just sort them?

By the way, the affector/emitter API is going to change slightly; I will probably abandon shared_ptr and make the API simpler, like in the Animation module.
Title: Re: Thor 2.0
Post by: Tank on April 16, 2013, 09:36:28 am
Quote
How do you implement Z ordering for your own airplanes? You just sort them?
Yes, I sort them according to their z position. Since my plan is to only use SFML in my current game thingy, I had to do it the ugly way. ;) I'd definitely prefer making use of the depth buffer.

Quote
I already thought about Z buffer functionality in Thor, but haven't found a good way to implement it, especially since SFML natively doesn't support it
Yep, and that's the point. You'd have a hard time implementing z ordering using the depth buffer yourself if SFML does not support it. And working around that (which is painful, because it's such a low-level feature) can't be the solution.  At least I can't think of a clean solution for integrating it externally.
Title: Re: Thor 2.0
Post by: Nexus on April 16, 2013, 09:55:17 am
Another important point is that depth buffering does not work with semi-transparent objects. So, manual sorting seems like the only way to go.

What I had in mind for a Z buffer was essentially a list of drawable objects that is sorted. This however opens up new questions, such as:
The idea is certainly interesting. For a long time, Z buffer was a feature on Thor's progress list (http://www.bromeon.ch/libraries/thor/progress.html), but considering the implementation and design difficulties, I didn't want to promise things that I weren't sure of ;)
Title: Re: Thor 2.0
Post by: Tank on April 16, 2013, 10:02:11 am
As I think more of it, it might be even possible. There could be a render queue that takes care of sorting drawables that you add to it. Something similar to this (but with a nicer interface):

sf::Sprite sprite;
sf::VertexArray array;
render_queue.add( sprite, 1.0f );
render_queue.add( array, 2.0f );

The floats determine the z position, as it can't be fetched from the drawables themselves. The queue will then insert the drawable into an internally sorted array. The sorting is dependent on things like z position and alpha color value (due to transparent stuff that has to be rendered front-to-back).

Ownership is very simple here: The queue only holds references (you'd store the drawables somewhere anyway). Also you can continue using SFML's drawables without any change.

To render it you'd only have to draw the queue:

render_window.draw( render_queue );
Title: Re: Thor 2.0
Post by: Nexus on April 16, 2013, 10:05:25 am
That's exactly the API I had in mind :)

But as far as I understood you, inserting a sf::VertexArray into the queue would not solve your problem, since you don't want it to be drawn at once. Therefore, one would have to split up the vertex array into single sprites (or at least smaller vertex arrays).
Title: Re: Thor 2.0
Post by: Tank on April 16, 2013, 10:08:26 am
Yes, because SFML does not support 3D positions and depth buffers. ;)
Title: Re: Thor 2.0
Post by: dragondgold on May 01, 2013, 06:05:00 am
Hello! I am new at SFML 2.0 and I wanted to try Thor, I have successfully compiled SFML and Thor (with C++11 flag) and have it working on Eclipse CDT. The problem is when I try to run my program using Thor I get this:

/home/andres/Dropbox/workspace/PruebaSFML/Debug/PruebaSFML: error while loading shared libraries: libthor-d.so: cannot open shared object file: No such file or directory

I have /SFML-2.0/lib added to my linker and the library libthor-d.so exists and also I have copied it to /usr/local/lib but still the same error. I am on Ubuntu 12.04 x64. What I am missing?

PD: I have it running ok on Windows XP x86
Title: Re: Thor 2.0
Post by: eXpl0it3r on May 01, 2013, 09:54:19 am
I have /SFML-2.0/lib added to my linker and the library libthor-d.so
So is the libthor-d.so in the SFML directory? ???
Otherwise you'll also have to add /Thor/lib to the linking command.

exists and also I have copied it to /usr/local/lib but still the same error
/usr/local/lib is not set by default for the LD_PATH_LIBRARY, so you'll have to set LD_PATH_LIBRARY with /usr/local/lib manually first for the linker to search in that directory.
Title: Re: Thor 2.0
Post by: dragondgold on May 01, 2013, 03:56:31 pm
So is the libthor-d.so in the SFML directory? ???
Otherwise you'll also have to add /Thor/lib to the linking command.

Yes, the library is in SFML-2.0/lib as you can see here:

ls '/home/andres/Dropbox/Development/SFML-2.0/lib'
libsfml-audio.so         libsfml-network.so      libsfml-window.so
libsfml-audio.so.2       libsfml-network.so.2    libsfml-window.so.2
libsfml-audio.so.2.0     libsfml-network.so.2.0  libsfml-window.so.2.0
libsfml-graphics.so      libsfml-system.so          libthor-d.so
libsfml-graphics.so.2    libsfml-system.so.2
libsfml-graphics.so.2.0  libsfml-system.so.2.0

In my Thor folder I have no lib folder, the library was compiled directly in SFML lib folder.

/usr/local/lib is not set by default for the LD_PATH_LIBRARY, so you'll have to set LD_PATH_LIBRARY with /usr/local/lib manually first for the linker to search in that directory.
I have added it because SFML also have libraries in /usr/local/lib:

cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf
include /usr/local/lib

Is very strange. To build Thor I have used this inside Thor directory:

cmake -G "Unix Makefiles" -D CMAKE_BUILD_TYPE=Debug -D CMAKE_INSTALL_PREFIX='/home/andres/Dropbox/Development/SFML-2.0' -D SFML_INCLUDE_DIR=/home/andres/Dropbox/Development/SFML-2.0/include -D SFML_ROOT=/home/andres/Dropbox/Development/SFML-2.0 -D THOR_BUILD_DOC=TRUE -D THOR_BUILD_EXAMPLES=TRUE -D THOR_SHARED_LIBS=TRUE .
make
sudo make install

I have it running OK on my Windows XP machine with Eclipse too.
Here you can see an image of how are my linker settings configured: https://www.dropbox.com/s/p0lp1jt2c2iqcq3/Eclipse.png
Title: Re: Thor 2.0
Post by: Lee R on May 01, 2013, 04:50:55 pm
Check this snippet, taken from 'ParticleSystem::computeVertices':

// Fill vertex array
AURORA_FOREACH(const Particle& p, mParticles)
{
    for (unsigned int i = 0; i < 4; ++i)
    {
        sf::Transform transform;
        transform.translate(p.position);
        transform.rotate(p.rotation);
        transform.scale(p.scale);

        mVertices.append( sf::Vertex(transform.transformPoint(positionOffsets[i]), p.color, texCoords[i]) );
    }
}

There is no need to re-construct the transform for each iteration of the inner loop. I'm guessing this is a refactoring artifact?
Title: Re: Thor 2.0
Post by: Nexus on May 01, 2013, 05:17:41 pm
The problem is when I try to run my program using Thor I get this:
Try sudo ldconfig to update the linker paths. Is there a reason why you link to the release version of SFML, but the debug version of Thor?

There is no need to re-construct the transform for each iteration of the inner loop. I'm guessing this is a refactoring artifact?
Maybe I just overlooked it ;)

Thanks a lot, I'm really glad that people occasionally look at my code!
Title: Re: Thor 2.0
Post by: FRex on May 01, 2013, 05:23:59 pm
Actually I was wrong in what I just written here so I removed it. ;D

Quote
Thanks a lot, I'm really glad that people occasionally look at my code!
I sometimes do too, at Thor, Lua, SFG and SFML.
Title: Re: Thor 2.0
Post by: dragondgold on May 01, 2013, 05:31:33 pm
Try sudo ldconfig to update the linker paths. Is there a reason why you link to the release version of SFML, but the debug version of Thor?

You are amazing Nexus :D It worked perfectly! Seems that something messed up!
Actually, I don't know what is the difference between Release and Debug libraries, I have always used libraries simply putting #include in my program is the first time I have to use a library and don't know why and haven't found nothing about it  :-\
Title: Re: Thor 2.0
Post by: Nexus on May 01, 2013, 05:38:02 pm
In general, you should use the release libraries. If you build Thor with CMake, set CMAKE_BUILD_TYPE to "Release". To link Thor, choose the library without -d prefix; in your linker settings, you can just specify "thor".

On Linux, the debug libraries are only needed if you need debugging symbols (i.e. you want to debug the library).
Title: Re: Thor 2.0
Post by: dragondgold on May 01, 2013, 11:34:26 pm
In general, you should use the release libraries. If you build Thor with CMake, set CMAKE_BUILD_TYPE to "Release". To link Thor, choose the library without -d prefix; in your linker settings, you can just specify "thor".

On Linux, the debug libraries are only needed if you need debugging symbols (i.e. you want to debug the library).

Nice, thank you for the info ! I have seen also that debug libraries have much more file size than release libraries (sorry my bad english)
Thank you very much for your help!
Title: [Thor] Color gradients
Post by: Nexus on May 05, 2013, 02:17:08 pm
Recent changes
New color gradient API

Since a long time I want to redesign the ColorGradient API. Currently, one specifies relative transition times between colors. In the following example, the transition from red to blue is 3 times longer than the transition from blue to cyan.
thor::ColorGradient gradient = thor::createGradient
(sf::Color::Red)
(3.f)
(sf::Color::Blue)
(1.f)
(sf::Color(0, 255, 255));

Despite being short, it may be somehow unintuitive, and it makes it difficult to use specific functions that take RGB (or HSV, in later Thor versions). Therefore I tend to named functions, two possibilities to achieve the same functionalities would be:
thor::ColorGradient gradient;
gradient.color(sf::Color::Red);
gradient.transition(3.f);
gradient.color(sf::Color::Blue);
gradient.transition(1.f);
gradient.rgb(0, 255, 255);
thor::ColorGradient gradient = createGradient()
.color(sf::Color::Red)
.transition(3.f)
.color(sf::Color::Blue)
.transition(1.f)
.rgb(0, 255, 255);
The second option would allow for more type safety, since I can enforce that transitions and colors are specified alternately. Additionally, one cannot change the gradient after construction.

Basically, do you consider the alternating transition-color chain meaningful? Or should I go with another model, like specifying points instead of transitions? The equivalent functionality would then look as follows (conventional methods or map style):
thor::ColorGradient gradient;
gradient.color(0.f, sf::Color::Red);
gradient.color(0.75f, sf::Color::Blue);
gradient.rgb(1.f, 0, 255, 255);
thor::ColorGradient gradient;
gradient[0.f] = sf::Color::Red;
gradient[0.75f] = sf::Color::Blue;
gradient[1.f] = sf::Color(0, 255, 255);

The disadvantage is that one always needs to specify 0.f and 1.f, and it becomes more difficult to express ratios between different partial gradients. Before, it was immediately clear that the first transition had 3 times the length of the second.

Maybe another idea?
Title: Re: Thor 2.0
Post by: Laurent on May 05, 2013, 02:35:43 pm
The second API has its own benefits that should be considered in my opinion:

- it's kind of standard (I've never seen an API similar to the first one for defining gradients)
- it allows to give points in arbitrary order
- it may be more intuitive to associate the color and its position in the same function call, rather than giving them alternately
Title: Re: Thor 2.0
Post by: Nexus on May 05, 2013, 08:53:31 pm
Thanks for the feedback. I chose the following variant, its syntax pleases me most:
thor::ColorGradient gradient;
gradient[0.f] = sf::Color::Red;
gradient[0.75f] = sf::Color::Blue;
gradient[1.f] = sf::Color(0, 255, 255);

There might be users forgetting to set 0.f and 1.f, but it's highlighted in the documentation and verified with assertions.
Title: Re: Thor 2.0
Post by: Laurent on May 06, 2013, 03:20:56 pm
I was looking at Thor/examples/Particles.cpp, and noticed something about the MousePosition functor: it is used only once, and it is "incorrect" (you should call window.mapPixelToCoords, not cast the vector to float directly). So maybe you should just remove it?

And by the way, tabs in the middle of lines look very ugly (at least on github) :P I think that using tabs for indentation is ok, but spaces should be preferred when you want to align things vertically.
Title: Re: Thor 2.0
Post by: Nexus on May 06, 2013, 04:09:21 pm
Thanks for the remarks!

it is "incorrect" (you should call window.mapPixelToCoords, not cast the vector to float directly)
You are right. I only had sf::Window, so I replace it with sf::RenderWindow and call sf::RenderWindow::mapPixelToCoords().


it is used only once [...] So maybe you should just remove it?
If you mean I should directly insert a value, this won't work, since I need to poll the mouse position continuously -- that's why I use a functor and no constant. What I could do would be to set the position each frame, but that somehow defeats the purpose of showing the distribution functors. On the other hand, I also do that for the velocity :P

In fact, this stuff is all quite old, with C++11 I could simply use a lambda expression. Some parts might become also simpler if I performed the Particles refactoring which I have in mind: To go away from shared-ownership and inherited emitters and affectors, towards functors that are copied -- very similar to the Animation API. Instead of:
thor::UniversalEmitter::Ptr emitter = thor::UniversalEmitter::create();
emitter->setEmissionRate(30.f);
system.addEmitter(emitter);
One would write:
thor::UniversalEmitter emitter;
emitter.setEmissionRate(30.f);
system.addEmitter(emitter);

However I'm not quite sure yet, I still have to investigate some points...


And by the way, tabs in the middle of lines look very ugly (at least on github) :P I think that using tabs for indentation is ok, but spaces should be preferred when you want to align things vertically.
I guess you mean
        sf::Vector2f            position;
        thor::PolarVector2f velocity(200.f, -90.f);
        bool                            paused = false;
That's indeed ugly, and it's not my way to define variables anyway. So I'll just go with one space.

What I always do, is using tabs inside class definitions, to align (return) types and declarations. It may be unconventional, but I won't change this just because sites like GitHub are not capable of displaying it correctly. Seriously, they can't just assume everybody uses tabs of width 8 ;)
Title: Re: Thor 2.0
Post by: Laurent on May 06, 2013, 04:31:33 pm
Ah, sorry, I didn't realize that setParticlePosition was taking a functor and not a value ;D

Quote
It may be unconventional, but I won't change this just because sites like GitHub are not capable of displaying it correctly. Seriously, they can't just assume everybody uses tabs of width 8
The problem when you use tabs to align things, is that you assume that tabs have a certain width, because you may mix whitespace (variable width) and characters (fixed width). It can work only with the tab width that you assumed when you wrote the code.

In your example above, "::PolarVector2f " takes 16 characters, therefore you use 2 tabs to align what's below if your tab width is 8, but in an editor where tab width is 4, alignment is broken.
Title: Re: Thor 2.0
Post by: fstream on May 06, 2013, 06:50:50 pm
For the record, tabs are used for indentation, spaces are used for alignment.

int main()
{
____printf("Indented!\n");
____int foo____= 3,
________barbaz_= 8;
____return EXIT_TAB_SUCCESS;
}
Title: Re: Thor 2.0
Post by: Laurent on May 06, 2013, 06:55:09 pm
Thanks, this is exactly what I mean :D
Title: Re: Thor 2.0
Post by: fstream on May 06, 2013, 07:16:26 pm
Thanks, this is exactly what I mean :D
Also this is very wrong as well:

int main()
{
____foo();
____
____return 0;
}


One proof of wrongness:

$ cat <<FOO > demo.c
> int main()
> {
>     foo();
>     
>     return 0;
> }
> FOO
$ git init
Initialized empty Git repository in /tmp/test/.git/
$ git add .
$ git diff --check --cached
demo.c:4: trailing whitespace.
+████


However, fixing it is very easy (https://github.com/SFML/SFML/pull/378) ;)
Title: Re: Thor 2.0
Post by: Laurent on May 06, 2013, 07:21:33 pm
Quote
However, fixing it is very easy
All the corrected files were edited on OS X, not my fault :P
Title: Re: Thor 2.0
Post by: Nexus on May 06, 2013, 07:27:58 pm
Don't flood the Thor thread with the space/tab discussion, I won't change my style anyway :P
Please split the posts to another thread if you want to continue that discussion.

(The specific case in examples/Particles.cpp (https://github.com/Bromeon/Thor/blob/master/examples/Particles.cpp) was fixed though).
Title: Re: Thor 2.0
Post by: Laurent on May 06, 2013, 07:35:57 pm
Sorry :-X
Title: Re: Thor 2.0
Post by: Verra on May 09, 2013, 05:54:23 am
Hello, I've recently built and setup thor and I've finally gotten around to trying to test it out. I started out with particles which seemed interesting . . . and that's where my fun ended. :<

Anyways I feel like I'm missing something blatantly obvious or I just have a setup that's incompatible with thor.
With this code:
#include <Thor/Particles.hpp>
#include <Thor/Animation.hpp>
#include <Thor/Vectors/PolarVector.hpp>
#include <Thor/Math/Distributions.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>

int main()
{
        sf::RenderWindow win(sf::VideoMode(400, 300), "Thor test", sf::Style::Close);
        sf::Event event;

        sf::Texture smoke;
        smoke.loadFromFile("smokeparticle.png");

        thor::ParticleSystem smokeSystem(smoke);
        sf::Clock smokeSystemClock;

        thor::UniversalEmitter::Ptr smokeEmitter = thor::UniversalEmitter::create();
        smokeEmitter->setEmissionRate(15.0f);
        smokeEmitter->setParticleLifetime(thor::Distribution<sf::Time>(sf::seconds(5)));
        smokeSystem.addEmitter(smokeEmitter);

        smokeSystemClock.restart();
        while(win.isOpen())
        {
                while(win.pollEvent(event))
                {
                        if(event.type == sf::Event::Closed)
                        {
                                win.close();
                                return 0;

                        }

                }

                smokeSystem.update(smokeSystemClock.restart());

                win.clear(sf::Color(255, 255, 255));
                win.draw(smokeSystem);
                win.display();

        }

}
 

Errors:
Line 20: Method 'setEmissionRate' could not be resolved
Line 21: Method 'setParticleLifetime' could not be resolved
Line 22: Invalid arguments ' Candidates are: void addEmitter(?) void addEmitter(?, sf::Time) '

I've also tried the example code for particles found on github, with the same errors, everywhere that 'emitter->' and '.addEmitter' are used. I am able to compile the above project with thor if I exclude the emitter code and keep the ParticleSystem it builds and runs properly.

I've setup the compiler flag for c++11 I've tested using shared_ptr separate from the above code with success. I'm using MinGW, gcc 4.7.2 with Eclipse CDT

I hope you have some idea of what's wrong and where I was a derp. Thanks for the help in advanced.

EDIT:

I fixed the issues with functions of UniversalEmitter being unresolved by casting the shared_ptr before using it. like this:
        ((thor::UniversalEmitter)*smokeEmitter).setEmissionRate(15.0f);
        ((thor::UniversalEmitter)*smokeEmitter).setParticleLifetime(thor::Distribution<sf::Time>(sf::seconds(5)));
 

The issues with adding the emitter to the particle system still remain however.

EDIT: EDIT:
I believe I found where I was being a derp all a long. ;) I should have checked the time stamps on the .exe. It was building just the eclipse indexer was saying that there were issues that would stop it from compiling. That still remains a problem so if you know how to fix that, that would be much appreciated.
Title: Re: Thor 2.0
Post by: Nexus on May 09, 2013, 10:51:11 am
The latest Thor revision on g++ compiles fine (tested with MinGW), unfortunately I am not experienced with Eclipse for C++. The indexer problem seems to be a known one, I found this thread (http://stackoverflow.com/questions/12194103/eclipse-cdt-indexer-how-to-solve-unresolved-includes) for example. If you search, you'll certainly find more...

By the way, I hope you're aware that your cast is no real fix -- the two "fixed" statements have no effect.
Title: Re: Thor 2.0
Post by: The Terminator on June 10, 2013, 11:31:39 pm
Hey Nexus, I have a problem that might be a bug in Thor 2.0. When using thor::Action::PressOnce for sf::Keyboard inputs, it performs identical actions to thor::Action::Hold. I can post some code if needed.
Title: Re: Thor 2.0
Post by: Nexus on June 11, 2013, 12:00:17 am
I assume you use the latest Thor revision from GitHub. Is SFML key repeat disabled?

If so, a code would be nice. Please keep it minimal, so that I can directly copy and test if necessary.
Title: Re: Thor 2.0
Post by: The Terminator on June 11, 2013, 12:18:50 am
I solved it shortly after I posted, it was due to the key repeat being on. Thanks anyways.
Title: Re: Thor 2.0
Post by: NaCl on June 18, 2013, 10:25:30 pm
Hi!
I bet I can find a solving for my problem here, but I wasnt able to so I have to ask here, sry.
I get lots of linking errors, it collides with MSVCP100D.dll and of course with MSVCP100.dll, too.
Linker settings: sfml-main-d.lib;sfml-graphics-s-d.lib;sfml-window-s-d.lib;sfml-audio-s-d.lib;sfml-system-s-d.lib;thor-s-d.lib;%(AdditionalDependencies)
Which options do I have to fix this? I have no clue, except unlinking MSVCP100 but I dunno how to do this on a good way. And I dont know if it would be "allowed", too.

Thanks,
Salt
Title: Re: Thor 2.0
Post by: Nexus on June 18, 2013, 10:34:19 pm
What does "it collides" mean? Have you followed the installation tutorial (http://www.bromeon.ch/libraries/thor/v2.0/tutorial-installation.html) step by step?
Title: Re: Thor 2.0
Post by: NaCl on June 18, 2013, 10:47:47 pm
Just that they have problems. xd
Yes I followed the tutorial step by step.
Maybe I should reinstall VS?

Salt
Title: Re: Thor 2.0
Post by: Nexus on June 18, 2013, 11:10:04 pm
Just that they have problems.
Would you mind telling which ones? ;)

That is, show the error message. Can you also tell me what your CMake settings are? I.e. the values of all the variables and checkboxes you see in the screenshot on the homepage.
Title: Re: Thor 2.0
Post by: NaCl on June 18, 2013, 11:41:26 pm
Ofc, excuse me.
The error-messages: http://pastebin.com/tUMeJyBE
My Cmake-Settings are...
CMAKE_BUILD_TYPE           set to Release
CMAKE_INSTALL_PREFIX     set to specific Path
SFML_INCLUDE_DIR            set to [Path to SFML]/include
SFML_ROOT                      set to [Path to SFML]
THOR_BUILD_DOC             set to Unchecked
THOR_BUILD_EXAMPLES    set to Unchecked       //First I checked this, but they didnt compile, same MSVCP100.dll errors
THOR_SHARED_LIBS         set to Unchecked
THOR_STATIC_STD_LIBS  set to Unchecked

Thanks,
Salt
Title: Re: Thor 2.0
Post by: Nexus on June 19, 2013, 07:30:27 am
The preprocessor macro SFML_STATIC is defined? And you are in debug mode?

It looks like you are linking the CRT twice. The option should be /MDd (http://msdn.microsoft.com/en-us/library/2kzt1wy3(v=vs.100).aspx) (multithreaded DLL debug) for SFML, Thor and your project. I would try to rebuild Thor with a completely clean CMake configuration, and create a new empty VS project that uses it.

You might also consider rebuilding SFML, especially if you used different CMake flags to compile it (most notably SFML_USE_STATIC_STD_LIBS).
Title: Re: Thor 2.0
Post by: NaCl on June 19, 2013, 02:12:26 pm
Yes and yes.
/MDd was already enabled, in every project.  :-\

Salt
Title: Re: Thor 2.0
Post by: Nexus on June 19, 2013, 07:50:54 pm
Are you absolutely sure that all three of SFML, Thor and your project use the same CRT configuration, and you link the correct libraries? That is, you don't link Thor in static debug and SFML in release (or dynamic) mode? I ask because these two lines
Quote
1>LINK : warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library
1>LINK : warning LNK4098: defaultlib 'LIBCMTD' conflicts with use of other libs; use /NODEFAULTLIB:library
indicate that two CRT configurations are mixed, namely /MTd and /MDd. Check my previous link.

If this is not the case, rebuild all three projects, after cleaning up their CMake build folders and cache completely. Sometimes there are options which are not correctly applied if you change them later on.

Do not enable either SFML_USE_STATIC_STD_LIBS or THOR_STATIC_STD_LIBS.
Title: Re: Thor 2.0
Post by: NaCl on June 19, 2013, 08:45:31 pm
It works now, thanks.
I reinstalled VS and recompiled SFML + Thor directly after a new download.
Thanks

Salt
Title: Re: Thor 2.0
Post by: tyrion on July 07, 2013, 04:06:52 pm
Hi,

how do i get the actions back from the map list?

e.g.
map[Run] = (Action(XE::IPT::Keyboard::LShift) || Action(XE::IPT::Keyboard::RShift)) && Action(XE::IPT::Keyboard::R);

How do i get LShit ... RShift .. R back?

Thx!  :)
Title: Re: Thor 2.0
Post by: Nexus on July 07, 2013, 06:59:34 pm
Currently, you don't. The original action is abstracted away, thor::Action acts as a type-erasure front end. An interface would be difficult anyway, what return type should a getter have? I would have to do something more complicated, something like it is used in typical type-erasure classes such as std::function or boost::any.

From the PM, I assume you need it for serialization. But it's not that easy anyway -- if you want to support arbitrary boolean-arithmetic expressions, you need a parser to interpret them.
Title: Re: Thor 2.0
Post by: The Terminator on July 13, 2013, 11:22:04 pm
Hey there Nexus, I'm having a little bit of a problem with your library. For my engine, I have an event manager defined here:

    class CEventManager
    {
    public:
        CEventManager();
        ~CEventManager();

        enum EC_Events
        {
            m_closeWindow,
            m_leftMouseButtonClicked
        };

        void clearEvents() { m_eventMap.clearEvents(); }
        void pushEvent(sf::Event& event) { m_eventMap.pushEvent(event); }

        bool isActive(const EC_Events& event) { return m_eventMap.isActive(event); }

    private:
        thor::ActionMap<EC_Events> m_eventMap;
    };

The manager has the Action map, where I have my events. For some reason, the actions never trigger (yes the enumerator stuff is defined.) I have part of my button class here:

    const bool CButton::checkIfMouseHovered(const float x, const float y) const
    {
        if (m_usingTexture)
        {
            if (m_sprite.getGlobalBounds().contains(x, y))
                return true;
        }

        else if (!m_usingTexture)
        {
            if (m_text.getGlobalBounds().contains(x, y))
                return true;
        }

        return false;
    }

    const bool CButton::checkIfMouseClicked(const float x, const float y, CEventManager manager) const
    {
        if (checkIfMouseHovered(x, y) && manager.isActive(CEventManager::EC_Events::m_leftMouseButtonClicked))
            return true;

        return false;
    }

Obviously, for checkIfMouseClicked, I want to check if the left mouse button is clicked. This registers nothing though. Here's part of my intro state class:

    void CIntroState::update()
    {
        m_game.m_eventManager.clearEvents();

        m_game.m_gameGUI.update(sf::Mouse::getPosition(m_game.screen).x, sf::Mouse::getPosition(m_game.screen).y,
                                m_game.m_eventManager);

        while (m_game.screen.pollEvent(m_event))
            m_game.m_eventManager.pushEvent(m_event);

        if (m_game.m_eventManager.isActive(CEventManager::EC_Events::m_closeWindow))
            m_game.quit();

        if (m_game.m_gameGUI.buttonClicked("playbutton"))
            std::cout << "Coming soon" << std::endl;

        else if (m_game.m_gameGUI.buttonClicked("optionbutton"))
            m_next = m_game.build<COptionsState>(true);

        else if (m_game.m_gameGUI.buttonClicked("quitbutton"))
            m_game.quit();
    }

I hope you could help me fix this. Thanks for making a great library!
Title: Re: Thor 2.0
Post by: Nexus on July 14, 2013, 05:20:59 pm
I don't directly see a mistake, but there are a lot of questionable things in the code. Can you reproduce the problem in a minimal and complete example (http://en.sfml-dev.org/forums/index.php?topic=5559.msg36368#msg36368)? Then it would be easier to see if you missed something obvious.

Maybe some tips regarding the use of Thor:
And some general C++ tips:
        if (m_usingTexture)
        {
            if (m_sprite.getGlobalBounds().contains(x, y))
                return true;
        }

        else if (!m_usingTexture)
        {
            if (m_text.getGlobalBounds().contains(x, y))
                return true;
        }

        return false;
This can be simplified a lot:
if (m_usingTexture)
    return m_sprite.getGlobalBounds().contains(x, y);
else
    return m_text.getGlobalBounds().contains(x, y);
The same applies to checkIfMouseClicked().

const bool CButton::checkIfMouseHovered(const float x, const float y) const
Don't overuse const. Only the last const is meaningful, the other three don't improve const-correctness. See here (http://en.sfml-dev.org/forums/index.php?topic=2767.msg18197#msg18197) for detailed explanation.

m_game.m_gameGUI.update(...);
It looks like the class of m_game is badly encapsulated, you shouldn't need to access its members directly. Maybe provide functions to hide the members.

void pushEvent(sf::Event& event) { m_eventMap.pushEvent(event); }
Since the parameter is not changed in the function, prefer using a reference to const: const sf::Event& event.

        CEventManager();
        ~CEventManager();
Defining constructor and destructor is not necessary, only do it if you need them. The rule of three (or five in C++11) should also be considered.

class CEventManager { enum EC_Events {...}; };
CEventManager::EC_Events::m_leftMouseButtonClicked
Accessing an enumerator via scope of the enum is unusual (in C++03 forbidden), since they are spread into the surrounding scope. CEventManager::m_leftMouseButtonClicked would be enough. But I don't think the m_ prefix is appropriate here; enumerators are constants, not member variables.

In general, the C prefix comes from an ancient idea (which was already wrong at that time) and shouldn't be used. See here (http://en.sfml-dev.org/forums/index.php?topic=9423.msg63949#msg63949) for more information.
Title: [Thor] New particle affector/emitter API
Post by: Nexus on July 19, 2013, 06:32:26 pm
New particle affector and emitter API

I have finally had time to work again on Thor, and I came up with a new design for particle emitters and affectors. Basically, as already announced long ago, I wanted to make affectors and emitters uniform with the animation API (http://en.sfml-dev.org/forums/index.php?topic=7329.msg53237#msg53237).

As a result, I have removed the following parts:
The affectors and emitters are now represented by function objects that have value semantics (like animations). This simplifies the usage a lot, as can be seen in the following example. First, the old API:
thor::UniversalEmitter::Ptr emitter = thor::UniversalEmitter::create();
emitter->setEmissionRate(30.f);
emitter->setParticleLifetime(sf::seconds(5.f));

thor::ParticleSystem system(texture);
system.addEmitter(emitter);
system.addAffector(thor::TorqueAffector::create(100.f));

With the new API, the indirect access via pointers and the factory functions are no longer necessary:
thor::UniversalEmitter emitter;
emitter.setEmissionRate(30.f);
emitter.setParticleLifetime(sf::seconds(5.f));

thor::ParticleSystem system(texture);
system.addEmitter(emitter);
system.addAffector(thor::TorqueAffector(100.f));

Instead of overwriting virtual functions affect() and emit(), a functor with overloaded operator() needs to be defined. As a nice side effect, this modification allows you to use lambda expressions to create emitters and affectors on-the-fly:
system.addAffector([] (thor::Particle& p, sf::Time dt)
{
    p.scale *= (1 - dt.asSeconds()); // shrinks particle over time
});

Shared ownership is no longer used. By default, function objects are copied to the particle system. If you need access to the original object after passing it to the particle system, it is possible to pass references using the functions thor::refAffector() and thor::refEmitter() -- again consistent with thor::refAnimation():
system.addEmitter(thor::refEmitter(emitter));
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 20, 2013, 12:24:57 am
Nice changes!

Arg why do you guys always change stuff, just as I've finished the new Nightly Builds! At least now it's really worth pushing out new builds for Thor. ;D
Title: Re: Thor 2.0
Post by: Nexus on July 20, 2013, 12:42:17 am
Just wait some time, there will probably be further changes soon :D

I don't think it matters to have always the most recent version. If it does, people are still able to pull from GitHub directly. In my opinion, your Nightly Builds do a very good job at giving users binaries in regular intervals -- but these intervals needn't correspond to single commits ;)
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 20, 2013, 12:53:25 am
Just wait some time, there will probably be further changes soon :D
*excited*

I don't think it matters to have always the most recent version. If it does, people are still able to pull from GitHub directly. In my opinion, your Nightly Builds do a very good job at giving users binaries in regular intervals -- but these intervals needn't correspond to single commits ;)
I know, then again all it takes for me is double clicking that build script and waiting till everything is finished... :D
Though I usually always look at the commit and decide on my own scale how important the change was.
Title: Re: Thor 2.0
Post by: FRex on July 21, 2013, 02:32:51 am
Are there any plans about changing something in Thor.Input?
Title: Re: Thor 2.0
Post by: Nexus on July 21, 2013, 12:33:29 pm
You can see the list of planned changes here (http://www.bromeon.ch/libraries/thor/progress.html).

For the Input module, the focus lies on two parts: Allowing more customization (for better support for input such as mouse wheel) and simplifying the API where possible.

The second point aims at action maps and callbacks, which now require rather a lot to set up:
thor::ActionMap<MyAction> map;
map[a] = ...;
map[b] = ...;  

thor::ActionMap<MyAction>::CallbackSystem system;
system.connect(a, &onA);
system.connect(b, &onB);

for (;;)
{
        map.update(window);
        map.invokeCallbacks(system, &window);
        ...
}
This is the most flexible way, as it allows multiple callback systems to be handled independently. I am not sure whether it's appropriate to have two separate classes ActionMap and ActionMap::CallbackSystem. One possibility would be to embed the latter into the former. But I still have to think about this...

Do you consider the current way user-friendly? Or would you like a different API?
Title: Re: Thor 2.0
Post by: FRex on July 22, 2013, 01:23:33 am
I'd say it's quite okay now. It's not really 'a lot' of set up code and amount of code to load/create actions and bind the callbacks and (possibly) filter events out from (sf)gui and push them manually will dominate over that little set up. It's nice that the functionality of several callback systems is there, it could get useful in a real app, like letting different menus, game modes, etc. have different callback systems but using same action map so for example: action esc in menu maps to back, in game maps to pause, wsad/arrows/whatever-is-in-settings works both for selecting options and movement in game etc.
Of course it'd be some performance hit to have all actions and callback attempts run all the time but it might be irrelevant because menus/options have time in their main loop to spare and most callback would belong to game class so it's actual overhead would be very little. I like the flexibility and the code is really not bloated or full of boilerplate. It couldn't really get much shorter: removing instancing of callback system and maybe invoking callbacks in update.
Title: Re: Thor 2.0
Post by: Hiura on July 23, 2013, 07:29:14 pm
I'm just throwing a thought here. I haven't had the chance to use Thor yet so take it carefully – maybe it doesn't apply at all.

A few years back, I used boost::program_options and I liked the way you can set it up :

po::options_description desc("Allowed options");
desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
;

Maybe something similar could be done (for the connect part) ?
Title: Re: Thor 2.0
Post by: vgambit on July 24, 2013, 04:25:28 am
Does Thor 2 work with SFML 2.0.0 or do I have to use the latest version from Git?
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 24, 2013, 12:10:27 pm
Since there are only bug-fixes and certainly not API change between SFML 2.0 and the latest Git version, Thor 2.0 does work with SFML 2 itself.
If you're on Windows you could also take a look at my Nightly Builds. ;)
Title: Re: Thor 2.0
Post by: Nexus on July 24, 2013, 01:31:34 pm
Thanks for the feedback, it's really appreciated!

It's nice that the functionality of several callback systems is there, it could get useful in a real app, like letting different menus, game modes, etc. have different callback systems but using same action map
That's a good example. Even if the callback systems are not used concurrently, one can switch between them.

A few years back, I used boost::program_options and I liked the way you can set it up [...] Maybe something similar could be done (for the connect part) ?
Interesting idea, but I'm not sure if the flexibility the operator() provides is needed for callback registrations -- these are all (key, function) pairs. I had such an API for the old color gradients, where you could specify an arbitrary amount of colors, but now I replaced it with something more expressive...
Title: Re: Thor 2.0
Post by: FRex on July 24, 2013, 02:55:22 pm
Boost API is sometimes quite WTF-inducing, chaining operator () or % for doing something very different than usual meaning of them.
Title: Re: Thor 2.0
Post by: Sonkun on August 10, 2013, 05:10:05 am
That's not a big deal but I noticed an unnecessary line in the StopWatch implementation. Line 74, it should work without the clock restart.

mClock.restart();
Title: Re: Thor 2.0
Post by: Nexus on August 10, 2013, 11:55:44 am
Indeed, thank you! :)
Title: [Thor] Vector projection + example
Post by: Nexus on August 11, 2013, 03:42:03 pm
I added the function thor::projectedVector() which returns the projection of a vector onto an other.

Additionally I wrote an example for the Vectors module, which shows some of the vector algebra functions (http://www.bromeon.ch/libraries/thor/v2.0/doc/_vector_algebra2_d_8hpp.html) in action: length(), signedAngle(), unitVector(), perpendicularVector(), rotatedVector() and projectedVector(). The class thor::Arrow is used to visualize the vectors.
Title: Re: Thor 2.0
Post by: Silvah on August 17, 2013, 07:20:19 pm
I found a while to rewrite it to make use of makepkg git support, so the AUR package (https://aur.archlinux.org/packages/thor-git/) is maintained again.
Title: Re: Thor 2.0
Post by: Nexus on August 17, 2013, 09:03:06 pm
Okay, good to know! Thanks!
Title: Re: Thor 2.0
Post by: FRex on August 21, 2013, 11:54:38 pm
I just noticed that stop watch reset and restart don't return elapsed time like clock does. Is that on purpose or oversight from time when clock didn't return time on restart too?
Title: Re: Thor 2.0
Post by: Nexus on August 22, 2013, 12:56:00 am
It's not only restart() and reset(); the member functions start() and stop() would have to return the elapsed time for consistency, too. In contrast to sf::Clock, the classes thor::StopWatch, thor::Timer and thor::CallbackTimer have many attributes (not just the time), so it is not immediately clear what the return type represents. Especially for timers, it may not be obvious that the returned value would be the remaining and not the elapsed time. That's why I prefer the explicit getters -- in most classes, modifiers and getters are separated anyway.

This might change in the future, but by keeping void for the moment, I'm not going to break any code, in case I should once find a more appropriate return type than the elapsed time.
Title: Re: Thor 2.0
Post by: Kojay on August 31, 2013, 07:01:19 pm
Is it necessary that thor::ParticleSystem be initialized with a sf::Texture, which in turn must have already been loaded? I find it impossible to have a system as member of a class without allocating it on the heap.
Title: Re: Thor 2.0
Post by: Nexus on September 01, 2013, 01:27:01 am
It's not strictly necessary -- I did it for the sake of class invariants.

However, as soon as I allow multiple textures or texture rects in a particle system, it will be possible to specify the texture later. I have planned to implement this feature, in order to allow variations of particles with a clear shape, such as debris.
Title: Re: [Thor] Vector projection + example
Post by: Lee R on September 01, 2013, 10:30:40 pm
I added the function thor::projectedVector() which returns the projection of a vector onto an other

You can get rid of the normalization step using the following definition (where a1 is the projection of a onto b):
(http://upload.wikimedia.org/math/a/d/9/ad92a17b245e925a2bff2e4444a520af.png)

template <typename T>
sf::Vector2<T> projectedVector(const sf::Vector2<T>& vector, const sf::Vector2<T>& axis)
{
    assert(axis != sf::Vector2<T>());
    return dotProduct(vector, axis) / squaredLength(axis) * axis;
}
Title: [Thor] Multiple particle variants
Post by: Nexus on September 02, 2013, 11:39:13 am
However, as soon as I allow multiple textures or texture rects in a particle system, it will be possible to specify the texture later.
Done. It is now possible specify different variants of a particle by using multiple texture rects:
thor::ParticleSystem system;
system.setTexture(texture);
system.addTextureRect(rect1);
system.addTextureRect(rect2);

As you see, the texture is specified later. If addTextureRect() is not called, the whole texture will be used. The particle class has a new member variable textureIndex that specifies which texture rect is used:
thor::Particle particle(...);
particle.textureIndex = 1; // use rect2

I also optimized the particle system a bit, such that it's not necessary to completely recompute 4 vertices from the texture rect for every particle every time.


You can get rid of the normalization step using the following definition (where a1 is the projection of a onto b)
Done. Thank you very much for the hint! :)
Title: [Thor] Animation tutorial
Post by: Nexus on October 16, 2013, 01:43:37 pm
I finally wrote a tutorial (http://www.bromeon.ch/libraries/thor/v2.0/tutorial-animation.html) about the Animation module. It will be extended over time :)
Title: Re: Thor 2.0
Post by: didii on November 27, 2013, 10:31:25 pm
If I would write the following
thor::UniversalEmitter emitter;
emitter.setParticleVelocity(thor::Distributions::uniform(-100.f,100.f));
for which the syntax is correct but will give an error wrong since thor::UniversalEmitter::setParticleVelocity needs a sf::Vector2<float> and thor::Distributions::uniform will return a float. When building, I get an error referring to
Code: [Select]
xrefwrap(431): error C2664: 'sf::Vector2<T>::Vector2(const sf::Vector2<T> &)' : cannot convert parameter 1 from 'float' to 'const sf::Vector2<T> &'which is quite confusing since you have no idea where the error comes from if you are not familiar with functors and/or Thor. Is there a possibility to separate the distributions according to their return type? Or is this error common while using functors?

I do have to note that I'm not familiar with functors and have no idea if it is possible at all. Also, I'm sorry if this has already been mentioned, I only did a very quick search on these 17 pages..



EDIT: I'm sorry, should have read 1 page more about functors before commenting here. So it does not seem possible to do this for which the compiler can notice the mistake from where it actually happens. It does seem to be possible to do this with functions though, but I can see the downsides of that.
Defining an abstract base template class won't work either since you are again stuck with the number of arguments... Is it really impossible to restrict the return types on functors? It seems so unlikely that you would accept and use a function without ever knowing which type it will return. Hoping that the user will use it correct is generally a bad practice...

EDIT2: oh, I used the most recent version of Thor btw right from your GitHub.
Title: Re: Thor 2.0
Post by: didii on November 28, 2013, 01:47:26 am
Now I feel embarrassed... So much mistakes were made from my side. I should now have found the problem, so let me rephrase everything.

When I give thor::UniversalEmitter::setParticleVelocity as input argument a thor::Distributions::uniform, the compiler accepts the argument and shows an error in xrefwrap instead. Below is a minimal working example. I have absolutely no idea why the compiler accepts a wrong input parameter. And I cannot seem to replicate it. I have already tried creating a uniform class/struct that inherits from Distribution<float>, getting the exact same error.

#include <Thor/Particles/Emitters.hpp>
#include <Thor/Math/Distributions.hpp>

int main() {
        thor::UniversalEmitter emitter;
        emitter.setParticleVelocity(thor::Distributions::uniform(-100.f,100.f));

        return 0;
}
Title: Re: Thor 2.0
Post by: Nexus on November 28, 2013, 08:59:26 am
I have absolutely no idea why the compiler accepts a wrong input parameter.
It does not accept it, otherwise there would be no error. With templates, there are mostly multiple error messages, each referring to a separate layer in the problematic call. If you scroll down, you will find the error in user code.

I agree that a compiler error in the depths of the std::function implementation is not ideal, but there's not much I can do about that. But even then, the first error message is quite expressive:
cannot convert argument 1 from 'float' to 'const sf::Vector2<float> &'

Is it really impossible to restrict the return types on functors? It seems so unlikely that you would accept and use a function without ever knowing which type it will return.
The return type is clear for a given function in the thor::Distributions namespace and for given argument types. In C++, a function cannot just return "anything", there's always a type.

Hoping that the user will use it correct is generally a bad practice...
I don't hope, I expect him to use it correctly... For some reason there is the documentation ;)
Title: Re: Thor 2.0
Post by: didii on November 28, 2013, 11:58:15 am
It does not accept it, otherwise there would be no error. With templates, there are mostly multiple error messages, each referring to a separate layer in the problematic call. If you scroll down, you will find the error in user code.
Indeed, in the 14th layer I can indeed see the referral to the main function :D So the actual 'problem' lies in the usage of different templates? Then probably Intellisense is also not made to look in such a depth. Thanks for clearing that up.

The return type is clear for a given function in the thor::Distributions namespace and for given argument types. In C++, a function cannot just return "anything", there's always a type.
Like I said in my second post. Disregard my first one, didn't see a lot of things. You indeed restrict its return type, but I thought, if you simply use
template <class C> void myFunc(C functor);
You are asking for any functor with any return type right? It just seems so unlikely for C++ to do such a thing. But if I now look at it, it's a template so you are in fact explicitly allowing it...

I don't hope, I expect him to use it correctly... For some reason there is the documentation ;)
Again, disregard my first post :)
Title: Re: Thor 2.0
Post by: Nexus on November 28, 2013, 01:15:55 pm
The problem is that you use Distribution<float> although Distribution<sf::Vector2f> is expected. std::function will still try to convert it somehow, leading to an error in its depths.

Note that he documentation of thor::Distribution<T> is simplified at that point, there's a lot of black magic going on behind the scenes. The actual constructors of thor::Distribution<T> are declared as follows, where AURORA_ENABLE_IF is a macro that activates the overload given the condition is true, according to SFINAE (https://en.wikipedia.org/wiki/SFINAE):
template <typename U>
Distribution(U constant
        AURORA_ENABLE_IF(std::is_convertible<U, T>::value));

template <typename Fn>
Distribution(Fn function
        AURORA_ENABLE_IF(!std::is_convertible<Fn, T>::value));

This is a very sophisticated way of overload resolution, but it allows me to differentiate between constants and functions passed to distributions. Ideally, I would just have two overloads that take T and std::function<T()>, however this doesn't work with implicit conversions. People expect to write emitter.setParticleRotation(90) although 90 is an int and not a float. So there would be two implicit conversions: int -> float -> Distribution<float>, and this is disallowed by the C++ standard.

Actually, that gives me an idea: I can extend these checks to create a clearer error message. But tinkering with black magic is always dangerous, I need to test some time. And that brings me to a general question: Should Distribution<T> be convertible to Distribution<U> if T is convertible to U (as it is now)? Or only explicitly? Hm... ???
Title: Re: Thor 2.0
Post by: didii on December 02, 2013, 04:05:58 pm
Should Distribution<T> be convertible to Distribution<U> if T is convertible to U (as it is now)? Or only explicitly? Hm... ???
In my opinion it's always more safe to only use explicit conversions. I like the way current C conversions happen: allow it, but display a (compiler) warning. But I suppose this is impossible without altering the compiler.
Allowing the conversion gives the user a more freedom and less tedious (and in a lot of cases unnecessary) conversions, but this does withhold users who are newer to C++ to learn that there is an actual difference between writing 90, 90. and 90.f. So it's your target audience or the reason behind the creation of Thor that matters I suppose.
Title: Re: Thor 2.0
Post by: Nexus on December 02, 2013, 07:30:25 pm
In my opinion it's always more safe to only use explicit conversions.
Thanks for the input! Generally, I share this opinion, but I thought about it again and found a very important argument:

If I allow a Distribution<T> to be initialized with a function with return type U (convertibility given), I must allow conversions from Distribution<U> to Distribution<T> as well, because distributions are functors like any other.

The only alternative would be to completely forbid functors whose types don't match exactly the distribution's declaration type. This might not only be too restrictive, but it contradicts the way how conversions are handled in C++ (std::function and between basic types). The following code is fine:
std::function<int()> f = [] () { return 4l; };

Requiring explicit conversions would probably confuse a lot of people. thor::Distribution is just a thin wrapper around std::function, and it interacts with basic types very closely. It doesn't introduce unexpected or dangerous conversions, only those that would already be possible if a distribution object were a value (in other words: the expected ones). That's why I'm leaving the implicit conversions as they are.
Title: [Thor] New joystick actions
Post by: Nexus on December 04, 2013, 11:41:44 pm
Changes in Joystick API

First, there were some renamings for the sake of clarity and expressiveness:
Second, and this is the important part, I added the class thor::JoystickAxis. Similar to thor::JoystickButton, it represents the state of a joystick axis as it is used for the action system. The class thor::Action was extended by an additional constructor for joystick axes.

What you can do now is associate an action with a joystick threshold exceedance. For example, if you want to react to a Y axis position of joystick 0 above 25%, you can now do this:
thor::Action action(thor::joy(0).axis(sf::Joystick::Y).above(25.f));

There is also a below() function for the less-than relation. This syntax is similar to the existing one for buttons ("is button 2 of joystick 0 pressed?"):
thor::Action action(thor::joy(0).button(2));
Title: Re: Thor 2.0
Post by: Lolilolight on December 12, 2013, 08:29:54 pm
The project seems to be interessant but some things in the that library are too complexe for me. (and unflexible)
By example : the resource system. :S

A resource holder with a simple template and an identifier which is stored into a multi-cache (by using a transtypage from the typename to a void* (type erasure) into a container like a vector or a map) should do the trick.

So you can add any fonctions that you want in the resource manager class without forcing the developper to use a shared pointer and a specific fonction/identifier to load a resource. :)

Example :
load (resource, identifier) instead of key = ...




Title: Re: Thor 2.0
Post by: Nexus on December 12, 2013, 08:38:31 pm
I know -- I frequently state that thor::ResourceCache shouldn't be overused, it is for special cases with shared ownership and automatic duplicate recognition. In cases where these features are required, it is really powerful, which comes at a cost for simpler use cases.

As you can see here (http://www.bromeon.ch/libraries/thor/progress.html), a more lightweight alternative to thor::ResourceCache is already planned :)
Title: Re: Thor 2.0
Post by: Lolilolight on December 13, 2013, 10:42:51 am
Ok, it's nice because, in my system I don't need duplicate recognition and shared ownership. :)

I simply need something like this : (The resource manager contains 1 or several resources, and, the cache contains the resource managers, so the resource manager is also the key.)

//Declaration and resources loading.
ResourceManager<Texture> text1;
text1.load("path1");
ResourceManager<Texture> text2;
text2.load("path2");
//Add the resources to the cache.
Cache cache;
cache.add<Texture>(text1);
cache.add<Texture>(text2);
//Get a resource from the cache by his variable name.
const Texture* text = cache.get<Texture>(text1);
//Retrive the path to the ressource. (To save them in a file later)
vector<string> paths = cache.getPaths();
 

Or, a second method is also possible, if he wants to use a string (with one texture manager for each textures) :

//Declaration and resources loading.
ResourceManager<Texture> textures;
textures.load("path1", "alias1");
textures.load("path2", "alias2");
//Add the resources to the cache.
Cache cache;
cache.add<Texture>(textures);
//Get a resource from the cache by his alias.
const Texture* text = cache.get<Texture>("alias1");
//Retrive the path to the ressource. (To save them in a file later)
vector<string> paths = cache.getPaths();
 

The inconvenient of the second method is that if he mistakes the string name it'll crash at the execution.
The advantage is that he don't have to keep the resource manager name to get the resource.

In the first method, this is juste the inverse : It'll won't compile if he mistakes the variable name but he must keep the variable name to retrieve the resource.
Title: Re: Thor 2.0
Post by: The Terminator on December 14, 2013, 12:31:01 am
Hi there, I wanted to adapt my GUI classes (mainly buttons and radioboxes) to the callback systems on thor, but unfortunately the "Connecting callbacks" tutorial does not compile on GCC 4.7.1. I have heard there are bugs on passing references to functions, is this true? Or is there a problem with thor?
Title: Re: Thor 2.0
Post by: Nexus on December 14, 2013, 12:45:53 am
Hi there, I wanted to adapt my GUI classes (mainly buttons and radioboxes) to the callback systems on thor, but unfortunately the "Connecting callbacks" tutorial does not compile on GCC 4.7.1. I have heard there are bugs on passing references to functions, is this true? Or is there a problem with thor?
I assume you're referring to the Actions tutorial.

Can you show a minimal and complete code example with the corresponding error message?
Title: Re: Thor 2.0
Post by: The Terminator on December 14, 2013, 06:09:34 pm
Yes I am. Here's a small snippet from my own engine:

Button.hpp:

    class Button : public GUIObject
    {
    public:
        enum class Button_Actions
        {
            CLICKED
        };

        Button(const std::string& textString, const std::string& fontPath, const sf::Vector2f pos,
                    int charSize, const sf::Color& defaultColor, const sf::Color& activatedColor,
                     bool alwaysDraw);

        void onClick(thor::ActionContext<Button_Actions> context)
        {
            std::cout << "test" << std::endl;
        }

    protected:
        thor::ActionMap<Button_Actions> m_map;
        thor::ActionMap<Button_Actions>::CallbackSystem m_system;

    };

Button.cpp:

    Button::Button(const std::string& textString, const std::string& fontPath, const sf::Vector2f pos,
                   int charSize, const sf::Color& defaultColor, const sf::Color& activatedColor,
                   bool alwaysDraw) :
    GUIObject(pos),
    m_defaultColor(defaultColor),
    m_activatedColor(activatedColor)
    {
        m_map[Button_Actions::CLICKED] = (thor::Action(sf::Mouse::Left, thor::Action::PressOnce));

        m_system.connect(Button_Actions::CLICKED, &Button::onClick);
    }

Running this will give me an error of:
c:\program files (x86)\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\functional|2013|error: no match for call to '(std::_Mem_fn<void (SE::Button::*)(thor::ActionContext<SE::Button::Button_Actions>)>) (const thor::ActionContext<SE::Button::Button_Actions>&)'|

It also opens up the functional file and points to an error on line 2013.
Title: Re: Thor 2.0
Post by: Nexus on December 14, 2013, 07:35:38 pm
The signature must be
void onClick(thor::ActionContext<Button_Actions> context)
however at you it is
void Button::onClick(thor::ActionContext<Button_Actions> context)
You are passing a member function pointer instead of a function pointer.

An easy fix is to make onClick() static. If it needs access to other members, you can bind the member function to the object:
std::bind(&Button::onClick, this, _1)
Title: Re: Thor 2.0
Post by: The Terminator on December 14, 2013, 08:48:16 pm
The signature must be
void onClick(thor::ActionContext<Button_Actions> context)
however at you it is
void Button::onClick(thor::ActionContext<Button_Actions> context)
You are passing a member function pointer instead of a function pointer.

An easy fix is to make onClick() static. If it needs access to other members, you can bind the member function to the object:
std::bind(&Button::onClick, this, _1)

Thanks! It works now.
Title: Re: Thor 2.0
Post by: didii on December 15, 2013, 12:32:07 pm
Hi,

Is it possible to use the thor::ActionMap::isActive function as
sf::RenderWindow window(...);
thor::ActionMap<std::string> action_map;

// gameloop
while (window.isOpen()) {
    action_map.update(window);
    if (action_map.isActive(thor::Action(...)) // <- this
        // do stuff
}

If I want for example to pass the thor::ActionMap to an object to access all occurred events, it seems a bit of a detour to add it to the list of actions, assign a random key value for it, and then check for the random key.
I also saw the object thor::detail::EventBuffer on the ActionMap. I suppose that is the container holding all events? It doesn't seem possible to pass that one as an argument either.
Title: Re: Thor 2.0
Post by: Nexus on December 15, 2013, 01:05:42 pm
If I want for example to pass the thor::ActionMap to an object to access all occurred events, it seems a bit of a detour to add it to the list of actions, assign a random key value for it, and then check for the random key.
The idea of the action map and the actions is to abstract from underlying SFML events and realtime input. With thor::ActionMap, you don't test anymore if the Space key is pressed, instead you test whether the Shoot action is active. This allows you to re-map keys easily, and you can even add combinatoric expressions of multiple actions ("Space or Shift and X").

When you need to find a random ID to register your action, you are bypassing this abstraction mechanism and could (more or less) as well poll SFML events directly. Since the action you want to pass is associated with specific game logic (such as "shoot" or "jump" or "quit application"), it should be possible to find a meaningful ID.

I also saw the object thor::detail::EventBuffer on the ActionMap. I suppose that is the container holding all events? It doesn't seem possible to pass that one as an argument either.
As the namespace detail suggests, this is an implementation detail and not part of the public API.
Title: Re: Thor 2.0
Post by: didii on December 15, 2013, 10:16:44 pm
The idea of the action map and the actions is to abstract from underlying SFML events and realtime input. With thor::ActionMap, you don't test anymore if the Space key is pressed, instead you test whether the Shoot action is active. This allows you to re-map keys easily, and you can even add combinatoric expressions of multiple actions ("Space or Shift and X").
Yes, I think I do understand that part of the thor::ActionMap.
But let me rephrase my question, since I'm bad with words... How would I use a thor::ActionMap if I want event handling in different places, such as inside the main loop (pauze menu, command window, ...) and one or more objects (such as the player (shoot, move, ...) or even multiple players).

I could give them all a thor::ActionMap and use thor::ActionMap::pushEvent, but then I would have multiple identical event containers. I could also handle all events inside the main loop, but then I could be checking for inputs that aren't used. I like having an object where I only need to call his update-function and it can manage itself.

I also might have an inefficient design and could have overlooked many things. But I don't (yet) see a better way of handling events efficiently.
Title: Re: Thor 2.0
Post by: Nexus on December 15, 2013, 11:35:28 pm
In general, you should try to keep responsibilities separate and modular. Game entities should not know about SFML events like "space key pressed", but they can know about high-level actions such as "shoot" or "jump". One possibility is to feed them with actions:
void Entity::HandleAction(const std::string& highlevelAction);
They can also get passed actions in their update step:
void Entity::Update(const std::vector<std::string>& actions);
Instead of strings, it's of course possible to use Action structures with more associated information.

You can make the separation more strict, in this case entities are not aware of input at all. They just provide corresponding member functions that are invoked by another class (the world containing them, for example).
void World::Update()
{
    if (mActionMap.isActive("Shoot"))
        mPlayer.Shoot();
}

Furthermore, a quite important feature that thor::ActionMap provides are callbacks. They allow to dispatch messages indirectly and reduce dependencies between modules. For example, in the World constructor you can register the callbacks.
typedef thor::ActionMap<std::string> ActionMap;

class World
{
    ActionMap::CallbackSystem   mCallbacks;
    Player                      mPlayer;
public:
    World()
    {
        auto shootFn = [this] (thor::ActionContext<MyAction> /*unused*/)
        {
            mPlayer.Shoot();
        };

        mCallbacks.connect("shoot", shootFn);
    }

    void HandleInput(const ActionMap& map, sf::RenderWindow& window)
    {
        map.invokeCallbacks(mCallbacks, &window);
    }
};

To get back to your initial question: When you have multiple places like menus and the game, it can be worthwhile to have one central ActionMap and multiple CallbackSystems (one per menu/game). With this approach, you can react to the same events differently in different application states. In the code above, a central class Application could then invoke World::HandleInput() with its action map and window.

As you see, there are many different approaches, with advantages and disadvantages. It depends on how you structure and design your game, and also a bit on personal preferences.
Title: Re: Thor 2.0
Post by: Lolilolight on December 20, 2013, 12:53:38 pm
I have a question : can we only load resources from file with thor ?

I saw that we can use the fonction fromFile for the key of the resource but how does it work if I need to load a resource from the memory by example ?

How does it work if we need to use different kinds of functions to load resources ?

PS : I have another question, std::bind can return every kind of function ?

I think I'll use it. *-*

Title: Re: Thor 2.0
Post by: eXpl0it3r on December 20, 2013, 02:21:42 pm
You should read the tutorial for resources (http://www.bromeon.ch/libraries/thor/v2.0/doc/namespacethor_1_1_resources.html), it's nicely explained there.
You can use different resource key factories, see here (http://www.bromeon.ch/libraries/thor/v2.0/doc/namespacethor_1_1_resources.html).
Title: [Thor] Custom actions, simpler callback registration
Post by: Nexus on December 23, 2013, 10:26:26 pm
I worked again on the Input module. Besides large internal simplifications and refactorings of the action resolution system, the following parts have changed:


1. Custom actions

It is now possible to bind user-defined actions to thor::Action. That is, you can not only combine existing action types with the boolean operators, but define yourself when an action is considered active. For this purpose, two factory functions thor::eventAction() and thor::realtimeAction() have been added. These take functors that return a bool whenever an action is supposed to be active.

For example, you can react specifically to every event, or once per frame to a realtime condition:
bool enteredLowerH(const sf::Event& event)
{
    return event.type == sf::Event::TextEntered && event.text.unicode == 'h';
}

bool joystickConnected()
{
    return sf::Joystick::isConnected(1);
}

thor::Action a = thor::eventAction(&enteredLowerH);
thor::Action b = thor::realtimeAction(&joystickConnected);

As you see, the realtime action is not directly linked to SFML, so you can also use it to check other states in your application.


2. Simpler callback registration


The two classes thor::EventSystem and thor::CallbackTimer allow you to register callbacks through the connect() function:
void listener(thor::CallbackTimer& trigger)
{
    std::cout << "expired" << std::endl;
    trigger.restart(sf::seconds(1.f));
}

thor::CallbackTimer timer;
timer.connect(&listener);

These callbacks take the instance that triggered them as a parameter. While this is useful in the above example, there are many cases where you just want to perform an action and don't care about the source. That is why I added the additional member functions connect0(), where 0 stands for "nullary" (meaning the function takes no arguments). Unfortunately I can't overload connect() because of ambiguities, at least not without a lot of black TMP magic.

An implication of this change is that the functions registered at thor::ActionMap::CallbackSystem do not need to carry a unused thor::ActionContext parameter. Instead of
void listener(thor::ActionContext<MyAction> context);

thor::ActionMap<MyAction>::CallbackSystem system;
system.connect(ActionXY, &listener);
you can now omit the parameter:
void listener();

thor::ActionMap<MyAction>::CallbackSystem system;
system.connect0(ActionXY, &listener);


3. API changes


The named-parameter-idiom function thor::joy() has been renamed to thor::joystick() for clarity.

The member typedefs Listener of thor::CallbackTimer and thor::EventSystem have been removed, and the connect() and connect0() parameters are written directly as std::function<...> instead of Listener. I hope that, by omitting this abstraction, it is clearer how the signature of the callbacks has to look.
Title: Re: Thor 2.0
Post by: zsbzsb on December 23, 2013, 10:45:44 pm
Looks good, but now I need to go update NetEXT  :P
Title: Re: Thor 2.0
Post by: Nexus on December 23, 2013, 11:41:41 pm
True, however the implementation is simpler than before ;)

And it's still possible to reduce the amount of code in the current implementation by using thor::eventAction() and thor::realtimeAction() even for built-in actions, so there would only be a few node classes. But at the moment, these functions incur additional overhead because of the std::function indirection. One way to mitigate this is are template parameters for the functors.

Bottom line: Concerning internal refactorings, don't be too eager to adapt them always immediately.
Title: Re: Thor 2.0
Post by: Carlitox on December 25, 2013, 03:06:54 am
Hello I'm new with this library and in the forum. I cannot see the option to insert code.


I'm dealing with the particle system and learning all about it. I read that you can create your own distributions and apply it to the particles properties like the lifetime, rotation, position, etc.

For example:


thor::UniversalEmitter emitter;
emitter.setParticleLifetime(thor::Distributions::uniform(sf::seconds(1.f), sf::seconds(3.f)));


I tried to make the same but with my own distribution following the documentation.


unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 engine(seed);
std::uniform_real_distribution<float> distr(1.f, 3.f);
auto randomizer = std::bind(distr, engine);
thor::Distribution<float> thorDistr(randomizer);

thor::UniversalEmitter emitter;
emitter.setParticleLifetime(sf::seconds(thorDistr()));

 

This solution gives the same lifetime to all the particles, therefore it fails.

I think that I must use something like this but the library doesn't allow to do it or maibe I don't know how to implement it correctly:



unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 engine(seed);
std::uniform_real_distribution<float> distr(1.f, 3.f);
auto randomizer = std::bind(distr, engine);
thor::Distribution<sf::Time> thorDistr(randomizer);

thor::UniversalEmitter emitter;
emitter.setParticleLifetime(thorDistr().asSeconds());

 

Do you how I can implement it?
Title: Re: Thor 2.0
Post by: Nexus on December 25, 2013, 12:49:45 pm
Your mistake is that you pass a constant; the following expression does not yield a functor. So the result will always be the same.
sf::seconds(thorDistr())

The function sf::seconds() takes a float and it returns a sf::Time object, so you can't simply convert a uniform float distribution to a sf::Time distribution. You need to write your own functor:
struct Randomizer
{
    Randomizer()
    : distr(1.f, 3.f)
    , engine(mySeed)
    {
    }

    sf::Time operator() () const
    {
        return sf::seconds(distr(engine));
    }

    std::uniform_real_distribution<float> distr;
    std::mt19937 engine;
};

You can then pass such a function object to the emitter:
emitter.setParticleLifetime(Randomizer());

It would also be possible to achieve the same using a lambda expression. By the way, the C++ code can be inserted using the rightmost dropdown field with "Code".
Title: Re: Thor 2.0
Post by: Carlitox on December 25, 2013, 03:38:30 pm
Thank you, it works. I tried to do the same with lambda and works as well.

auto randomizer_lambda =
[]()
{
        std::uniform_real_distribution<float> distr(1.f, 3.f);
        std::mt19937 mt(std::chrono::system_clock::now().time_since_epoch().count());
        return sf::seconds(distr(mt));
};

emitter.setParticleLifetime(randomizer_lambda);
Title: Re: Thor 2.0
Post by: Nexus on December 25, 2013, 03:51:11 pm
That's not how you should do it. You create a new engine and distribution every time the functor is invoked. Thus, the random number generator is useless.

Pass both distribution and engine as reference in the lambda's capture clause (or simply use the functor class I showed you).
Title: Re: Thor 2.0
Post by: Carlitox on December 25, 2013, 04:40:52 pm
Now I avoid the unnecesary copies.

std::mt19937 mt;
std::uniform_real_distribution<float> distr(1.f, 3.f);

auto randomizer_lambda = [&distr, &mt]
{
        return sf::seconds(distr(mt));
};

thor::UniversalEmitter emitter;
emitter.setParticleLifetime(randomizer_lambda);

 
Title: [Thor] Arrow style, fewer shapes
Post by: Nexus on December 28, 2013, 05:11:48 pm
The class thor::Arrow has been extended with a style attribute. It can not only be used as an arrow, but also as a line. I will probably add support for bidirectional arrows in the future. To clarify the graphical differences:
line       -----
arrow      ---->
bd. arrow  <--->

The function thor::Shapes::pie() has been removed because I considered the pie shape too specific. I wanted to remove thor::Shapes::line() as well, because lines can now be expressed as arrows, but I think it may be useful for those who only need a sf::ConvexShape and not a whole arrow object.
Title: Re: Thor 2.0
Post by: iride on January 03, 2014, 03:35:02 am
I want particles to have random color. How can I do that using UniversalEmitter::setParticleColor?
Title: Re: Thor 2.0
Post by: Nexus on January 03, 2014, 02:25:25 pm
It's very simple, you can pass a function pointer to setParticleColor(). It is then converted to a thor::Distribution<sf::Color>.
// Your function that creates a random color
sf::Color randomColor();

thor::UniversalEmitter emitter;
emitter.setParticleColor(&randomColor);
Title: Re: Thor 2.0
Post by: Raincode on January 05, 2014, 01:49:01 pm
Hi,
I ran cmake and then tried building Thor with mingw32-make install, and got errors. I seriously don't know what they mean, maybe someone can decypher them for me and tell me what the problem is, please?#

D:\Thor\Thor-master\src\Particle.cpp: In function 'float thor::getElapsedRatio(const thor::Particle&)':
D:\Thor\Thor-master\src\Particle.cpp:62:38: error: no match for 'operator/' (operand types are 'sf::Time' and 'sf::Time')
  return getElapsedLifetime(particle) / getTotalLifetime(particle);
                                      ^
D:\Thor\Thor-master\src\Particle.cpp:62:38: note: candidates are:
In file included from D:/SFML-2.1/include/SFML/System/Vector2.hpp:250:0,
                 from D:/Thor/Thor-master/include/Thor/Particles/Particle.hpp:35,
                 from D:\Thor\Thor-master\src\Particle.cpp:26:
D:/SFML-2.1/include/SFML/System/Vector2.inl:131:19: note: template<class T> sf::Vector2<T> sf::operator/(const sf::Vector2<T>&, T)

 inline Vector2<T> operator /(const Vector2<T>& left, T right)
                   ^
D:/SFML-2.1/include/SFML/System/Vector2.inl:131:19: note:   template argument deduction/substitution failed:
D:\Thor\Thor-master\src\Particle.cpp:62:65: note:   'sf::Time' is not derived from 'const sf::Vector2<T>'
  return getElapsedLifetime(particle) / getTotalLifetime(particle);
                                                                 ^
In file included from D:/Thor/Thor-master/include/Thor/Particles/Particle.hpp:34:0,
                 from D:\Thor\Thor-master\src\Particle.cpp:26:
D:/SFML-2.1/include/SFML/System/Time.hpp:376:22: note: sf::Time sf::operator/(sf::Time, sf::Int64)
 SFML_SYSTEM_API Time operator /(Time left, Int64 right);
                      ^
D:/SFML-2.1/include/SFML/System/Time.hpp:376:22: note:   no known conversion for argument 2 from 'sf::Time' to 'sf::Int64 {aka lon
g long int}'
D:/SFML-2.1/include/SFML/System/Time.hpp:364:22: note: sf::Time sf::operator/(sf::Time, float)
 SFML_SYSTEM_API Time operator /(Time left, float right);
                      ^
D:/SFML-2.1/include/SFML/System/Time.hpp:364:22: note:   no known conversion for argument 2 from 'sf::Time' to 'float'
D:\Thor\Thor-master\src\Particle.cpp: In function 'float thor::getRemainingRatio(const thor::Particle&)':
D:\Thor\Thor-master\src\Particle.cpp:67:40: error: no match for 'operator/' (operand types are 'sf::Time' and 'sf::Time')
  return getRemainingLifetime(particle) / getTotalLifetime(particle);
                                        ^
D:\Thor\Thor-master\src\Particle.cpp:67:40: note: candidates are:
In file included from D:/SFML-2.1/include/SFML/System/Vector2.hpp:250:0,
                 from D:/Thor/Thor-master/include/Thor/Particles/Particle.hpp:35,
                 from D:\Thor\Thor-master\src\Particle.cpp:26:
D:/SFML-2.1/include/SFML/System/Vector2.inl:131:19: note: template<class T> sf::Vector2<T> sf::operator/(const sf::Vector2<T>&, T)

 inline Vector2<T> operator /(const Vector2<T>& left, T right)
                   ^
D:/SFML-2.1/include/SFML/System/Vector2.inl:131:19: note:   template argument deduction/substitution failed:
D:\Thor\Thor-master\src\Particle.cpp:67:67: note:   'sf::Time' is not derived from 'const sf::Vector2<T>'
  return getRemainingLifetime(particle) / getTotalLifetime(particle);
                                                                   ^
In file included from D:/Thor/Thor-master/include/Thor/Particles/Particle.hpp:34:0,
                 from D:\Thor\Thor-master\src\Particle.cpp:26:
D:/SFML-2.1/include/SFML/System/Time.hpp:376:22: note: sf::Time sf::operator/(sf::Time, sf::Int64)
 SFML_SYSTEM_API Time operator /(Time left, Int64 right);
                      ^
D:/SFML-2.1/include/SFML/System/Time.hpp:376:22: note:   no known conversion for argument 2 from 'sf::Time' to 'sf::Int64 {aka lon
g long int}'
D:/SFML-2.1/include/SFML/System/Time.hpp:364:22: note: sf::Time sf::operator/(sf::Time, float)
 SFML_SYSTEM_API Time operator /(Time left, float right);
                      ^
D:/SFML-2.1/include/SFML/System/Time.hpp:364:22: note:   no known conversion for argument 2 from 'sf::Time' to 'float'
src\CMakeFiles\thor.dir\build.make:465: recipe for target 'src/CMakeFiles/thor.dir/Particle.cpp.obj' failed
mingw32-make[2]: *** [src/CMakeFiles/thor.dir/Particle.cpp.obj] Error 1
CMakeFiles\Makefile2:77: recipe for target 'src/CMakeFiles/thor.dir/all' failed
mingw32-make[1]: *** [src/CMakeFiles/thor.dir/all] Error 2
Makefile:115: recipe for target 'all' failed
mingw32-make: *** [all] Error 2
 

Kind Regards
Title: Re: Thor 2.0
Post by: Nexus on January 05, 2014, 01:56:13 pm
You must use the latest SFML revision from GitHub. operator/ for sf::Time was a relatively recent addition.
Title: Re: Thor 2.0
Post by: Raincode on January 05, 2014, 02:38:55 pm
Ah ok, thanks. Know I at least understand what's going on

Know it gives me "Unsupported architecture" when trying to use cmake on sfml,  guess I'll still habe to try a bit or use a slightly older version of thor



Title: Re: Thor 2.0
Post by: zachprinz on January 07, 2014, 03:39:38 am
Hey, I'm not sure how much this has to do with Thor but I'm having a wierd problem with the library.

I've build and installed the latest GitHub versions of both SFML and Thor for VS11 using Cmake, but get this error when trying to run your example "particle.cpp" after linking the created libs for the aforementioned libraries.

(http://i.imgur.com/4IsrLWf.png?1)

I know this usually happens when there's a mismatch between what was linked to and the dll, or a mismatch in the IDE the libraries libs were compiled for but both SFML and Thor were compiled for VS11.

Anyways, I figured I'd post and see if anyone would know whats happening.

Thanks.

EDIT: I just build static libs for sfml and thor and that works fine.
Title: AW: Thor 2.0
Post by: eXpl0it3r on January 07, 2014, 07:29:26 am
The error means that you have a library mismatch, i.e. you used different libraries to build your application, than the dlls you have providee.
Title: Re: Thor 2.0
Post by: Lolilolight on January 07, 2014, 05:36:02 pm
In your resource system you should use a variable who accepts any kind of function type to load the resources. (It's what I was trying to say earlier)

And, you should use a simplified system for your callback system, and get rid of the context, to do something lie this :
//Store a function pointer to a member function and pass an objet to call the function later.
Function <void(MyAppli&, Vector2f)> (&function, &object);
//Create and store the signal and the slot.
System::connect<Function<void(MyAppli&, Vector2f)>>("IsMouseInsideRect",  func);
//Call the
 

The interest is that the second parameter of the connect method can be any kind of function objects who call a pointer to a function.

I had juste to write a class who store a pointer to a non member function  wich call a pointer to any king a function. (I had to do this because we can't store the adress of object members functions.)
This class can also store the value of the arguments if it's necessary.

To call the signal, you just have to write the kind of the function pointer in <> :
System::emit<Function<void(MyAppli&, Vector2f)>>("IsMouseInsideRect",  mousePos);
 

The class system use the type erasure to store a generic pointer to the slot, and to cast the generic pointer into the slot type at the execution when we need to call it.

The same mecanism can be applied for actions, you can create an action, passing them a slot, and, link the slot to one or more sf::event throw the action, I've event set a map who link to sf::even, one event to trigger the action, and another event to terminate the action, but, I need to still improve the code, the template syntax is a bit barabare, and I need to redefine the operator || and && like you do in your class action map :

moveAction = new Action<Slot<void, Function<void(MyAppli&, sf::Keyboard::Key, sf::Time)>>> (slot2, false);
        sf::Event endEvent1, endEvent2, endEvent3, endEvent4;
        sf::Event event1, event2, event3, event4;
        event1.type = sf::Event::KeyPressed;
        event1.key.code = sf::Keyboard::Key::Z;
        event2.type = sf::Event::KeyPressed;
        event2.key.code = sf::Keyboard::Key::Q;
        event3.type = sf::Event::KeyPressed;
        event3.key.code = sf::Keyboard::Key::S;
        event4.type = sf::Event::KeyPressed;
        event4.key.code = sf::Keyboard::Key::D;

        endEvent1.type = sf::Event::KeyReleased;
        endEvent1.key.code = sf::Keyboard::Key::Z;
        endEvent2.type = sf::Event::KeyReleased;
        endEvent2.key.code = sf::Keyboard::Key::Q;
        endEvent3.type = sf::Event::KeyReleased;
        endEvent3.key.code = sf::Keyboard::Key::S;
        endEvent4.type = sf::Event::KeyReleased;
        endEvent4.key.code = sf::Keyboard::Key::D;
        moveAction->linkEvents(event1, endEvent1);
        moveAction->linkEvents(event2, endEvent2);
        moveAction->linkEvents(event3, endEvent3);
        moveAction->linkEvents(event4, endEvent4);
 

To call the slot you just need to call the process method of the action class (and you can pass some params if it's necessary) :

 if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased) {
                moveAction->pushEvent(event);
                View view = getWindow().getView();
                moveAction->process(event.key.code,realTime.restart());
 


But except that 2 defaults that I've still to improve (the template writting and the redefinition of the operator && and ||) I find that this code is perfect.

A macro should do the trick.  :)

But I think you can easely simplify the action mecanism and the resource loading mecanism of the thor library by this way, because, if we can pass any kind of fonction pointer to the resource system, you don't have to redefine the key for loading the resource, and, you don't need to pass by class such contexts to access to the window. (It's often the cause of many crashes and environnement problems, then I prefer pass the render windw to a function)

To finish my discution, I think I'll even do a placeholder system, to replace some arguments before calling the slot. (and not always the whole argument list)
If I an find a way to pass references into a tuple, it would be nice too. (But I think that the lvalues and std::forwad should solve the problem)

PS : The new c++11 functionnalities seems to be powerfull!  :D


Title: Re: Thor 2.0
Post by: Nexus on January 07, 2014, 08:17:59 pm
Lolilolight, there is connect0() for exactly that.

But we discussed resource managers and callbacks almost to death in the French thread (http://fr.sfml-dev.org/forums/index.php?topic=13719.msg96902#msg96902). Please don't start again, especially not in this thread. Furthermore, I already stated several times that I will reflect about a different (simpler) design for resource management in Thor, so please just be patient...
Title: Re: Thor 2.0
Post by: Lolilolight on January 08, 2014, 10:23:52 am
Ok.  :)

I think I'll rewritte the SFML event with a flag system for my class action. (Because I cannot store the Actions because they are on different types)
I can get rid of the ActionMap so. (I find that it's very unplaisant to recreate an action, for each SFML events)

But I didn't want to discuss again about that in this thread anymore.





Title: Re: Thor 2.0
Post by: kingcools on January 11, 2014, 01:56:18 am
Hi, im trying to download and install the thor framework yet my winrar always tells me the archives are damaged.
This happens everytime i try to download the thor 1.1 sdk for example (tried other links as well)
Title: Re: Thor 2.0
Post by: Nexus on January 11, 2014, 08:52:08 am
I reuploaded all the archives, should be fine now.

Anyway, I recommend using the latest Thor revision from GitHub rather than Thor 1.1, see also this post (http://en.sfml-dev.org/forums/index.php?topic=14111.msg98899#msg98899).
Title: Re: Thor 2.0
Post by: kingcools on January 11, 2014, 05:52:33 pm
Hi,

thank you for the reupload, even though i used the github version as a substitute in the meantime :P

One critique:
When building the (thor-)project it would be better or at least more convenient if cmake would create a makefile that in return would build all of the project in the same folder.
After the build process i still had the include/cpp files in the download folder, though it would be nice if those were in the chosen buildfolder (thats how it is with sfml for example).

edit:
Good job by the way, your lib looks very useful!
one question: are you the same nexus that is on the c++-forum? if so, thanks for your help there haha
Title: Re: Thor 2.0
Post by: eXpl0it3r on January 11, 2014, 06:06:02 pm
When building the (thor-)project it would be better or at least more convenient if cmake would create a makefile that in return would build all of the project in the same folder.
You should always build/make the install project, i.e. make install -j4. That way everything will be install to the path specified via CMAKE_INSTALL_PREFIX.

one question: are you the same nexus that is on the c++-forum? if so, thanks for your help there haha
Yes, that's also him. ;)
Title: Re: Thor 2.0
Post by: kingcools on January 11, 2014, 06:23:32 pm
Thank you expl0it3r, learned something new there :)
Title: Re: Thor 2.0
Post by: Nexus on January 11, 2014, 06:27:34 pm
Thank you expl0it3r, learned something new there :)
It's not as if it weren't mentioned in the tutorial (http://www.bromeon.ch/libraries/thor/v2.0/tutorial-installation.html) with a red IMPORTANT subtitle :P
(Even if it's written for SFML, for Thor the same applies)
Title: Re: Thor 2.0
Post by: Lolilolight on January 11, 2014, 09:27:46 pm
I don't know wich compiler you use but this code don't compile :

Action& operator[] (const I& id) {
        return actions[id];
}
 

Code: [Select]
D:\Projets\Projets-c++\TestSFGL\myApplication.h|123|error: invalid types 'ActionMap<std::basic_string<char> >[const char [13]]' for array subscript|
Title: Re: Thor 2.0
Post by: The Terminator on January 12, 2014, 01:17:23 am
Hi there Nexus,

Is there a way to do this:

thor::Action left_press(sf::Mouse::Left, thor::Action::PressOnce);
thor::Action left_hold(sf::Mouse::Left, thor::Action::Hold);

m_input_map[User_Input::USER_MOUSE_LEFT_PRESS] = left_press | !left_hold;

Basically just saying that USER_MOUSE_LEFT_PRESS cannot be left_hold. The reason I want this is because of this:
 
if (m_input_manager.getInputMap().isActive(User_Input::USER_MOUSE_LEFT_PRESS))
        std::cout << "wassup" << std::endl;

else if (m_input_manager.getInputMap().isActive(User_Input::USER_MOUSE_LEFT_HOLD))
        std::cout << "wassup 2" << std::endl;

Whenever I click once, it'll say "wassup" once and "wassup 2" about 5-6 times. I want there to be a clear difference between USER_MOUSE_LEFT_PRESS and USER_MOUSE_LEFT_HOLD. Is there any way to do this? (PS: setKeyRepeatEnabled is already false)

Thanks!
Title: Re: Thor 2.0
Post by: Nexus on January 12, 2014, 02:01:38 pm
I don't know wich compiler you use but this code don't compile :
As this is not Thor's original code, please keep problems about your own library SFGL/ODFAEG out of this thread. If you're trying to adopt Thor's implementation and have problems with it, you should discuss it in your own thread...


Is there a way to do this:
There are && and ! operators for thor::Action, but I think you should approach the problem differently.

Why do you need to differentiate between both actions? The press event is always followed by the key being held down. What do you actually want to achieve?
Title: Re: Thor 2.0
Post by: Lolilolight on January 12, 2014, 02:33:37 pm
Quote
As this is not Thor's original code, please keep problems about your own library SFGL/ODFAEG out of this thread. If you're trying to adopt Thor's implementation and have problems with it, you should discuss it in your own thread...

It's not only for my own library..., it doesn't compile in general..., but, anyway I've just changed that and used a normal function instead of the operator[] overloading and it work fine.
The operator[] overlaoding works only with int for me.

But I've a question, why so many classes, is it for optimisation ?

Me I've just a classe action, and a an actionmap (to store the action and the signal), and a thirt class to store every object with a key. (If you have looked at my github repository)
I looked at your code, and I didn't understand very well so I've implemented your system with less code.

Title: Re: Thor 2.0
Post by: Nexus on January 12, 2014, 03:06:23 pm
But I've a question, why so many classes, is it for optimisation ?
Which classes do you mean? The ones in ActionOperations.hpp represent different nodes in the tree that is built from boolean combinations.

If you have built the same functionality with less code, fine :)
Title: Re: Thor 2.0
Post by: Lolilolight on January 12, 2014, 07:54:55 pm
Ha ok, then I'm in the right way. :)
Title: Re: Thor 2.0
Post by: kingcools on January 12, 2014, 09:52:49 pm
Thank you expl0it3r, learned something new there :)
It's not as if it weren't mentioned in the tutorial (http://www.bromeon.ch/libraries/thor/v2.0/tutorial-installation.html) with a red IMPORTANT subtitle :P
(Even if it's written for SFML, for Thor the same applies)

Guess im to blame, because i always just build via "make all". :P
Title: Re: Thor 2.0
Post by: kingcools on January 13, 2014, 02:48:20 am
okay i need some thor insight:

Im trying to implement the animatorclass for creating animations in my project, but somehow the animate() function crashes my project:

This contains the animator:
class AnimationComponent
:public ComponentBase<AnimationComponent>
{

public:
    sf::Texture tex;
    thor::FrameAnimation walk;

public:
    AnimationComponent(const sf::Texture& t,const sf::Vector2f& p,const thor::Animator<sf::Sprite, std::string>& a)
    :tex(t),animator(a)
    { spr.setTexture(tex); spr.setPosition(p); }

    thor::Animator<sf::Sprite, std::string> animator;
    sf::Sprite spr;
};
 


Here i create a dummy animation:
void addFrames(thor::FrameAnimation& animation, int x, int yFirst, int yLast, float duration = 1.f)
{
        const int step = (yFirst < yLast) ? +1 : -1;
        yLast += step; // so yLast is excluded in the range

        for (int y = yFirst; y != yLast; y += step)
                animation.addFrame(duration, sf::IntRect(36*x, 39*y, 36, 39));
}

void Factory::createDummyAnim()
{
    sf::Image image;
    sf::Texture texture;

        if(!image.loadFromFile("animation.png")){
        std::cout << "No such file" << std::endl;
        }

        image.createMaskFromColor(sf::Color::White);
        if(!texture.loadFromFile("animation.png"))
        std::cout << "Texture gone wrong\n";

        // Define walk animation
        thor::FrameAnimation walk;
        addFrames(walk, 0, 0, 7);                       // Frames 0..7  Right leg moves forward
        addFrames(walk, 0, 6, 0);                       // Frames 6..0  Right leg moves backward

        // Register animations with their corresponding durations
        thor::Animator<sf::Sprite, std::string> animator;
        animator.addAnimation("walk", walk, sf::seconds(1.f));
        animator.playAnimation("walk",true);

        Entity& e = _entitymanager.createEntity();
        _entitymanager.addComponent(new AnimationComponent(texture,sf::Vector2f(100.f,100),animator),e);
}

Here the animator::animate() method crashes my code:
void AnimationSystem::update(const sf::Time& dt)
{
    entitylist& entities = _entitymanager.getEntitiesWithComponent<AnimationComponent>();

    for(auto x: entities){
        constptr<AnimationComponent> ac = _entitymanager.getComponent<AnimationComponent>(x);
        ac->animator.update(dt);
        ac->animator.animate(ac->spr);//This line crashes my program, ac->spr is valid
    }
}

ac is valid and ac->spr 's texture is valid as well.

When i create the whole animator in the last code part my program does not crash. the whol entitysystem works, that is not the problem.
Title: Re: Thor 2.0
Post by: Nexus on January 13, 2014, 08:46:20 am
Hm, I don't immediately see a mistake. Where does it crash exactly? Are you really sure that getComponent doesn't return a corrupt pointer? Could you maybe show a minimal complete example?

And
for(auto x: entities)
Are you sure you want to copy each entity? Otherwise you have to use auto& x (unless it's a pointer).
Title: Re: Thor 2.0
Post by: kingcools on January 13, 2014, 03:08:23 pm
Its hard to give a minimal complete example due to the component system, i'll try to create one later (busy right now).
The entitielist is just a vector of pointers, so it should not matter whether i copy those or use a reference.

im pretty sure the componentpointer is not corrupted.
Its not a null pointer, all other components work just like this without a problem and the raw data stored in the components works just fine and does not crash my program when i dereference them. (i can draw the components sprite just fine, only the animate function applied to it crashes)
Title: Re: Thor 2.0
Post by: Nexus on January 13, 2014, 06:49:34 pm
Now that I looked again at your code, I have a suspicion: Since you copy the animator, it might be that some parts are not updated. Indeed, it looks like the iterator Animator::mPlayingAnimation still points to the old instance.

I'll investigate this, thanks!
Title: Re: Thor 2.0
Post by: kingcools on January 13, 2014, 10:10:16 pm
Thanks for the insight.
Guessed it would be the copy that corrupts the inner state of the animator since it runs normally with the components data when i build a "brand new" animator right in the update function, i will look for a work around for the time being.

edit:
small update: you talked about a bug in the copy mechanics so i used pointers instead and it works now without crashing anything! Thank you for your help!
Title: Re: Thor 2.0
Post by: Nexus on January 14, 2014, 12:35:00 am
I pushed the bugfix.

You are now able to use move semantics. You should prefer it over pointers (never use new/delete!)
// Function that takes argument by value; can be a constructor
void function(thor::Animator<sf::Sprite, std::string> animator);

thor::Animator<sf::Sprite, std::string> animator;
function(std::move(animator)); // transfer ownership to function
Title: Re: Thor 2.0
Post by: kingcools on January 14, 2014, 04:16:52 am
Great! Well i used a unique_ptr so it wont matter
Title: Re: Thor 2.0
Post by: kingcools on January 16, 2014, 04:42:06 am
Hi,

right now i want to create a bullet whenever my animation is at the proper sprite. now i figured the animator class has no "current animation element" sort of function neither an animation time function.
How would you implement a "correct" (== bullet matches shooting animation) bullet creation?
Title: Re: Thor 2.0
Post by: Nexus on January 16, 2014, 09:26:09 am
I wouldn't make game logics dependent on graphics, rather the other way around: Determine a time, and then set the animation duration and the fire delay accordingly.
Title: Re: Thor 2.0
Post by: The Terminator on January 25, 2014, 08:40:18 pm
Hi Nexus,

I have a quick question regarding sf::TextEntered. Now, with the default SFML polling you can do things like this:

if (event.type == sf::Event::TextEntered)
{
    if (event.text.unicode < 128)
        std::cout << "ASCII character typed: " << static_cast<char>(event.text.unicode) << std::endl;
}

Using Thor's actions, how would I be able to find out what key the user has pressed?

Thanks!
Title: Re: Thor 2.0
Post by: Nexus on January 26, 2014, 10:51:24 am
// Callback function that is called when text entered event is triggered
void onTextEntered(const thor::ActionContext<MyAction>& context)
{
        sf::Uint32 character = context.event->text.unicode;
        ...
}

// Action map initialization
thor::ActionMap<MyEnum> map;
map[MyTextAction] = thor::Action(sf::Event::TextEntered);

// Callback registering
thor::ActionMap<MyEnum>::CallbackSystem callbacks;
callbacks.connect(MyTextAction, &onTextEntered);
Title: Re: Thor 2.0
Post by: The Terminator on January 26, 2014, 05:08:54 pm
// Callback function that is called when text entered event is triggered
void onTextEntered(const thor::ActionContext<MyAction>& context)
{
        sf::Uint32 character = context.event->text.unicode;
        ...
}

// Action map initialization
thor::ActionMap<MyEnum> map;
map[MyTextAction] = thor::Action(sf::Event::TextEntered);

// Callback registering
thor::ActionMap<MyEnum>::CallbackSystem callbacks;
callbacks.connect(MyTextAction, &onTextEntered);

Thanks! I have one more question. Let's say I have the onTextEntered method, but want to change it a little bit:

static void onTextEntered(const thor::ActionContext<User_Input>& context,
                                  const SInputManager& instance);

How would I connect the callback to the system?
Title: Re: Thor 2.0
Post by: Nexus on January 26, 2014, 05:27:17 pm
There are multiple possibilities what you can pass to connect().

Functor:
struct Functor
{
    void operator() (const thor::ActionContext<...>& context) const
    {
        SInputManager::onTextEntered(context, instance);
    }

    const SInputManager& instance;
    ...
}

Lambda expression:
[&instance] (const thor::ActionContext<...>& context)
{
    onTextEntered(context, instance);
}

Bind (_1 is in namespace std::placeholders):
std::bind(&SInputManager::onTextEntered, _1, std::cref(instance))

onTextEntered() can also be a non-static member function, you have to adapt the function objects accordingly. I recommend reading more about function objects in C++, they're very powerful.

And don't use those S prefixes for classes, there is really no reason to (http://en.sfml-dev.org/forums/index.php?topic=9423.msg63949#msg63949) :(
Title: Re: Thor 2.0
Post by: The Terminator on January 26, 2014, 06:07:30 pm
There are multiple possibilities what you can pass to connect().

Functor:
struct Functor
{
    void operator() (const thor::ActionContext<...>& context) const
    {
        SInputManager::onTextEntered(context, instance);
    }

    const SInputManager& instance;
    ...
}

Lambda expression:
[&instance] (const thor::ActionContext<...>& context)
{
    onTextEntered(context, instance);
}

Bind (_1 is in namespace std::placeholders):
std::bind(&SInputManager::onTextEntered, _1, std::cref(instance))

onTextEntered() can also be a non-static member function, you have to adapt the function objects accordingly. I recommend reading more about function objects in C++, they're very powerful.

And don't use those S prefixes for classes, there is really no reason to (http://en.sfml-dev.org/forums/index.php?topic=9423.msg63949#msg63949) :(

I'm going to std::bind route, and the code compiles, but the application crashes right as invokeCallbacks is called. My code:

static void onTextEntered(const thor::ActionContext<User_Input>& context,
                           const SInputManager& instance);

m_callback_system.connect(User_Input::TEXTENTERED, std::bind(&SE::SInputManager::onTextEntered,
                                                                     std::placeholders::_1,
                                                                     std::cref(*this)));

m_user_map.invokeCallbacks(m_callback_system, nullptr);

    void SInputManager::onTextEntered(const thor::ActionContext<User_Input>& context, const SInputManager& instance)
    {
        sf::Uint32 character = context.event->text.unicode;

        m_textEntered += character;
    }
Title: Re: Thor 2.0
Post by: Nexus on January 27, 2014, 08:18:50 pm
There's no need to quote the whole post if it's just above ;)

Where does it crash exactly? Please minimize the code and try to debug a bit on your own. If you want me to see the problem, show a minimal and complete example.

Anyway, it would be easier to have a non-static member function, and pass this as the second parameter (first after function name) to std::bind().
Title: Re: Thor 2.0
Post by: The Terminator on January 29, 2014, 09:57:37 pm
Anyway, it would be easier to have a non-static member function, and pass this as the second parameter (first after function name) to std::bind().

I've been reading a little bit about std::bind and functors. I fully understand functors now, but I'm still having a little bit of trouble with std::bind. I've done exactly what you said (remove static and pass this to connect) but I'm still having some issues. My code:

m_callback_system.connect(User_Input::TEXTENTERED, std::bind(&SE::SInputManager::onTextEntered, *this));

Thanks again!
Title: Re: Thor 2.0
Post by: Nexus on January 29, 2014, 10:40:07 pm
You still need _1 as the last argument in std::bind() -- it specifies the thor::ActionContext argument that is forwarded. Furthermore, for member functions you should pass a pointer, not a reference to the object.
std::bind(&SE::SInputManager::onTextEntered, this, _1)

If you struggle at understanding std::bind(), just use lambda expressions.

And have you seen my advice concerning "S" prefixes? ;)
Title: Re: Thor 2.0
Post by: pedrolino on January 30, 2014, 02:42:07 pm
Hello :)
I want to try to use thor, but I have problems :
I tried to use triangulation, but I have a segmentation fault when I call


OutputIterator thor::triangulate   (   InputIterator    verticesBegin, InputIterator    verticesEnd, OutputIterator    trianglesOut )   


To be sure that I did not make mistakes in my code, I tried to compile the triangulation example with my compiler settings : I copy paste the main function in my main.cpp, but keep my CMakeLists.txt as I am used to write it.

So in my opinion the problem is here : I probably forgot an option in my cmake file, but I don't understand cmake enough to find what is wrong in my file compared to the lib file.

So I ask you for help :)

Here is my CMakeLists.txt :

cmake_minimum_required(VERSION 2.6)

#Project name
project(Projet)

SET(CMAKE_CXX_FLAGS "-std=c++11")

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")

find_package(SFML COMPONENTS graphics window system REQUIRED)
find_package(Thor REQUIRED)

include_directories(${SFML_INCLUDE_DIRS})
include_directories(${THOR_INCLUDE_DIRS})

file(
    GLOB_RECURSE
    source_file
    src/*
)

#Executable
add_executable(
    exe
    ${source_file}
)

target_link_libraries(
    exe
    ${SFML_LIBRARIES}
    ${THOR_LIBRARY}
)
 

I hope you will be able to help me, and I apoligize if my question is stupid.

Thank you :)

(And please excuse my english : I am french and I did not practice for a while  :-[)
Title: Re: Thor 2.0
Post by: Nexus on January 30, 2014, 03:12:19 pm
You forgot to set the CMAKE_BUILD_TYPE variable. Either set it to "Release" or "Debug" (without quotation marks). You could also try to use THOR_LIBRARY_RELEASE directly instead of THOR_LIBRARY.

If it still doesn't work, can you add the following lines to your CMakeLists script directly after find_package() and show the output?
message("lib sfml [${SFML_LIBRARIES}]")
message("    thor [${THOR_LIBRARY}]")
message("inc sfml [${SFML_INCLUDE_DIRS}]")
message("    thor [${THOR_INCLUDE_DIRS}]")

Does the original Thor configuration work at you (when you build Thor with CMake, choose to build the examples)?
Title: Re: Thor 2.0
Post by: pedrolino on January 30, 2014, 07:56:04 pm
Hello :)

Quote
Either set it to "Release" or "Debug"

This worked!
Thank you very much.

Quote
Does the original Thor configuration work at you (when you build Thor with CMake, choose to build the examples)?

Yes it works, that's why I thought it was a problem in my CMakeLists script.

Thanks again! :D
Title: Re: Thor 2.0
Post by: The Terminator on January 31, 2014, 03:54:28 am
You still need _1 as the last argument in std::bind() -- it specifies the thor::ActionContext argument that is forwarded. Furthermore, for member functions you should pass a pointer, not a reference to the object.
std::bind(&SE::SInputManager::onTextEntered, this, _1)

If you struggle at understanding std::bind(), just use lambda expressions.

And have you seen my advice concerning "S" prefixes? ;)

Thanks a lot! Regarding the S prefixes, they are not being used in the same way C prefixes were. In my engine, all code that belongs to it is marked with an S (stands for Shock, my engine is called Shock Engine) prefix to differentiate between engine code and user game code.
Title: Re: Thor 2.0
Post by: dabbertorres on January 31, 2014, 05:40:43 am
I'm not sure what exactly Nexus is referring to concerning prefixes, but, my guess would be that you should look into using namespaces rather than using a prefix, which, is what they're meant to be used for after all.  ;)

For example:
std::bind(&shk::E::InputManager::onTextEntered, this, _1)

That's why SFML uses the 'sf' namespace, to separate framework code from user code (and potentially other engine code), which is what you want to accomplish.

What if someone else made a library for something and prefixed all of their functions with an 'S' as well? You'd have a clash, which never turns out good for the compiler. As namespaces have longer names, the chances of clashing turns out much less.
Title: Re: Thor 2.0
Post by: Nexus on January 31, 2014, 10:23:58 am
Another advantage of namespaces is that you can keep them long and expressive:
namespace ShockEngine
{
    // your library
}

In user code, you can still create aliases, even for nested namespaces:
namespace shk = ShockEngine;
namespace si = ShockEngine::Input;

shk::InputManager mgr;

You can also locally "empty out" the namespace (but never do this in headers):
using namespace ShockEngine;
Title: Thor 2.0
Post by: The Terminator on January 31, 2014, 01:44:26 pm

Another advantage of namespaces is that you can keep them long and expressive:
namespace ShockEngine
{
    // your library
}

In user code, you can still create aliases, even for nested namespaces:
namespace shk = ShockEngine;
namespace si = ShockEngine::Input;

shk::InputManager mgr;

You can also locally "empty out" the namespace (but never do this in headers):
using namespace ShockEngine;

I am using namespaces as well. Well known libraries and engines have a prefix similar to mine such as Ogre3D. I am open to new ideas, but I think that the prefix will stay.
Title: Re: Thor 2.0
Post by: Nexus on January 31, 2014, 01:59:29 pm
You're full-quoting again :P

Well known libraries and engines have a prefix similar to mine such as Ogre3D.
Ogre3D uses the Ogre namespace, not a prefix. Most C++ libraries, especially modern ones, do use namespaces. Box2D is famous for using prefixes instead of namespaces; the arguments of the developers (http://www.box2d.org/forum/viewtopic.php?f=4&t=4150) however are either very weak or inherently wrong ("it makes porting harder", "you have to type more", "debuggers can't handle them").

I am open to new ideas
Well, you've heard them ;)

I just think you should benefit of C++ features where they bring advantages (and I don't see a real argument for prefixes, to be honest). But of course it's your decision.
Title: Re: Thor 2.0
Post by: Lo-X on January 31, 2014, 02:17:41 pm
My two cents are that when I write code, I like it to sounds like real written english (sort of). So when I use a class, its name should be the same that in a sentence. It's also easier to find them again with our auto-completion.

Prefixes tend to break these statements. But of course, that's not a reason not to use the lib. Just a convenience thing.
Title: Re: Thor 2.0
Post by: FRex on January 31, 2014, 02:58:50 pm
Quote
Box2D is famous for using prefixes instead of namespaces
Qt does use Q prefixes at times, not sure if it uses namespaces, but it's a very backwards compatible library so it's understandable.

Erin Catto also uses argument that he supports compilers that don't support namespaces (?!) and explicitly changed all cxxx includes to xxx.h few months ago (back to C from c++ compatibility ones, probably since they use namespaces, the commit had simply stated the fact, not given a reason), also he uses raw memory blocks instead of new (but that's to also allow plugging in other memory allocators). There is also a bug where copying ChainShape(it's that I think, I'm sure one class does that, might not be ChainShape but I'm fairly sure) would cause double free because only pointer gets copied - violated rule of zero/five/three + manual memory management. It's like ultimate bane of your existence, Nexus. ;)

I don't know what to think about that. It's good physics library but the mentality of 'c++ is actually C' is very weird to me personally, especially since I am one of people who really really love C being nearly subset of c++.

I personally like namespaces, and they help with the fact that code completion starts looking only inside namespace when typing it's name followed by ::. They also make code clear and allow me to see easier which 'module' the functionality is coming from at a glance, :: really separates out the namespace name in monospaced fonts. Netbeans has no problem running GDB and listing these classes, it shows the type of class in namespace correctly as 'namespace::ClassName'.
Title: Re: Thor 2.0
Post by: FRex on February 05, 2014, 10:37:28 pm
Is there anything that could be done about Hold using isKeyPressed, like internally keeping bool for each key on your own instead and set/unset them on every keypressed/keyreleased event? I'm not sending any events to action map while input box is up but WASD still moves my character because ActionMap uses isKeyPressed. Using PressOnce with repeating keys makes it so first the character jerks a bit and then it starts moving smoothly(because there is one event, break and then many events for each key).
(As an ad hoc solution I'm not invoking callbacks with map instead of not sending events to map, but could something else be done for that? Also it'd be problem in (unlikely) case that someone wants to record input events and then use them to make demo/recording of game by letting game run using faked events from file instead of player ones).
Title: Re: Thor 2.0
Post by: Nexus on February 05, 2014, 10:56:24 pm
An event-based hold mechanism might be an idea for the future. It would also make things like handling only events inside the window easier. But the current realtime-based hold would probably still persist; I guess SFML users expect it to work like SFML's realtime input.

If you need a challenge, you can try to achieve this already now by combining thor::eventAction() and thor::realtimeAction() :P
(see doc (http://www.bromeon.ch/libraries/thor/v2.0/doc/classthor_1_1_action.html))
Title: Re: Thor 2.0
Post by: Dante12129 on February 23, 2014, 07:16:15 am
I have compiled SFML and Thor before, but I am having issues with the latest versions. I got SFML to compile fine, but whenever I try to configure Thor in Cmake, it gives me this message:
Could NOT find SFML (missing:  SFML_AUDIO_LIBRARY SFML_GRAPHICS_LIBRARY SFML_WINDOW_LIBRARY SFML_SYSTEM_LIBRARY)

-> SFML directory not found. Set SFML_ROOT to SFML's top-level path (containing "include" and "lib" directories).
-> Make sure the SFML libraries with the same configuration (Release/Debug, Static/Dynamic) exist.

I have all my SFML stuff in C:/SFML-2.1, and have set the SFML_ROOT in Cmake to there. I have SFML_INCLUDE_DIR set to C:/SFML-2.1/include. I compiled SFML into debug and release dynamic libraries, and have THOR_SHARED_LIBS set to do the same. I am using Windows 7 and TDM GCC 4.8.1.
Title: Re: Thor 2.0
Post by: Nexus on February 23, 2014, 12:14:43 pm
So you followed the installation tutorial (http://www.bromeon.ch/libraries/thor/v2.0/tutorial-installation.html) precisely? Have you edited the existing CMake variables (you should not create new ones)?

Are you sure that same the configuration you're currently trying to build for Thor exists already for SFML (all required files in include, lib and possibly bin directories are in SFML_ROOT)? For example, when you build Dynamic Release, there must be lib/libsfml-system.a and bin/sfml-system.dll.

Since you're mentioning TDM, it might also be related to that compiler, it's known to cause issues because it handles things non-inutitively. See also SFML issue #487 (https://github.com/SFML/SFML/pull/487)... We still have to find a definitive solution. But I wonder why CMake would not even find SFML; I'd rather expect linking problems.
Title: Re: Thor 2.0
Post by: Svenstaro on February 27, 2014, 01:01:56 pm
Did you consider adding a general tweening system? I think it would be very helpful on its own and you could also use it internally in some places.
Title: Re: Thor 2.0
Post by: Nexus on February 27, 2014, 01:10:19 pm
Not at the moment... What functionality and API would you imagine?
Title: Re: Thor 2.0
Post by: Svenstaro on February 27, 2014, 01:22:13 pm
Something simple like this: https://github.com/runemadsen/Tween

It should be really easy to implement. A lot like the ParticleSystem, you'd have a TweeningSystem you add things to and update the TweeningSystem once a tick globally.
Title: Re: Thor 2.0
Post by: Nexus on April 02, 2014, 01:00:56 pm
I'm planning to make Thor 2.0 ready for release in the near future, so that I can make this version compatible with SFML 2.2 once it is out.

Most tasks are done (http://www.bromeon.ch/libraries/thor/progress.html), there are a few bugs (related to triangulation and compile errors in Aurora) that I plan to fix. Since Aurora is shipped with Thor, I might also clean it up fundamentally. Are there other crucial things? Note that I won't implement new features for Thor 2.0.

It's also a good opportunity to give again feedback to Thor's API. Do you like it, where do you think it can be improved?
Title: Re: Thor 2.0
Post by: AlexxanderX on April 05, 2014, 09:43:03 am
I want to say Nexus that you did a great job :D
But when try to compile I get those erros and I think are not related to my code:
obj/Game.o: In function `thor::MultiResourceCache::MultiResourceCache()':
Game.cpp:(.text+0x9c): multiple definition of `thor::MultiResourceCache::MultiResourceCache()'
obj/Entity.o:Entity.cpp:(.text+0x114): first defined here
obj/Game.o: In function `thor::MultiResourceCache::MultiResourceCache()':
Game.cpp:(.text+0x9c): multiple definition of `thor::MultiResourceCache::MultiResourceCache()'
obj/Entity.o:Entity.cpp:(.text+0x114): first defined here
obj/Game.o: In function `thor::MultiResourceCache::MultiResourceCache(thor::MultiResourceCache&&)':
Game.cpp:(.text+0xcc): multiple definition of `thor::MultiResourceCache::MultiResourceCache(thor::MultiResourceCache&&)'
obj/Entity.o:Entity.cpp:(.text+0x144): first defined here
obj/Game.o: In function `thor::MultiResourceCache::MultiResourceCache(thor::MultiResourceCache&&)':
Game.cpp:(.text+0xcc): multiple definition of `thor::MultiResourceCache::MultiResourceCache(thor::MultiResourceCache&&)'
obj/Entity.o:Entity.cpp:(.text+0x144): first defined here
obj/Game.o: In function `thor::MultiResourceCache::operator=(thor::MultiResourceCache&&)':
Game.cpp:(.text+0x118): multiple definition of `thor::MultiResourceCache::operator=(thor::MultiResourceCache&&)'
obj/Entity.o:Entity.cpp:(.text+0x190): first defined here
... and more more erros like those
 
Title: Re: Thor 2.0
Post by: Nexus on April 05, 2014, 10:10:13 am
The Resources example that also uses thor::MultiResourceCache builds fine at me, so can you show a minimal complete example (you should always do that)? You're not including the .inl file directly or mixing two versions, are you?
Title: Re: Thor 2.0
Post by: Laurent on April 05, 2014, 10:39:16 am
Nexus, I think your MultiResourceCache constructors and operator= (https://github.com/Bromeon/Thor/blob/master/include/Thor/Resources/Detail/MultiResourceCache.inl#L61) miss the "inline" keyword.
Title: Re: Thor 2.0
Post by: Nexus on April 05, 2014, 10:50:08 am
Ah exactly! They're not templates. Thanks a lot :)

Edit: Fixed now.
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 11, 2014, 08:58:53 am
While compiling Thor for the Nightly Builds, the 64 bit version of Visual Studio spit out the following two errors (yeah not gonna bother translating them :P):
Thor\src\ParticleSystem.cpp(92) : warning C4267: 'return': Konvertierung von 'size_t' nach 'unsigned int', Datenverlust möglich
Thor\examples\Fireworks.cpp(39) : warning C4267: 'Argument': Konvertierung von 'size_t' nach 'unsigned int', Datenverlust möglich
Title: Re: Thor 2.0
Post by: Nexus on April 11, 2014, 10:16:32 am
Thanks! That problem of mixing types is inherent to C++ (http://en.sfml-dev.org/forums/index.php?topic=7303.msg49688#msg49688), and it's unfortunate that there is no clean solution, you always end up casting in some places.

There are mostly three unsigned integer types applicable in Thor, I think it would make sense to use them as follows:
I have to have a look at the corresponding places and check what measures would be the lesser evil... I originally planned to have a uniform interface with only unsigned int, but I guess that's not the best idea...
Title: Re: Thor 2.0
Post by: Lolilolight on May 25, 2014, 04:46:46 pm
Hi!

Is your git hub repository up to date ???

When I try to compile I get this error :

Code: [Select]
/home/laurent/Projets-dev/Projets-c++/ODFAEG/src/odfaeg/Math/distribution.cpp|78|error: could not convert ‘<lambda closure object>odfaeg::Distributions::uniform(sf::Time, sf::Time)::__lambda1{((float)floatMin), ((float)floatMax)}’ from ‘odfaeg::Distributions::uniform(sf::Time, sf::Time)::__lambda1’ to ‘odfaeg::Distribution<sf::Time>’|

Title: Re: Thor 2.0
Post by: Chaore on May 25, 2014, 05:02:56 pm
It was working 2 weeks ago so I expect that yes it's up to date.
Title: Re: Thor 2.0
Post by: Lolilolight on May 25, 2014, 05:07:49 pm
Ok, ok.
Title: Re: Thor 2.0
Post by: Lolilolight on May 26, 2014, 08:44:57 am
Erf, I just had miss typed the ENABLE_IF macro code. (because I don't want to use aurora, I've something else instead.)

I've a question, what does the macro FOR_EACH does ?

Is it the same that std::for_each ?

You have a bunch of macros in Aurora and I don't understand anything. (because I don't do like you does, I have a class which encapsulate c++ basic function and c++11 functions and a class any to encapsulate constant.)

Some c++11 functionnalities are still too complex for me.

Anyway I don't need to store functions parameters value here so I re-use your code with std::function but it's a bit difficult with your macros. :/

PS : erf it seems that your particule system generate only 2D vectors, I have to modify that.
Title: Re: Thor 2.0
Post by: Nexus on May 26, 2014, 09:16:09 am
The documentation exists for a reason...

No, AURORA_FOREACH emulates range-based for loops. You don't need it for fully C++11 conforming compilers.
Title: Re: Thor 2.0
Post by: Lolilolight on May 26, 2014, 09:36:10 am
Ha ok so I don't need it, I replaced it by that :

std::for_each (auto& affectorPair : mAffectors)
affectorPair.function(*reader, dt);
 

So you mean that you want to made a code which compile also with non c++11 compilers ?

If it's the case it differs from the mine.
Title: Re: Thor 2.0
Post by: Nexus on May 26, 2014, 09:44:26 am
std::for_each (auto& affectorPair : mAffectors)
Good luck with that 8)

So you mean that you want to made a code which compile also with non c++11 compilers ?
Mainly compilers that only implement a subset of C++11, such as Visual Studio 2010.
Title: Re: Thor 2.0
Post by: Lolilolight on May 26, 2014, 10:00:40 am
I suppose that I have to rewrite all by myself then. :/

If I don't understand the code it'll lead to bugs.

Most of all, your affector seems to use your connexion interface. :/

And I use delegates, so ...
Title: Re: Thor 2.0
Post by: Lolilolight on May 26, 2014, 11:25:21 am
I got it!

I think I don't need to return an objet of type connexion, so, addAfffector return void, and I replaced AURORA_FOR_EACH by a basic for loop.
I replaced also all sf::Vector2f by sf::Vector3f.

/////////////////////////////////////////////////////////////////////////////////
//
// Thor C++ Library
// Copyright (c) 2011-2014 Jan Haller
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////

#include "../../../include/odfaeg/Physics/particuleSystem.h"


#include "../../../include/odfaeg/Graphics/renderWindow.h"
#include "../../../include/odfaeg/Graphics/texture.h"

#include <algorithm>
#include <array>
#include <cmath>
#include <cassert>


namespace odfaeg
{
namespace
{

// Erases emitter/affector at itr from ctr, if its time has expired. itr will point to the next element.
template <class Container>
void incrementCheckExpiry(Container& ctr, typename Container::iterator& itr, sf::Time dt)
{
// itr->second is the remaining time of the emitter/affector.
// Time::Zero means infinite time (no removal).
if (itr->timeUntilRemoval != sf::Time::Zero && (itr->timeUntilRemoval -= dt) <= sf::Time::Zero)
itr = ctr.erase(itr);
else
++itr;
}

sf::IntRect getFullRect(const Texture& texture)
{
return sf::IntRect(0, 0, texture.getSize().x, texture.getSize().y);
}

} // namespace

// ---------------------------------------------------------------------------------------------------------------------------


ParticleSystem::ParticleSystem()
: mParticles()
, mAffectors()
, mEmitters()
, mTexture(nullptr)
, mTextureRects()
, mVertices(sf::Quads)
, mNeedsVertexUpdate(true)
, mQuads()
, mNeedsQuadUpdate(true)
{
}

void ParticleSystem::setTexture(const Texture& texture)
{
mTexture = &texture;
mNeedsQuadUpdate = true;
}

unsigned int ParticleSystem::addTextureRect(const sf::IntRect& textureRect)
{
mTextureRects.push_back(textureRect);
mNeedsQuadUpdate = true;

return mTextureRects.size() - 1;
}

void ParticleSystem::swap(ParticleSystem& other)
{
// Use ADL
using std::swap;

swap(mParticles,        other.mParticles);
swap(mAffectors,        other.mAffectors);
swap(mEmitters, other.mEmitters);
swap(mTexture,  other.mTexture);
swap(mTextureRects,     other.mTextureRects);
swap(mVertices, other.mVertices);
swap(mNeedsVertexUpdate,        other.mNeedsVertexUpdate);
swap(mQuads,    other.mQuads);
swap(mNeedsQuadUpdate,  other.mNeedsQuadUpdate);
}

void ParticleSystem::addAffector(std::function<void(Particle&, sf::Time)> affector)
{
    addAffector(std::move(affector), sf::Time::Zero);
}

void ParticleSystem::addAffector(std::function<void(Particle&, sf::Time)> affector, sf::Time timeUntilRemoval)
{
    mAffectors.push_back( Affector(std::move(affector), timeUntilRemoval) );
}

void ParticleSystem::clearAffectors()
{
mAffectors.clear();
}

void ParticleSystem::addEmitter(std::function<void(EmissionInterface&, sf::Time)> emitter)
{
    addEmitter(emitter, sf::Time::Zero);
}

void ParticleSystem::addEmitter(std::function<void(EmissionInterface&, sf::Time)> emitter, sf::Time timeUntilRemoval)
{
    mEmitters.push_back( Emitter(std::move(emitter), timeUntilRemoval) );
}

void ParticleSystem::clearEmitters()
{
mEmitters.clear();
}

void ParticleSystem::update(sf::Time dt)
{
// Invalidate stored vertices
mNeedsVertexUpdate = true;

// Emit new particles and remove expiring emitters
for (EmitterContainer::iterator itr = mEmitters.begin(); itr != mEmitters.end(); )
{
itr->function(*this, dt);
incrementCheckExpiry(mEmitters, itr, dt);
}

// Affect existing particles
ParticleContainer::iterator writer = mParticles.begin();
for (ParticleContainer::iterator reader = mParticles.begin(); reader != mParticles.end(); ++reader)
{
// Apply movement and decrease lifetime
updateParticle(*reader, dt);

// If current particle is not dead
if (reader->passedLifetime < reader->totalLifetime)
{
// Only apply affectors to living particles
AffectorContainer::iterator it;
for (it = mAffectors.begin(); it < mAffectors.end(); it++) {
    it->function(*reader, dt);
}
// Go ahead
*writer++ = *reader;
}
}

// Remove particles dying this frame
mParticles.erase(writer, mParticles.end());

// Remove affectors expiring this frame
for (AffectorContainer::iterator itr = mAffectors.begin(); itr != mAffectors.end(); )
{
incrementCheckExpiry(mAffectors, itr, dt);
}
}

void ParticleSystem::clearParticles()
{
mParticles.clear();
}

void ParticleSystem::draw(RenderTarget& target, RenderStates states) const
{
// Check cached rectangles
if (mNeedsQuadUpdate)
{
computeQuads();
mNeedsQuadUpdate = false;
}

// Check cached vertices
if (mNeedsVertexUpdate)
{
computeVertices();
mNeedsVertexUpdate = false;
}

// Draw the vertex array with our texture
states.texture = mTexture;
target.draw(mVertices, states);
}

void ParticleSystem::emitParticle(const Particle& particle)
{
mParticles.push_back(particle);
}

void ParticleSystem::updateParticle(Particle& particle, sf::Time dt)
{
particle.passedLifetime += dt;

particle.position += dt.asSeconds() * particle.velocity;
particle.rotation += dt.asSeconds() * particle.rotationSpeed;
}

void ParticleSystem::computeVertices() const
{
// Clear vertex array (keeps memory allocated)
mVertices.clear();

// Fill vertex array
ParticleContainer::const_iterator it;
for(it = mParticles.begin(); it < mParticles.end(); it++)
{
TransformMatrix transform;
transform.setTranslation(Vec3f(it->position.x, it->position.y, it->position.z));
transform.setRotation(it->rotation);
transform.setScale(Vec3f(it->scale.x, it->scale.y, it->scale.z));

// Ensure valid index -- if this fails, you have not called addTextureRect() enough times, or p.textureIndex is simply wrong
assert(it->textureIndex == 0 || it->textureIndex < mTextureRects.size());

const auto& quad = mQuads[it->textureIndex];
for (unsigned int i = 0; i < 4; ++i)
{
Vertex vertex;
Vec3f pos = transform.transform(Vec3f(quad[i].position.x, quad[i].position.y,quad[i].position.z));
vertex.position = sf::Vector3f(pos.x, pos.y, pos.z);
vertex.texCoords = quad[i].texCoords;
vertex.color = it->color;

mVertices.append(vertex);
}
}
}

void ParticleSystem::computeQuads() const
{
// Ensure setTexture() has been called
assert(mTexture);

// No texture rects: Use full texture, cache single rectangle
if (mTextureRects.empty())
{
mQuads.resize(1);
computeQuad(mQuads[0], getFullRect(*mTexture));
}

// Specified texture rects: Cache every one
else
{
mQuads.resize(mTextureRects.size());
for (std::size_t i = 0; i < mTextureRects.size(); ++i)
computeQuad(mQuads[i], mTextureRects[i]);
}
}

void ParticleSystem::computeQuad(Quad& quad, const sf::IntRect& textureRect) const
{
sf::FloatRect rect(textureRect);

quad[0].texCoords = sf::Vector2f(rect.left, rect.top);
quad[1].texCoords = sf::Vector2f(rect.left + rect.width, rect.top);
quad[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height);
quad[3].texCoords = sf::Vector2f(rect.left, rect.top + rect.height);

quad[0].position = sf::Vector3f(-rect.width, -rect.height, 0) / 2.f;
quad[1].position = sf::Vector3f( rect.width, -rect.height, 0) / 2.f;
quad[2].position = sf::Vector3f( rect.width, rect.height, 0) / 2.f;
quad[3].position = sf::Vector3f(-rect.width, rect.height, 0) / 2.f;
}

} // namespace thor
 
Title: Re: Thor 2.0
Post by: Nexus on May 27, 2014, 09:10:27 am
Lolilolight, this is the thread about Thor, not ODFAEG. Nobody who reads this thread wants to know how your code looks.

And please read the license text when you're using my code:
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.

I would appreciate if you could add a note to the original license text that states that you have written or adapted this code, not I. Thank you :)
Title: Re: Thor 2.0
Post by: Lolilolight on May 27, 2014, 05:17:44 pm
Ok nexus.  :)
Title: Re: Thor 2.0
Post by: Mutoh on June 02, 2014, 03:37:20 am
Ever thought about adding "clamp" functions to the VectorAlgebra libraries, Nexus? :)

template <typename T>
void clamp(sf::Vector2<T>& vector, T maxLength)
{
        if (squaredLength(vector) > std::pow(maxLength, 2))
        {
                auto angle = polarAngle(vector);

                vector.x = maxLength;
                vector.y = 0;

                setPolarAngle(vector, angle);
        }
}

template <typename T>
sf::Vector2<T> clamped(const sf::Vector2<T>& vector, T maxLength)
{
        sf::Vector2<T> copy = vector;
        clamp(copy, maxLength);

        return copy;
}

This is the piece of code that I've added to the library to suit my needs. Just thought I'd comment. :y
Title: Re: Thor 2.0
Post by: Laurent on June 02, 2014, 07:46:01 am
sf::Vector2<T> clamped(const sf::Vector2<T>& vector, T maxLength)
{
    sf::Vector2<T> copy = vector;

=>

sf::Vector2<T> clamped(sf::Vector2<T> vector, T maxLength)
{
 
Title: Re: Thor 2.0
Post by: Nexus on June 02, 2014, 10:04:28 am
That might be an option for a future version, but I would probably provide a method that also handles the minimum length. For me, the term "clamp" denotes bounds on two sides.

Plus, your version can be made more efficient, there's no need to compute the angle:
template <typename T>
void clamp(sf::Vector2<T>& vector, T maxLength)
{
    T square = squaredLength(vector);
    if (square > maxLength * maxLength)
        vector = maxLength * vector / TrigonometricTraits<T>::sqrt(square);
}
Maybe setLength() could also be reused.
Title: Re: Thor 2.0
Post by: Skamer on June 05, 2014, 06:15:00 pm
I have a question.

I need know the keys(keyboard or mouse) that have been set in a Thor::Action.
Does it give a way to know them?
Title: Re: Thor 2.0
Post by: Nexus on June 05, 2014, 08:30:46 pm
No. The information is type-erased, so that actions can work with all possible kinds of events and realtime input conditions. The user can even specify his own custom actions.

Why do you need to know it?
Title: Re: Thor 2.0
Post by: Skamer on June 06, 2014, 01:05:06 pm
I have created a new class called PlayerInput that inherited de thor::ActionMap<std::string> in order to create two new method : loadFromFile and saveToFile.

- LoadFromFile  : it reads the xml file (PlayerInput.xml for example) that contains the player input saved and add them to mActionMap (i had to set it as protected).
- SaveToFile :  the same that LoadFromFile but it saves instead of to load player input.

The goal is to load/save directly player input from/to a xml file from this class.

Thanks you for your answer. It's not a problem, i will do it in another class that will contain a map<std::string,std::string> with for example the first string, the action name and the second string, the keyboard key string.
Title: Re: Thor 2.0
Post by: Nexus on June 06, 2014, 03:04:46 pm
I have created a new class called PlayerInput that inherited de thor::ActionMap<std::string> in order to create two new method : loadFromFile and saveToFile.
Why do people always inherit? That's not how C++ works. Almost none of the classes in Thor are intended as a base class, for good reasons. Instead, you should store the action map as a member. I'm sure not all of its methods make sense for PlayerInput anyway; see also LSP (https://en.wikipedia.org/wiki/Liskov_substitution_principle).

I guess I'll have to make massive use of the final keyword once all compilers support it :D


The goal is to load/save directly player input from/to a xml file from this class.
Okay. I was already asked for serialization earlier. The problem is, I cannot provide it in a generic way. Simple mappings like action X is bound to key Y are just the beginning; users can specify their own custom actions over which I have no control; and different actions can be combined with logical operators.

Another problem is also that custom actions are packed into std::function, which doesn't allow to extract the original functor in the general case. So I would have to store the events/real-time conditions separately in each action. But I don't know if it's even possible in all situations...

So if you can contrain the complexity to simple mappings on user side, a serialization will be much simpler. But these conversion functions (http://www.bromeon.ch/libraries/thor/v2.0/doc/_input_names_8hpp.html) can be useful for you, maybe you're using them already.
Title: Re: Thor 2.0
Post by: Jesper Juhl on June 07, 2014, 11:07:45 pm
I guess I'll have to make massive use of the final keyword once all compilers support it :D

You don't need final to make it impossible to inherit from a class. A little creative use of virtual inheritance can do the job  ;)

class Uninheritable
{
protected:
    virtual ~Uninheritable() {}
};

struct DontInheritFromMe : virtual private Uninheritable
{
};

struct BadBoy : public DontInheritFromMe
{
};

int main()
{
    DontInheritFromMe d;
    BadBoy b;
}
 

and then you'll get nice compiler errors when someone tries to inherit :

Code: [Select]
$ clang++ src/test.cc
src/test.cc:13:8: error: inherited virtual base class 'Uninheritable' has private destructor
struct BadBoy : public DontInheritFromMe
       ^
src/test.cc:9:28: note: declared private here
struct DontInheritFromMe : virtual private Uninheritable
                           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/test.cc:20:12: note: implicit default constructor for 'BadBoy' first required here
    BadBoy b;
           ^
Title: Re: Thor 2.0
Post by: select_this on June 07, 2014, 11:30:48 pm
I've not seen that trick before - I like it because it feels devious :)
Title: Re: Thor 2.0
Post by: Lolilolight on June 07, 2014, 11:39:27 pm
Quote
Okay. I was already asked for serialization earlier. The problem is, I cannot provide it in a generic way. Simple mappings like action X is bound to key Y are just the beginning; users can specify their own custom actions over which I have no control; and different actions can be combined with logical operators.

Another problem is also that custom actions are packed into std::function, which doesn't allow to extract the original functor in the general case. So I would have to store the events/real-time conditions separately in each action. But I don't know if it's even possible in all situations...

I think this should be possible, but not with your structure because you packed your action into std::function.
But if you do the inverse I think this is possible. (pack the functions into your actions)

Your not forced to pack only std::function but also basic function pointers (if you really need to get the pointer), and the functions parameters into a tuple. (if you want to call to function with different object's parameters for the serialisation)

I think you can do serialisation with that. :P

And if you want to use inheritance you can define an interface (by example ActionListener) and some function to redefine, you create an object of your interface, you link it to your action and you call the function on the interface.

I think this is how java does.
Title: Re: Thor 2.0
Post by: Nexus on June 08, 2014, 01:35:07 pm
Indeed an interesting trick, Jesper :)

It comes at a high cost though. And generally, I go with the C++ philosophy and don't want to enforce correct usage, but rather encourage it. There will always be unintended uses... as long as I show how the API is supposed to be used, that should be enough.
Title: Re: Thor 2.0
Post by: Jesper Juhl on June 09, 2014, 12:35:47 am
Right. I wasn't really advocating that you use it. I was just showing that you could do it  ;)
Title: Re: Thor 2.0
Post by: tyrion on August 26, 2014, 02:02:14 am
Hi,

after a long time i have a new problem with thor, that i couldnt solve till now ....
I am trying to push an event manually in code:
      
void init()
{
thor::ActionMap<InputCmd::MyAction>::CallbackSystem system;
thor::ActionMap<InputCmd::MyAction> mMyActionmap;

mMyActionmap[InputCmd::KeyPressed] = Action(Event::KeyPressed);
mMyActionmap[InputCmd::Forward] = Action(toKeyboardKey("Key_W"), Action::Hold); //hold Action
       
system.connect(InputCmd::KeyPressed, ActionHandler(this));
system.connect(InputCmd::Forward, std::bind(&Controller::move, this, InputCmd::Forward));

}

void update()
{
mMyActionmap.update(*mView.mWindow);

// Forward actions to callbacks: Invokes onResize() in case of Event::Resized events
mMyActionmap.invokeCallbacks(system, mView.mWindow);
}

void manualEvent()
{
sf::Event eventTest;
eventTest.type = sf::Event::EventType::KeyPressed;
eventTest.key.code = sf::Keyboard::Key::W;
mMyActionmap.pushEvent(eventTest); //push event here
}

 

what works:
- pressing and holding the key "K" in the window triggers the "Forward" event
- calling manualEvent()  and change Action::Hold to Action::PressOnce fires the "Forward" event

what doesn't work:
- calling manualEvent() with Action::Hold doesn't trigger the "Forward" event, just the "Keypressed" event

Shouldn't the hold event fire, if the "keypressed" event is fired, without keyreleased?
do i miss somthing?
Title: Re: Thor 2.0
Post by: Nexus on August 26, 2014, 10:00:56 am
Hold actions are not linked to events, but to real-time input. What they do is checking the current state of sf::Keyboard, sf::Mouse and sf::Joystick.

Your approach seems a bit strange to me -- what do you exactly want to achieve? Are you sure about where to use events and where real-time input?
Title: Re: Thor 2.0
Post by: tyrion on August 26, 2014, 01:10:46 pm
is the realtime input not checked per event?
sf::Event eventTest;
eventTest.type = sf::Event::EventType::KeyPressed;
eventTest.key.code = sf::Keyboard::Key::W;

by using a window handle all mapped actions are working as i wish  :)
actually i create a wpf editor and want to pass the sfml events to sfml ....
i thought it would be enough to just push the events to "thor" manually?
Title: Re: Thor 2.0
Post by: Nexus on August 26, 2014, 10:15:44 pm
No, real-time input and events are completely different things. Thor's Actions provide a uniform interface for both, but that doesn't mean you can mix them behind the scenes. When you push an event, only event-based actions will fire.

PressOnce and ReleaseOnce denote events (they happen once), while Hold is a real-time state (a state you can query).

Maybe the functions thor::eventAction() and thor::realtimeAction() are interesting for you.
Title: Re: Thor 2.0
Post by: Jesper Juhl on August 26, 2014, 10:30:42 pm
The way I like to think about it is;

An event is something that happened in the (immediate) past that I need to react to.
A realtime test that's == true is something that's happening right now. And is I don't react right now it'll be too late.
Title: Re: Thor 2.0
Post by: Mars_999 on August 29, 2014, 03:57:51 pm
When is Thor2.0 going to be done, sorry but I been watching it for years and still nothing is final? This sucks... Please finish it so one can use it in 2.0 final state...

THanks!
Title: Re: Thor 2.0
Post by: Nexus on August 29, 2014, 05:34:25 pm
I want to make the Thor 2.0 release compatible to SFML 2.2; so you can use this as a lower bound in time.

Why is it so crucial for you to have an officially released version? The documentation and tutorials are available, there are even binaries as nightly builds, you get full support in case of problems...
Title: Re: Thor 2.0
Post by: Mars_999 on August 29, 2014, 07:25:58 pm
Please post link to binaries and source download page...

I don't use any SVN or other way of getting these builds and don't want to hassle with that stuff. I just want to grab and use these libs I don't have time to learn the whole detailed process of grabbing these projects...

I would need VC++ 2013 binaries...

Thanks!
Title: Re: Thor 2.0
Post by: Nexus on August 29, 2014, 07:39:12 pm
You should check the download page, there are the links to the nightly builds.

Have you really waited all this time for binaries that have already been available? :P
Title: Re: Thor 2.0
Post by: Mars_999 on August 29, 2014, 07:44:41 pm
Could NOT find SFML (missing:  SFML_AUDIO_LIBRARY SFML_GRAPHICS_LIBRARY SFML_WINDOW_LIBRARY SFML_SYSTEM_LIBRARY)

-> SFML directory not found. Set SFML_ROOT to SFML's top-level path (containing "include" and "lib" directories).
-> Make sure the SFML libraries with the same configuration (Release/Debug, Static/Dynamic) exist.

Configuring done

error I get on cmake build....
Title: Re: Thor 2.0
Post by: Mars_999 on August 29, 2014, 07:45:06 pm
yes I have been waiting
Title: Re: Thor 2.0
Post by: Mars_999 on August 29, 2014, 08:01:00 pm
Now I get this error on using the Thor build in my project...

1>C:\Programming\Thor-master\include\Thor/Config.hpp(32): fatal error C1083: Cannot open include file: 'Aurora/Config.hpp': No such file or directory


I dont' even see Aurora listed in the master directory?

BTW glad that you are using Cmake and it actually works where most projects it's a hit or miss deal... SO thanks for keeping this clean and workable at least for me.

Please advise on the Aurora/config.h issue...
Title: Re: Thor 2.0
Post by: Mars_999 on August 29, 2014, 08:06:34 pm
Whoops nevermind find out you need to download your header only project. Not sure if this is stated on the front page of the Thor page but would be useful to say so a list of requirements maybe...

Thanks trying it now!!
Title: Re: Thor 2.0
Post by: Hapax on August 29, 2014, 08:49:23 pm
need to download your header only project
I believe Aurora is supplied with Thor. Just looked; it's in the extlibs folder.
Title: Re: Thor 2.0
Post by: MadMartin on August 29, 2014, 10:33:52 pm
When is Thor2.0 going to be done, sorry but I been watching it for years and still nothing is final? This sucks... Please finish it so one can use it in 2.0 final state...
That's gross! Nexus does this in his spare time, without compensation and gives it to you for FREE and you DEMAND that he should speed up the process?

Unbelievable...
Title: Re: Thor 2.0
Post by: zsbzsb on August 30, 2014, 12:11:16 am
Not to mention all this rude bumping of the thread - 4 replies directly after each other. In any forum that had moderators you would seriously be banned for doing something like this.
Title: Re: Thor 2.0
Post by: Mars_999 on August 30, 2014, 12:51:15 am
Not trying to be rude and get off my back about etiquette, I know all about it, I have been watching SFML since before 1.6 even and been watching Thor since before 2.0 was coming and was pumped about the possibilities, I just not getting any younger and with my health failing I would like to make something before I get worse...

Anyway I am not getting into some debate about this crap so don't expect me to reply to anymore comments about these postings.

And yes Nexus thanks A MILLION for the great lib. Just got it working and built it from Cmake builds. Finally your lib and current state of SFML are so much better to work with then others projects in the past when I was trying out SFML what a nightmare, Cmake builds had errors stuff wouldn't compile. So again thank you very much and if I lived by you I would buy you a few beers! :)

Title: Re: Thor 2.0
Post by: tyrion on September 11, 2014, 11:27:01 pm
Back to my previous problem :)
PressOnce and ReleaseOnce denote events (they happen once), while Hold is a real-time state (a state you can query).

Maybe the functions thor::eventAction() and thor::realtimeAction() are interesting for you.

maybe u are interrested in how i solved my problem. If not sry for this post.

it was much easier than i thought to handle the "realtime actions".
After some debugging i found this line in sfml: 
return (GetAsyncKeyState(vkey) & 0x8000) != 0;

i always thought i need a window handle for key events .... :(

Solution:
i have to send only the "GainedFocus" event to activate realtime actions and "LostFocus" to deactivate realtime actions ....
no manual sending of events (because it works without setting a window handle)!

Title: Re: Thor 2.0
Post by: eXpl0it3r on January 16, 2015, 01:16:53 am
Just noticed while building the Nightly Builds that the import libraries get the ".dll.a" suffix, is this intentional or some issue with CMake?
Title: Re: Thor 2.0
Post by: Laurent on January 16, 2015, 07:43:55 am
".dll.a" is the default extension if you don't explicitly change it.
Title: AW: Thor 2.0
Post by: eXpl0it3r on January 16, 2015, 09:20:52 am
I'm aware, question is, should it use that extension given that static libs get differentiated with the -s suffix. ;)
Title: Re: Thor 2.0
Post by: devilswin on March 03, 2015, 06:26:40 pm
Hello, Im on mac and i have SFML working but wen i try to make the build of thor, i get errors for the build, CMAKE can run fine but the issue comes with making it
Title: Re: Thor 2.0
Post by: Jesper Juhl on March 03, 2015, 06:35:28 pm
Maybe you should post the errors you get if you want people to be able to help you...
Title: Re: Thor 2.0
Post by: devilswin on March 03, 2015, 06:48:38 pm
/Users/****/Downloads/Thor-master/src/Particle.cpp:62:38: error:
      invalid operands to binary expression ('sf::Time' and 'sf::Time')
        return getElapsedLifetime(particle) / getTotalLifetime(particle);
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Frameworks/SFML.framework/Headers/System/Time.hpp:364:22: note:
      candidate function not viable: no known conversion from 'sf::Time' to
      'float' for 2nd argument
SFML_SYSTEM_API Time operator /(Time left, float right);
                     ^
/Library/Frameworks/SFML.framework/Headers/System/Time.hpp:376:22: note:
      candidate function not viable: no known conversion from 'sf::Time' to
      'Int64' (aka 'long long') for 2nd argument
SFML_SYSTEM_API Time operator /(Time left, Int64 right);
                     ^
/Library/Frameworks/SFML.framework/Headers/System/Vector2.inl:131:19: note:
      candidate template ignored: could not match 'Vector2<type-parameter-0-0>'
      against 'sf::Time'
inline Vector2<T> operator /(const Vector2<T>& left, T right)
                  ^
/Users/****/Downloads/Thor-master/src/Particle.cpp:67:40: error:
      invalid operands to binary expression ('sf::Time' and 'sf::Time')
        return getRemainingLifetime(particle) / getTotalLifetime(particle);
               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
/Library/Frameworks/SFML.framework/Headers/System/Time.hpp:364:22: note:
      candidate function not viable: no known conversion from 'sf::Time' to
      'float' for 2nd argument
SFML_SYSTEM_API Time operator /(Time left, float right);
                     ^
/Library/Frameworks/SFML.framework/Headers/System/Time.hpp:376:22: note:
      candidate function not viable: no known conversion from 'sf::Time' to
      'Int64' (aka 'long long') for 2nd argument
SFML_SYSTEM_API Time operator /(Time left, Int64 right);
                     ^
/Library/Frameworks/SFML.framework/Headers/System/Vector2.inl:131:19: note:
      candidate template ignored: could not match 'Vector2<type-parameter-0-0>'
      against 'sf::Time'
inline Vector2<T> operator /(const Vector2<T>& left, T right)
                  ^
2 errors generated.
make[2]: *** [src/CMakeFiles/thor.dir/Particle.cpp.o] Error 1
make[1]: *** [src/CMakeFiles/thor.dir/all] Error 2
make: *** [all] Error 2
****-MacBook-Pro-2:Build gabeorlanski$ cd
 
Title: Re: Thor 2.0
Post by: Jesper Juhl on March 03, 2015, 06:49:28 pm
Nobody can help you without knowing
 - the platform you're on
 - the compiler you use
 - the exact error messages you get
 - possibly your actual code
I recommend reading this: http://www.catb.org/esr/faqs/smart-questions.html
Title: Re: Thor 2.0
Post by: devilswin on March 03, 2015, 06:53:00 pm
1 this is Via mac terminal
2 Unix Makefiles
3 Clang is my compiler
4 The code is the build of THOR
Title: Re: Thor 2.0
Post by: Laurent on March 03, 2015, 07:07:52 pm
The important thing to know is your version of SFML. Most likely not SFML 2.2, which is the only version that has this operator.
Title: Re: Thor 2.0
Post by: devilswin on March 03, 2015, 07:09:25 pm
So i got it to build with Xcode by changing in particle.cpp lines 60-68


float getElapsedRatio(const Particle& particle)
{
        return getElapsedLifetime(particle) / getTotalLifetime(particle);
}

float getRemainingRatio(const Particle& particle)
{
        return getRemainingLifetime(particle) / getTotalLifetime(particle);
}
 


to

float getElapsedRatio(const Particle& particle)
{
        return getElapsedLifetime(particle).asMilliseconds() / getTotalLifetime(particle).asMilliseconds();
}

float getRemainingRatio(const Particle& particle)
{
        return getRemainingLifetime(particle).asMilliseconds() / getTotalLifetime(particle).asMilliseconds();
}
 


So yeah, i don't know if this is an unknown bug (Downloaded straight from github). But something doesn't feel right about doing this


The important thing to know is your version of SFML. Most likely not SFML 2.2, which is the only version that has this operator.

It is 2.1, the issue is that by downloading the clang release of 2.2, there is no cmake file, which makes it impossible to install (at least as far as i know)
Title: Re: Thor 2.0
Post by: eXpl0it3r on March 03, 2015, 07:12:21 pm
You're not using SFML 2.2 and thus you're missing the / operator for sf::Time.

As for using this forum: It's not a chat, so don't submit one after the other post, but use the edit function!
Title: Re: Thor 2.0
Post by: devilswin on March 03, 2015, 07:17:27 pm
Sorry for the spam...



But with the way the clang files for 2.2, there is no cmake lists so how would i install it...



There i removed my other comments
Title: Re: Thor 2.0
Post by: Laurent on March 03, 2015, 07:54:30 pm
The CMake files for compiling SFML are in the source code package.
Title: Re: Thor 2.0
Post by: devilswin on March 03, 2015, 09:54:12 pm
So i compiled the SFML 2.2, now i tried compiling the Thor files, however only debug was made and i cannot seem to  be able to use it on QT project, as that is my preferred IDE...
Title: Re: Thor 2.0
Post by: Jesper Juhl on March 03, 2015, 10:54:11 pm
Thor can be build as both debug and release (optimized) - I know that for a fact since I do it regularly myself.

This does the trick for me :
mkdir build && cd build && cmake -DCMAKE_BUILD_TYPE=Release .. && sudo make -j8 install
Title: Re: Thor 2.0
Post by: devilswin on March 04, 2015, 02:21:22 pm
Well, it still has yet to work, so i think i will wait until i boot camp my macbook to begin using thor(the nightly builds make it SO much easiar)
Title: [Thor] Resources revisited
Post by: Nexus on March 25, 2015, 08:45:17 pm
Resources revisited

thor::ResourceCache is a very sophisticated resource manager: it detects when the user wants to load a resource twice and tracks lifetime of all resources as well as itself using shared_ptr and weak_ptr. It allows for different strategies regarding error handling (null pointer or exception) as well as resource release (automatic or explicit).

On the other side, this comes with certain complexity. Due to the lack of an alternative resource system in Thor, many people have seen ResourceCache as a general-purpose resource manager, which it is definitely not. A very common use case in games consists of loading resources initially and using them while the game is running. For these cases, not a lot of functionality is needed. A simple class like the one discussed in our book already does the job pretty well.

Over the years, I have spent considerable thought into resource managing systems, and it's something I find rather difficult to get right, especially when you want to cover lots of different needs. I have also not come across many generic solutions so far (as it is often the case with game-related functionality: most people write code specific to their own needs). I originally planned to add another class in addition to the existing ResourceCache -- this was mainly due to my assumption that because of apparently very different semantics, it would be very hard to combine both. Yesterday, I recognized that the main difference is the ownership, other than that there are many commonalities. Therefore, ResourceCache will cease to exist in its current form and make room for a better approach.

The class template ResourceHolder is an attempt to provide a more flexible and simpler way of handling resources. Resources can be addressed by user-defined IDs. The basic use case looks as follows:
namespace res = thor::Resources;
enum struct TextureType { Grass, Rock };

// Loading
thor::ResourceHolder<sf::Texture, TextureType> textures;
textures.acquire(TextureType::Grass, res::fromFile<sf::Texture>("grass.png"));
textures.acquire(TextureType::Rock, res::fromFile<sf::Texture>("rock.png"));

// Usage
sf::Sprite sprite;
sprite.setTexture(textures[TextureType::Grass]);

Easy, eh? In the basic case, we just have centralized ownership semantics: the ResourceHolder object stores everything, and people can get references to the resources using operator[]. Now to the flexibility part: it is also possible to have shared-ownership semantics as before with ResourceCache. In this case, a reference counter makes sure that the last user cleans up. This implies that there is at least one shared pointer referring to the resource at any time. A third template argument specifies the ownership model, in this case RefCounted.
// Loading and storing in shared pointers
thor::ResourceHolder<sf::Texture, TextureType, res::RefCounted> textures;
std::shared_ptr<sf::Texture> grass = textures.acquire(TextureType::Grass, ...);
std::shared_ptr<sf::Texture> rock = textures.acquire(TextureType::Rock, ...);

// Later, get another shared pointer, either by copying existing one or directly from holder
std::shared_ptr<sf::Texture> rock2 = rock;
std::shared_ptr<sf::Texture> rock3 = textures[TextureType::Rock];

// Now rock, rock2 and rock3 point to the same resource.
// As soon as all of them go out of scope, the resource is released.

// Keep shared pointer alive while in use
sprite.setTexture(*rock2);

The basic functionality is there, I need to perform some further tests and design some special cases. There are also some interesting features one could still add:
Title: Re: Thor 2.0
Post by: Jesper Juhl on March 25, 2015, 10:53:45 pm
@Nexus : cool stuff.  Thor is my favorite SFML add-on library and it just keeps getting better.
Keep up the fantastic work you are doing - it's really excellent!
Title: Re: Thor 2.0
Post by: Nexus on March 26, 2015, 05:30:36 pm
Thank you for the nice feedback! :)

A first version has now been pushed, the documentation (http://www.bromeon.ch/libraries/thor/v2.0/doc/group___resources.html) and the new tutorial (http://www.bromeon.ch/libraries/thor/v2.0/tutorial-resources.html) are meanwhile also online. The latter should give you a good overview about the API's capabilities, feel free to have a look!

Recent changes:
Title: Re: Thor 2.0
Post by: DJuego on March 29, 2015, 05:24:43 pm
Hi! Nexus. Yes! Thank you for your amazing add-on for SFML.  :-*

Today i have tried to build the library with Mingw-Builds(i686-4.9.2-release-win32-sjlj-rt_v4-rev2.7z) from github(last commit: cf93e235233d3cf583babf7939f84f187d4ab546), and...

I get warnings...

(http://i.imgur.com/YGgBhWp.png?1)

and errors...

(http://i.imgur.com/dYbDG6O.png?1)

However There are no problems with Visual Studio 2013 ;D

PS: I am using SFML from github too (last commit: 20f213bfac713c5d98abf6afb6f893c318bc9fdd)

DJuego

Title: Re: Thor 2.0
Post by: eXpl0it3r on March 30, 2015, 11:48:29 am
Doesn't work with SFML master since GLEW was removed. :D

Quote
SFML found but some of its dependencies are missing ( GLEW)
Title: Re: Thor 2.0
Post by: Nexus on March 30, 2015, 11:58:24 am
I just asked myself! SFML is progressing too quickly :D
I'll fix the issues shortly, thanks for the reports :)

And I need to adapt the new FindSFML.cmake module, too...

[Edit] Fixed. There was a typename problem, and apparently only the most recent g++ versions support std::map::emplace(), which is pretty annoying. Now I used std::map::insert() instead, so some people with older compilers are still able to use Thor.
Title: Re: Thor 2.0
Post by: DJuego on March 30, 2015, 03:38:34 pm
Yes!!  :D I confirm that Thor builds correctly now. Thank you for your very swift reaction, Nexus. (!)

Old gcc compiler? Well...

bash-3.1$ gcc --version
gcc.exe (i686-win32-sjlj-rev2, Built by MinGW-W64 project) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


It will be probably a specific problem with MinGW.  ::)

DJuego

Title: Re: Thor 2.0
Post by: eXpl0it3r on April 15, 2015, 11:54:41 pm
While playing around with Thor I noticed that you always pass sf::Time as non-const value.
What exactly is the reasoning behind this? :)
Title: Re: Thor 2.0
Post by: Nexus on April 16, 2015, 12:05:41 am
It wraps a sf::Uint64 value -- and I pass basic types by value, too ;)

I do the same with sf::Vector2f, by the way. Code is more readable, and performance is the same as pass-by-reference -- or even better, if the reference is not optimized away 8)
Title: Re: Thor 2.0
Post by: eXpl0it3r on April 16, 2015, 12:51:58 am
Right. Guess that makes sense then. Thanks for the explanation. :)
Title: Re: Thor 2.0
Post by: Nexus on May 12, 2015, 10:06:04 pm
My plan is to release Thor 2.0 soon, the idea is that it will be compatible with SFML 2.3. For people not willing to build things on their own, this simplifies the process (rather than "use commit xy with commit yz").

There are still a few APIs I consider changing in the near future.
I originally wanted to do all that before Thor 2.0, but that would take quite some time until it's ready. Considering that Thor has already undergone loads of changes (version 2.0 has now been in development for 3 years, and Thor in total almost half a decade!), I think it's reasonable to release a first version, even if the API will change a bit for 2.1.

In general, Thor 2 won't follow an extreme policy regarding backwards compatibility. During development, I have regularly encountered situations where something became just too unflexible, and instead of fixing things up with duct tape, I came up with new, better designs. Notable examples are particle emitters/affectors, resource handling or animation storage. From the feedback I've got, Thor users liked those changes, even though it meant adjusting a few lines of code in their applications :)

Any comments?
Are there things you deem important before Thor 2.0? Severe bugs or bad APIs?
Title: Re: Thor 2.0
Post by: Jesper Juhl on May 13, 2015, 07:15:15 pm
For what its worth; I really like Thor 2.0 in the shape it is currently in.
I'm sure I could find some minor nits to complain about if I really went looking for them, but for the stuff I use the current state of things are just fine and work really well.
Title: Re: Thor 2.0
Post by: Nexus on May 14, 2015, 01:55:34 pm
Okay, thanks! Out of interest, which APIs in Thor are you using?
Title: Re: Thor 2.0
Post by: Jesper Juhl on May 14, 2015, 02:10:24 pm
In my current project I'm using these modules:
 Animations
 Particles
 Resources
 Vectors

I've been considering the Input module as well since it could probably simplify my curent input handling, but I have not yet gotten around to playing with it.
Title: VS 2015 users needed!
Post by: Nexus on June 14, 2015, 05:22:23 pm
A Thor user reported a problem inside thor::ResourceHolder on Visual Studio 2015 Community RC. More clearly, an internal STL assertion occurs in ResourceHolder.inl (line 130) during the destruction of an iterator.

Since I don't have this compiler version and would prefer not to install it just for a single issue, I wanted to ask whether a VS 2015 user would be willing to test the code and see if the error can be reproduced, and if there's an obvious problem? Thanks in advance :)
#include <Thor/Resources.hpp>

struct Resource {};

int main()
{
        auto lambda = [] () { return std::make_unique<Resource>(); };
        thor::ResourceLoader<Resource> loader(lambda, "some info");

        thor::ResourceHolder<Resource, int> holder;
        holder.acquire(3, loader);
}
Title: Re: Thor 2.0
Post by: SpeCter on June 14, 2015, 07:50:33 pm
I can confirm that the error can be reproduced.
I used latest git version for both sfml and thor to test it out.
Doesn't seem like an obvious problem for me at least.
Title: Re: Thor 2.0
Post by: dabbertorres on June 14, 2015, 08:03:30 pm
I've seen bits and pieces of the changelog for 2015. They've done a fair amount of changes with templates and such... Could be a bug. It is just a release candidate after all.
Title: Re: Thor 2.0
Post by: Nexus on June 14, 2015, 08:12:19 pm
Thanks! Might be worth investigating then.

It's much worse if there's a bug in the VS 2015 compiler or the standard library than in Thor.
Title: Re: Thor 2.0
Post by: SpeCter on June 14, 2015, 08:16:50 pm
If you need anything else, just say so. Now that I installed it and compiled all libraries I prefer to make it worthwhile xD
Title: Re: Thor 2.0
Post by: dabbertorres on June 14, 2015, 08:55:35 pm
I know of a user on Reddit who works on the VS compiler/standard library (may just be the standard library, can't remember exactly). I could try messaging him to ask about it, if you like.

He'll prolly want a sscce.
Title: Re: Thor 2.0
Post by: SpeCter on June 14, 2015, 09:00:35 pm
My guess would be that you are referring to STL(not the library) :D
Title: Re: Thor 2.0
Post by: Nexus on June 14, 2015, 09:45:33 pm
SpeCter, that's really nice of you, thanks! :)

I'd like to track down the problem to a minimal complete example with just a main() function, and without Thor. So if it is indeed a VS 2015 problem, I could report it at Microsoft Connect, and they can hopefully fix it for the full release.

The original code in thor::ResourceHolder::load() is a bit convoluted because of genericity with multiple ownership strategies. Simplified, it's roughly equivalent to these lines:
#include <map>
#include <memory>

struct R {};
typedef std::map<int, std::unique_ptr<R>> Map;

R& load(Map& map, int id)
{
        std::unique_ptr<R> original = std::make_unique<R>();
        auto inserted = map.insert(std::make_pair(id, nullptr)).first;

        std::unique_ptr<R> loaded = std::move(original);
        R& returned = *loaded;

        inserted->second = std::move(loaded);

        return returned;
}

int main()
{
        Map map;
        load(map, 3);
}

Can you tell me if this still reproduces the error (I guess not :D). If it does, can you further minimize it? That is, try as many of the following omissions as possible, as long as the code still reproduces the error:
Title: Re: Thor 2.0
Post by: dabbertorres on June 14, 2015, 09:49:36 pm
My guess would be that you are referring to STL(not the library) :D

You would be correct! Haha.

If that indeed does reproduce, SpeCter or I could message him then I guess. He may be able to fast-forward a fix, that's why I mentioned him as a possibility. Haha.
Title: Re: Thor 2.0
Post by: SpeCter on June 14, 2015, 10:02:06 pm
Your guess was right,it does not reproduce the error  :(
Title: Re: Thor 2.0
Post by: Nexus on June 15, 2015, 03:54:11 pm
Of course, would have been too easy ;)

I eventually decided to install VS 2015 RC myself, tried this code (http://en.sfml-dev.org/forums/index.php?topic=7329.msg132294#msg132294), and could reproduce the issue. It seems to be a bug in the debug iterator checks of the STL implementation. The following code shows the problem (for std::vector as well as for std::map):
#include <vector>
typedef std::vector<int> Vector;

struct Wrapper
{
        Vector::iterator itr;
};

Wrapper BadWrap(Vector::iterator itr) // triggers issue
{
        return {itr};
}

Wrapper GoodWrap(Vector::iterator itr) // works fine
{
        Wrapper w = {itr};
        return w;
}

int main()
{
        Vector v = {1};
        Wrapper w = BadWrap(v.begin());
} // access violation during destruction of v

I filed a bug report at Microsoft Connect (https://connect.microsoft.com/VisualStudio/feedback/details/1436301). If anybody of you wants to inform Stephan T. Lavavej, feel free to do so :)

Thanks to both of you (and the guy who originally reported the problem) for your assistance!
Title: Re: Thor 2.0
Post by: omnomasaur on June 23, 2015, 03:04:37 am
Is it possible to set up the particle color on an emitter to pull randomly from a gradient?

UniversalEmitter::setParticleColor takes a Distribution<sf::Color>, but I can't figure out how to actually use that to get different colors. 
Title: Re: Thor 2.0
Post by: Nexus on June 23, 2015, 01:10:28 pm
Yes, it's possible. A distribution is just a function returning a value.
thor::ColorGradient gradient = ...;
thor::Distribution<sf::Color> dist = [gradient] () -> sf::Color
{
    return gradient.sampleColor(thor::random(0.f, 1.f));
};

It may be worthwhile to not use the global random number generator, and instead store a Distribution<float> within the function object.
Title: Re: Thor 2.0
Post by: Hiura on June 29, 2015, 10:29:32 am
Hey Nexus, I've spotted an issue with unsigned int/size_t being mixed in header and source files with the current master.

Here's a quick patch that makes sure the declaration and implementation signatures match (I chose to keep unsigned int but that was totally arbitrary):

diff --git a/src/Emitters.cpp b/src/Emitters.cpp
index 6af1b27..1887689 100644
--- a/src/Emitters.cpp
+++ b/src/Emitters.cpp
@@ -105,12 +105,12 @@ void UniversalEmitter::setParticleColor(Distribution<sf::Color> particleColor)
        mParticleColor = std::move(particleColor);
 }
 
-void UniversalEmitter::setParticleTextureIndex(Distribution<std::size_t> particleTextureIndex)
+void UniversalEmitter::setParticleTextureIndex(Distribution<unsigned int> particleTextureIndex)
 {
        mParticleTextureIndex = std::move(particleTextureIndex);
 }
 
-std::size_t UniversalEmitter::computeParticleCount(sf::Time dt)
+unsigned int UniversalEmitter::computeParticleCount(sf::Time dt)
 {
        // We want to fulfill the desired particle rate as exact as possible. Since the amount of emitted particles per frame is
        // integral, we have to emit sometimes more and sometimes less. mParticleDifference takes care of the deviation each frame.
diff --git a/src/ParticleSystem.cpp b/src/ParticleSystem.cpp
index 4cb024c..5a61c5d 100644
--- a/src/ParticleSystem.cpp
+++ b/src/ParticleSystem.cpp
@@ -112,7 +112,7 @@ void ParticleSystem::setTexture(const sf::Texture& texture)
        mNeedsQuadUpdate = true;
 }
 
-std::size_t ParticleSystem::addTextureRect(const sf::IntRect& textureRect)
+unsigned int ParticleSystem::addTextureRect(const sf::IntRect& textureRect)
 {
        mTextureRects.push_back(textureRect);
        mNeedsQuadUpdate = true;
Title: Re: Thor 2.0
Post by: Nexus on June 29, 2015, 07:57:58 pm
Thanks! I fixed that.

Did you test on OS X? If so, are there other configuration issues or compiler warnings/errors on that platform?
Title: Re: Thor 2.0
Post by: Hiura on June 30, 2015, 08:47:36 am
Actually it was on Ubuntu 15.04 x86_64 with clang 3.6 & libc++ 3.6 (so it should be very similar to OS X). Once my mac is repaired I will test it.  ;)

But that was the only error I got. I didn't add any specific warning flags though. If you want me to build it with some additional warning flag let me know.
Title: Re: Thor 2.0
Post by: Nexus on July 02, 2015, 06:39:12 pm
I can eventually test Ubuntu, just not after every single commit 8)

But I'd be really glad about feedback from OS X... Also regarding compiler warnings. Important are those that occur when compiling Thor (without changing flags) as well as when using it (with -Wall and possibly others). But having a look at the SDK examples is more than enough, I'd truly appreciate that :)

Do you have a rough estimate when your Mac is repaired? I'm asking because I've been planning to release Thor 2.0 for some time already ;) of course, if there's anybody else with OS X, that would be very nice, too!
Title: Re: Thor 2.0
Post by: Hiura on July 02, 2015, 07:03:31 pm
I'll try to remember to test it when I get my mac back but it might take a while; they told me it can stay in shop for about a month but I'll also need to reinstall everything when I get it back because when I gave it to them the HDD got corrupted.. like having some battery issue wasn't enough. ^^'

Additionally, I just started a new job so I don't know how much time I'll have during this summer. So it's probably safer not to delay Thor 2.0 just for my feedback.

Anyhow, if someone else's got a mac close by, it's really easy to set it up and test it so you should do it!  ;D
Title: Re: Thor 2.0
Post by: Nexus on July 03, 2015, 09:13:48 am
Don't worry... If needed I can still adapt things after Thor 2.0. I think I'll focus on that release for the next time ;)
Title: Re: Thor 2.0
Post by: Foaly on July 10, 2015, 02:01:39 pm
Hello there!

I don't know if this is the right thread for this, but I have a problem compiling Thor.
I have pulled the lasted github version, configured cmake to point to SFML (2.3.0) and then generated two seperate debug and release projects (codeblocks).
When I open the debug project, compile and install it everything works as intended. But when I try to compile the release project, I get the following compile error:

Code: [Select]
cd /d F:\Librarys\Thor\Build\Release\src && C:\MinGW\bin\g++.exe   -DTHOR_EXPORTS -Dthor_EXPORTS -std=c++0x -O3 -DNDEBUG @CMakeFiles/thor.dir/includes_CXX.rsp   -o CMakeFiles\thor.dir\Action.cpp.obj -c F:\Librarys\Thor\Thor\src\Action.cpp
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\cmath:44:0,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\random:38,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\stl_algo.h:65,
                 from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\algorithm:62,
                 from F:/Librarys/official_SFML/install/include/SFML/System/Utf.hpp:32,
                 from F:/Librarys/official_SFML/install/include/SFML/System/String.hpp:32,
                 from F:/Librarys/official_SFML/install/include/SFML/Window/Joystick.hpp:32,
                 from F:/Librarys/Thor/Thor/include/Thor/Input/Joystick.hpp:34,
                 from F:/Librarys/Thor/Thor/include/Thor/Input/Detail/ActionOperations.hpp:29,
                 from F:/Librarys/Thor/Thor/include/Thor/Input/Action.hpp:32,
                 from F:\Librarys\Thor\Thor\src\Action.cpp:26:
c:\mingw\include\math.h: In function 'float hypotf(float, float)':
c:\mingw\include\math.h:635:30: error: '_hypot' was not declared in this scope
 { return (float)(_hypot (x, y)); }
                              ^

According to this SO (https://stackoverflow.com/questions/29450016/o1-2-3-with-std-c1y-11-98-if-cmath-is-included-im-getting-error-hypo) its a MinGW compiler bug (I am using gcc 4.8.1 on windows). I fixed it like the first answer sugessted, but I was wondering, why is Thor using the flag -std=c++0x and not -std=c++11 ? It doesn't make a difference in this case, but I just noticed that. (also I wanted to show other people a solution, who might run into the same problem)
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 10, 2015, 02:21:05 pm
The simple solution to your problem is to upgrade GCC. If a software has a bug that's preventing your from working on things and there's a newer version of said software released, it's better to upgrade than to work around the bug.

I assume Thor uses -std=c++0x to be compatible with older compilers which do not have the -std=c++11 flag.
Title: Re: Thor 2.0
Post by: Nexus on July 10, 2015, 02:21:49 pm
Code: [Select]
... C:\MinGW\bin\g++.exe   -DTHOR_EXPORTS -Dthor_EXPORTS -std=c++0x ...
Why are you defining those export macros, of which one is even wrong? They're not documented for a reason, CMake and Config.hpp take care of everything.

I was wondering, why is Thor using the flag -std=c++0x and not -std=c++11?
Early C++11 compilers did not recognize -std=c++11.
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 10, 2015, 02:36:05 pm
Why are you defining those export macros, of which one is even wrong? They're not documented for a reason, CMake and Config.hpp take care of everything.
I doubt that he wrote these commands. This is one of the command generated by CMake.
Title: Re: Thor 2.0
Post by: Nexus on July 10, 2015, 02:45:38 pm
In that case, I don't remember giving CMake the instruction of defining thor_EXPORTS, there's only THOR_EXPORTS (https://github.com/Bromeon/Thor/blob/master/CMakeLists.txt#L46).

Is that another one of these implicit CMake "features"? ::)
Title: Re: Thor 2.0
Post by: eXpl0it3r on July 10, 2015, 03:15:32 pm
I just mark it as "CMake magic" and forget about it. You'd hope that CMake generates clean make and project files, but truth be told, the generated build files are messy and not really "reusable". It's fine if you just want to build and forget, but if you want to see what's going on, you better buckle up. :P
Title: Re: Thor 2.0
Post by: dabbertorres on July 10, 2015, 08:38:13 pm
its a MinGW compiler bug (I am using gcc 4.8.1 on windows)
I recommend upgrading too. I like this distro (http://nuwen.net/mingw.html). It's not ancient (it's gcc 5.1.0, which has support for almost all of C++11 and 14) (*cough* "official" mingw and mingw-64 *cough*), doesn't have any odd quirks (*cough* TDM *cough*), and it's much more... friendly to Unix users (no weird "gotchas" of being on Windows), in my experience.
Title: Re: Thor 2.0
Post by: Jesper Juhl on July 10, 2015, 09:25:01 pm
This is where I just can't help myself and have to mention SCons (http://www.scons.org/)  ;)
Yeah, CMake does work and solves a problem, but its internals are nasty and their own custom scripting language just makes me go "yuck". SCons is so much nicer and uses a sane scripting language (Python) rather than inventing their own.. Check it out; you'll be glad you did :)
Title: Re: Thor 2.0
Post by: Nexus on July 11, 2015, 07:51:51 pm
I plan to release Thor 2.0 in the next days, so if you still see serious issues with the latest commit, you should tell me now ;)

Feedback/testing is of course highly appreciated!
Title: Re: Thor 2.0
Post by: Jesper Juhl on July 11, 2015, 09:27:47 pm
Go for it!
I've been using git snapshots of your library for a long time and my judgement is that it's more than ready (I know few developers who write as high-quality C++ code as you do). :)
Fix up any minor issues in a 2.1 release , but just ship the damn thing now as 2.0 ;)
Title: Re: Thor 2.0
Post by: Nexus on July 11, 2015, 09:38:50 pm
Thanks for the nice feedback again, Jesper :)

Yes, it's so annoying, I have wanted to release it for such a long time already, but there were always issues (like triangulation bugs) that would come up unexpected, or then I was short on time... And there are still some designs I'm not 100% happy with, but I'd rather change the API slightly after 2.0 than be stuck with bad things for years ;)
Title: Re: Thor 2.0
Post by: Jesper Juhl on July 11, 2015, 09:53:35 pm
There will always be bugs. The thing to realise (in my experience) is that there are bugs and then there are show-stopper bugs. You can always ship/release with bugs - that's just how things are. What you don't want is to ship with major show-stopper bugs. And I don't think you are in that risk category :)
Title: Re: Thor 2.0 released!
Post by: Nexus on July 12, 2015, 01:00:33 pm
Took a decent amount of time, but I'm finally able to announce:

Thor 2.0
[-> Download] (http://www.bromeon.ch/libraries/thor/download.html)

Almost everything has changed in the last three years, some parts multiple times. A few examples:
As mentioned multiple times, I won't maintain a strict API backwards compatibility policy. I thought long about this, and my conclusion was that for Thor users, API quality is my absolute priority; see also my reasoning here (http://en.sfml-dev.org/forums/index.php?topic=7329.msg130476#msg130476).

Anyway, have fun 8)
Title: Re: Thor 2.0 released!
Post by: Laurent on July 12, 2015, 01:11:10 pm
I wonder if it took longer than SFML 2 :P
Title: Re: Thor 2.0 released!
Post by: eXpl0it3r on July 12, 2015, 02:05:41 pm
Yay! :)

Congratulation on the release.
Title: Re: Thor 2.0 released!
Post by: Hapax on July 12, 2015, 05:37:13 pm
Congratulations!  :)
Title: Re: Thor 2.0 released!
Post by: UroboroStudio on July 12, 2015, 05:53:10 pm
Nice! Good job Nexus!  :)
Title: Re: Thor 2.0 released!
Post by: Jesper Juhl on July 12, 2015, 11:01:58 pm
Congratulations on wrapping up Thor 2.0.
It's a great improvement. Works well. And complements SFML very nicely.
Title: Re: Thor 2.0 released!
Post by: Nexus on July 12, 2015, 11:36:25 pm
Thanks for all the nice comments! Also thanks for Laurent's comment ;D

No, really, thank you for all the constructive feedback you've given me in the past years. This thread alone is a great example, so are the dozens of e-mails and private messages. And I truly appreciate the additional services for Thor, like eXpl0it3r's nightly builds or zsbzsb's NetEXT C# port! :)

Something very interesting for me would be to see how and where Thor is used. It would also show me different use cases, which I can incorporate in future API design. I've seen a few projects here and on GitHub... If you have an example where Thor helps achieve some features in a game or multimedia application, that would be nice to know 8)
Title: Re: Thor 2.0 released!
Post by: Jesper Juhl on July 13, 2015, 12:05:50 am
I don't have code to show you (it's just not ready yet), but I can tell you that Thor has saved me a bunch of time from not having to write my own animation code, giving me an easy way to deal with input remapping and letting me implement some nice particle effects in a couple of hours rather than days. And more.
I hope to finish my little game project before my 40'th birthday (in april) and although it probably won't be open source (initially) I guess I could give you a copy to see how I used Thor :)
Title: Re: Thor 2.0 released!
Post by: JackPS9 on August 30, 2015, 08:04:21 pm
Can someone help me out with a rain/snow particle system?
I have an emitter working, but the problem is I can't figure out what would be the best way to go about it.
Title: Re: Thor 2.0 released!
Post by: LanceJZ on October 11, 2015, 04:37:47 am
This works fine with the new release of SFML 2.3.2? I'm about to compile it. Thank you for your time.
Title: Re: Thor 2.0 released!
Post by: bjadams on October 22, 2015, 01:42:11 pm
Most probably the most useful lib after SFML itself!

I am reading the book SFML Essentials and I am glad that Thor has done a more complete Asset Manager & Animation system than the basic one described in the book

Hope this lib will continue to be developed
Title: Re: Thor 2.0 released!
Post by: Nexus on October 22, 2015, 01:53:22 pm
Thank you! Development will definitely continue ;)

I have already started to implement some bigger improvements in the Animations module. I'll push them once I've got something usable :)
Title: Re: Thor 2.0 released!
Post by: Nexus on October 26, 2015, 12:36:24 am
I added Thor 2.0 binaries for Visual Studio 2015.
-> Download page (http://www.bromeon.ch/libraries/thor/download.html)
Title: Re: Thor 2.0 released!
Post by: bjadams on October 27, 2015, 11:35:41 pm
just in time for me to start using sfml + thor!
Title: [Thor] New Animator API
Post by: Nexus on December 29, 2015, 10:54:26 am
It has been a while since the last update. As I mentioned already a few times, I wasn't exactly happy with some limitations of the Animations module, for example the need to copy animations for every animator or to manually track progress, e.g. to know when an animation has finished. In the meantime, I have addressed many of those issues. That's why I'm now announcing a major improvement of the thor::Animator API.


Animation maps

The Thor 2.0 Animator stores all the animations and tracks a progress. Since different animated objects (e.g. sprites) have different animation progress, one needs to duplicate the Animator instance, and with it all the stored animations. Thor 2.1 changes this by splitting the functionality in two classes: Animator that tracks progress and animates an object, and AnimationMap which stores the animations. The former references the latter. Animation maps are resource-style classes, this separation is comparable to sf::Sprite and sf::Texture.
thor::AnimationMap<sf::Sprite, std::string> animations;
animations.addAnimation("anim1", ...);

thor::Animator<sf::Sprite, std::string> animator(animations);


Queued animations

It is now finally possible to queue multiple animations. Thus, one need no longer keep track of an animation, and code like if (finished) startNewAnimation() is history. The API is very simple and expressive, thanks to operator overloading. The play() function plays some animations and resets the queue, the queue() function appends to the end.
thor::Animator<sf::Sprite, std::string> animator;

// Play anim1, then anim2
animator.play() << "anim1" << "anim2";

// Append further animations to the queue
animator.queue() << "anim3";


Playback schemes and notifications

Another new feature are playback schemes. They give more control over the playback of animations. So far, I have implemented repeat() to repeat an animation a finite number of times and loop() to repeat it indefinitely. They're very easy-to-use with the queue syntax (which was not straightforward to implement, there's some heavy metaprogramming behind the scenes):
// Play one animation, then 3 times another, then loop a third one
animator.play()
   << "anim1"
   << thor::Playback::repeat("anim2", 3)
   << thor::Playback::loop("anim3");

Furthermore, you can be notified when an animation starts or finishes. You can register a callback that does virtually anything. The SDK example uses it to output the playing animation. On the other hand, explicit polling functions like isPlayingAnimation() and getPlayingAnimation() have been removed.
animator.play()
   << "anim1"
   << thor::Playback::notify([] () { std::cout << "Finished!\n"; });


Keep in mind that this entire API is generic. You don't have to use it to animate SFML objects, you can do anything it permits. It needn't even be an animation, you can also use it for other logic that is updated based on a progress.

You can get an overview over the new functionality on my homepage (http://www.bromeon.ch/libraries/thor/v2.1/doc/group___animations.html). You can directly use it by checking out the latest revision on GitHub (https://github.com/Bromeon/Thor). Have fun! :)
Title: Re: Thor 2.0 released!
Post by: Elias Daler on December 29, 2015, 10:31:41 pm
Nice update!

I was thinking about the issue of copying animation data not long ago and it's nice to see that you thought about the same stuff as well. :D

Playback shemes / queueing has very nice design that I may try to implement for my engine somewhere in the future. Looks very clean and makes it so much easier than constantly checking which animation is playing at the moment. This design might be useful for doing cutscenes and music playlists too! :)

Title: Re: Thor 2.0 released!
Post by: AlexxanderX on December 30, 2015, 10:14:33 am
It would be nice if you could separate in modules the library, like SFML. For my game I want just to use the ResourceManager. Anyway, nice ResourceManager implementation.  :D
Title: Re: Thor 2.0 released!
Post by: Nexus on December 30, 2015, 10:20:21 am
Playback shemes / queueing has very nice design that I may try to implement for my engine somewhere in the future.
You can also just use it instead of re-implementing the same design ;)

In fact, that would help me much more, because then I see how Thor is used in the real world. If people want to achieve something, they try to exploit the available API to its limits, and don't just write their own workarounds. If something isn't possible, such feedback is very valuable for me -- I can use it to improve the API, and other users can benefit as well. If everybody just copies the code or writes his own variation, Thor won't progress.


This design might be useful for doing cutscenes and music playlists too! :)
Yes. Reusable design was a core criterion when writing this, it's very likely that I'm going to use some parts when I write the music players in Thor.


It would be nice if you could separate in modules the library, like SFML. For my game I want just to use the ResourceManager.
I thought about this, but the modules are too small and there are already 9 (and this number will grow in the future). It would add a lot of complexity to link everyone of them separately and get the dependencies right, for little benefit. There should not be a big issue with using only the resource managers -- it's not as if you carry Thor's entire weight in your application. Linkers are smart enough to exclude the parts that are not used.

Concerning thor::ResourceHolder in particular, a lot of it should be header-only, if I remember correctly. So you may not even have to link Thor.


Anyway, nice ResourceManager implementation.  :D
Thanks :)
Title: Re: Thor 2.0 released!
Post by: AlexxanderX on December 30, 2015, 02:03:55 pm
I get this warning when using the Aurora that come with Thor:
Quote
In file included from E:/Work/Programare/Libs/Thor/include/Thor/Resources/OwnershipModels.hpp:34:0,
                 from E:/Work/Programare/Libs/Thor/include/Thor/Resources.hpp:32,
                 from E:/Work/Programare/Apps/CPP/Katan/Client/include/States/StateMachine.hpp:9,
                 from E:\Work\Programare\Apps\CPP\Katan\Client\src\States\StateMachine.cpp:1:
E:/Work/Programare/Libs/Thor/include/Thor/Resources/OwnershipModels.hpp: In member function 'void thor::detail::TrackingDeleter<R, Map>::operator()(R*)':
E:/Work/Programare/Libs/Thor/extlibs/aurora/include/Aurora/Meta/Templates.hpp:188:57: warning: typedef 'auroraRequireCompleteType' locally defined but not used [-Wunused-local-typedefs]
 #define AURORA_REQUIRE_COMPLETE_TYPE(Type) typedef char auroraRequireCompleteType[(sizeof(Type))]
                                                         ^
E:/Work/Programare/Libs/Thor/include/Thor/Resources/OwnershipModels.hpp:105:4: note: in expansion of macro 'AURORA_REQUIRE_COMPLETE_TYPE'
    AURORA_REQUIRE_COMPLETE_TYPE(R);
Title: Re: Thor 2.0 released!
Post by: Jesper Juhl on December 30, 2015, 02:16:47 pm
Great news Nexus. I look forward to playing with the new Thor - expecting it to be excellent as always ;)
Title: Re: Thor 2.0 released!
Post by: Elias Daler on December 30, 2015, 03:18:22 pm
Playback shemes / queueing has very nice design that I may try to implement for my engine somewhere in the future.
You can also just use it instead of re-implementing the same design ;)

In fact, that would help me much more, because then I see how Thor is used in the real world. If people want to achieve something, they try to exploit the available API to its limits, and don't just write their own workarounds. If something isn't possible, such feedback is very valuable for me -- I can use it to improve the API, and other users can benefit as well. If everybody just copies the code or writes his own variation, Thor won't progress.
Yeah, seeing such cool changes is making me think about using your library. You see, I'm just learning a lot more when I implement my own stuff but now I think that I can use some help with your lib. :D
I'm thinking about doing a smaller project some time soon and I'll use Thor for it for different stuff and if I'm comfortable enough with it, I'll use it in Re:creation.
Title: [Thor] New Animator API
Post by: Nexus on December 30, 2015, 04:55:33 pm
@AlexxanderX: I fixed the warning in Aurora (but it's not merged to Thor yet). If you need to get rid of it now, copy the Aurora include files to Thor's extlib directory, overwriting the existing ones.

@Jesper Juhl: Thanks for the confidence :)

@Elias Dialer: Alright, let me know in case you have questions!
Title: Re: Thor 2.0 released!
Post by: FRex on January 03, 2016, 02:31:47 pm
I've noticed when browsing that two dates on http://www.bromeon.ch/index.html say 2016 instead of 2015 (or Thor is literally the software of the future).
Title: Thor 2.0 released!
Post by: eXpl0it3r on January 03, 2016, 04:27:18 pm
Guess the search + replace backfired. :P
Title: Re: Thor 2.0 released!
Post by: Nexus on January 03, 2016, 04:57:08 pm
Indeed, thanks! That went really fast :)
Title: Re: Thor 2.0 released!
Post by: Kojay on January 19, 2016, 01:15:03 am
Hello,

I am looking to implement ctrl+tab and shift+tab shortcuts in an application, with the help of Thor.Input. However, only the former works. This is a minimal example that reproduces the behavior:

#include <Thor/Input.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <iostream>

enum class Action{
    Close,
    ShiftTab,
    CtrlTab
};

int main()
{
    sf::RenderWindow window(sf::VideoMode(800,600),"SFML with Thor");
    window.setFramerateLimit(60);

    thor::ActionMap<Action> actionMap;
    thor::ActionMap<Action>::CallbackSystem system;

    actionMap[Action::Close] = thor::Action(sf::Event::Closed);
    system.connect(Action::Close, std::bind(&sf::RenderWindow::close, &window));

    thor::Action lctrl(sf::Keyboard::LControl, thor::Action::Hold),
                 rctrl(sf::Keyboard::RControl, thor::Action::Hold),
                 lshift(sf::Keyboard::LShift, thor::Action::Hold),
                 rshift(sf::Keyboard::RShift, thor::Action::Hold),
                 tab(sf::Keyboard::Tab, thor::Action::PressOnce);

    auto ctrl = lctrl || rctrl;
    auto shift = lshift || rshift;

    actionMap[Action::CtrlTab] = ctrl && tab;
    system.connect0(Action::CtrlTab, [](){
        std::cout << "CtrlTab" << std::endl;
    });

    actionMap[Action::ShiftTab] = shift && tab;
    system.connect0(Action::ShiftTab, [](){
        std::cout << "ShiftTab" << std::endl;
    });

    while (window.isOpen()){
        actionMap.update(window);
        actionMap.invokeCallbacks(system, &window);

        window.clear();
        window.display();
    }
}
 

CtrlTab appears on stdout everytime Ctrl+Tab is pressed; Shift+Tab does not. Instead, shift key by itself works.
Any clues would be appreciated.
Title: Re: Thor 2.0 released!
Post by: Nexus on January 19, 2016, 10:55:11 pm
Hm... I can't imagine how this could be related to Thor, as I don't treat the keys differently. Can you reproduce the same behavior with SFML alone (with sf::Keyboard for Shift and sf::Event for Tab)?

Might Shift+Tab be a special combination of your OS or a running application, similar to Alt+Tab?
Title: Re: Thor 2.0 released!
Post by: Kojay on January 20, 2016, 06:47:25 am
You are correct. This reproduces the issue

if (event.type == sf::Event::KeyPressed){
    if (event.key.code == sf::Keyboard::Tab){
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
            std::cout << "ShiftTab" << std::endl;
    }
}
if (event.type == sf::Event::KeyPressed){
    if (event.key.code == sf::Keyboard::Tab){
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::LControl))
            std::cout << "CtrlTab" << std::endl;
    }
}
 

I will test this on other OS/desktop. However, Shift+Tab does work fine for other applications (ie Firefox).

Edit: I will also add that the issue persists with this code
if (event.type == sf::Event::KeyPressed){
    if (event.key.code == sf::Keyboard::Tab){
        if (event.key.control)
            std::cout << "CtrlTab" << std::endl;
        if (event.key.shift)
            std::cout << "ShiftTab" << std::endl;
    }
}
 

Update: this was an SFML problem (didn't return the correct code) which has been fixed for a while
Title: Re: Thor 2.0 released!
Post by: eXpl0it3r on March 11, 2016, 10:24:18 am
Have you ever thought about adding asynchronous resource loading?
Title: A promising future
Post by: Nexus on March 11, 2016, 02:04:27 pm
I have, but not in detail yet... At the moment, the thor::ResourceHolder is not really designed for asynchronous loading, as it returns resources instantly. I think the nicest asynchronous implementation would base on promises and futures, so that a client can asynchronously request the loading at startup, and access the loaded resource at a later stage, as well as check the state in between.

Aren't there several issues with SFML resources being loaded from other threads, especially textures? Since Thor is almost always used together with SFML, this is something I have to keep in mind.
Title: Re: A promising future
Post by: eXpl0it3r on March 11, 2016, 02:18:32 pm
I think the nicest asynchronous implementation would base on promises and futures, so that a client can asynchronously request the loading at startup, and access the loaded resource at a later stage, as well as check the state in between.
That what I've been thinking of as well.

Aren't there several issues with SFML resources being loaded from other threads, especially textures? Since Thor is almost always used together with SFML, this is something I have to keep in mind.
I guess sf::Texture can't/shouldn't be used directly. It would be nice to just load the image from disk into RAM and when used first or so, you move the image data from RAM to VRAM. This would be good enough in most cases since loading from disk is usually the bottleneck.
For sf::Font I just had a look at the implementation and it seems like loadFrom* doesn't use OpenGL, so this may work without problems.
I assume sf::SoundBuffer would work fine too, but I don't know what the threading restraints are.
sf::Image, no problem.
And for sf::Shader I have no idea.
Title: Re: Thor 2.0 released!
Post by: DurtyFree on May 15, 2016, 02:32:34 am
I have some questions regarding the animations library.

It seems like I am not able to play differrent animations for different sprites at the same time.
I have 2 entities ( 1 Player, 1 NPC ), the players movement is triggered by user input. The NPC just moves to random coordinates. Both entities call a function from my AnimationHandler => PlayAnimation(string animationId, Sprite sprite, bool loop = false), where animationId is the id of the animation to play on the given sprite.
This function runs PlayAnimation(animationId, loop) on the animator and adds the given Sprite to a list.

Then in the game loop I call the animate and the update function of my AnimationHandler, the update function triggers the update of the animator, the animate function runs trough a list of sprites and animates them.

This works perfect for 1 entity, but as i try to handle 2 entities with different animations running, it doesnt seem to work. How am I able to build an working AnimationHandler for more than 1 entity?

//Edit:
I already fixed my problem.
Title: Re: Thor 2.0 released!
Post by: Nexus on May 20, 2016, 11:40:48 pm
//Edit:
I already fixed my problem.
You should explain how, for future readers.

In general, you're supposed to use one thor::Animator instance per object you want to animate. Every animator stores its own independent state of the animation. The animations themselves are stored in a thor::AnimationMap object, which is referenced by thor::Animator.

-> Documentation (http://www.bromeon.ch/libraries/thor/documentation/v2.1/group___animations.html)
Title: Re: Thor 2.0 released!
Post by: eXpl0it3r on July 14, 2016, 05:25:55 pm
We need updated tutorials for the in-development version! ;)
Title: Re: A promising future
Post by: Ungod on July 15, 2016, 09:55:43 pm
Aren't there several issues with SFML resources being loaded from other threads, especially textures? Since Thor is almost always used together with SFML, this is something I have to keep in mind.

I use (my own) multithreaded-ressource loader for (sfml-)textures and it works quiet well until now, but its unfinished. It works with callbacks, instead of futures, means that the method that requests a resources gets a lambda-expression that is invoked for the texture once its loaded (you can attach the texture to a sprite in there or something like that).

Post any progress in terms of multitreading you may make here, if you like. I would appreciate it. :)
Title: Re: Thor 2.0 released!
Post by: Kojay on July 30, 2016, 03:17:51 pm
Used Thor to make an animation between two points (https://kojirion.github.io/2016/07/30/Move-animation-and-sliding-console.html). This brought up some thoughts:

- Interpolation schemes - I think you have talked about including such in Thor. Is this something we could expect in the short-term, or should we be looking elsewhere?

- Parallel animations - It doesn't look like a single animator can play animations in parallel (only in internal edge cases). Is the only way to do this to compose them manually? Would using two animators be reliable enough?

- Inability to query animator status - The docs state this is by design, however the rationale behind this design isn't so clear. In the example in my post, I wished to ignore the keypress while the animation was playing; so this had to be tracked externally and updated with the callback mechanism. A lot of verbosity that would be eliminated by querying whether there's an active animationn. Meanwhile, internally this looks to be as simple as returning mPlayingAnimations.empty().

I realise the example is simple, however in a larger application one could keep distinct animators - according to the role - and thus still obtain useful information from this query.

Other animation APIs do offer such functionality. Could you clarify why you deem it best not to provide it? Do you have a better design in mind to achieve the intention in the example?
Title: Re: A promising future
Post by: Zentropy on August 19, 2016, 07:38:44 am
Aren't there several issues with SFML resources being loaded from other threads, especially textures? Since Thor is almost always used together with SFML, this is something I have to keep in mind.

I use (my own) multithreaded-ressource loader for (sfml-)textures and it works quiet well until now, but its unfinished. It works with callbacks, instead of futures, means that the method that requests a resources gets a lambda-expression that is invoked for the texture once its loaded (you can attach the texture to a sprite in there or something like that).

Post any progress in terms of multitreading you may make here, if you like. I would appreciate it. :)

Are you using the current release version of SFML?  I'm curious how you're getting multithreading to work if so.  There's a pretty gnarly bug that causes SFML to overflow the stack recursively creating openGL contexts if you try using a background thread to load textures (or do anything else OpenGL-related).

I ran into it a couple days ago and ended up having to use the dev branch of SFML from pending pull requests that removes the nested contexts entirely.  I'd rather use the official source though if you have a good solution to the problem!
Title: Re: Thor 2.0 released!
Post by: Hapax on August 19, 2016, 02:19:21 pm
Are you using the current release version of SFML? [...] There's a pretty gnarly bug that causes SFML to overflow the stack recursively creating openGL contexts if you try using a background thread to load textures (or do anything else OpenGL-related).

I ran into it a couple days ago and ended up having to use the dev branch of SFML from pending pull requests that removes the nested contexts entirely.
Is this bug official and there an issue (https://github.com/SFML/SFML/issues) for it? If not, have you reported it?

p.s. I'm not sure why you changed the thread's subject.
Title: Re: Thor 2.0 released!
Post by: Zentropy on August 19, 2016, 07:09:07 pm

Is this bug official and there an issue (https://github.com/SFML/SFML/issues) for it? If not, have you reported it?

p.s. I'm not sure why you changed the thread's subject.

Yep there's all of that as well as a fixed branch already up, the 2.4.0 version just released may have already fixed it too.

p.s. I'm not sure how that happened either.  It was late and I guess I accidentally pasted over that field without realizing it, sorry!
Title: Re: Thor 2.0 released!
Post by: Nexus on September 05, 2016, 09:37:03 pm
Post any progress in terms of multitreading you may make here, if you like. I would appreciate it. :)
I will. The reason why this hasn't happen is not that I'm doing it in a secret underground facility, but rather since it has (once more) been difficult to allocate enough time to the project... And sorry for the delay in my answer.


- Interpolation schemes - I think you have talked about including such in Thor. Is this something we could expect in the short-term, or should we be looking elsewhere?
If I remember correctly, plans were related to animations, not functionality of a generic tweener library. But nothing in that direction is planned for the near future.


- Parallel animations - It doesn't look like a single animator can play animations in parallel (only in internal edge cases). Is the only way to do this to compose them manually? Would using two animators be reliable enough?
Depending on what you want to do, you can just use an animation that plays two other animations (if progress aligns):
auto anim = [=] (sf::Sprite& animated, float progress)
{
    anim1(animated, progress);
    anim2(animated, progress);
};

Using two animators should work too, but it's a bit overkill if the progress is changed in the same way for both.

Parallel animations have been on my list for ages, it's a shame I haven't done them yet ::)


In the example in my post, I wished to ignore the keypress while the animation was playing; so this had to be tracked externally and updated with the callback mechanism. A lot of verbosity that would be eliminated by querying whether there's an active animationn. Meanwhile, internally this looks to be as simple as returning mPlayingAnimations.empty().

I realise the example is simple, however in a larger application one could keep distinct animators - according to the role - and thus still obtain useful information from this query.

Other animation APIs do offer such functionality. Could you clarify why you deem it best not to provide it? Do you have a better design in mind to achieve the intention in the example?
Yup, it's mainly the reason outlined in the docs (http://bromeon.ch/libraries/thor/documentation/v2.1/classthor_1_1_animator.html):
Quote
This class does not provide any methods to query the state and progress of the animations, by design. On one hand, there is not always an unambiguous animation playing – there may be none, or there may be multiple (when the delta time passed to update() has exceeded one). On the other hand, the intent of animators is to abstract such information from the user, and attempts to retrieve it nonetheless indicate a misunderstanding of Animator's capabilities (e.g. the need to know when an animation has finished, in order to start another). Sequential actions can be queued using play() and queue(); it's even possible to notify the user through callbacks.

The fact that your console example is simple can be important -- from my experience, things may look differently in bigger contexts. You want: "ignore keypress while animation is playing", but this is a short-cut that makes input directly dependent from graphics, a design that could be done differently. In a game, the actual condition might be: "when the guy presses the fire button (input), play the fire animation (graphics), launch a bullet (logic) and wait half a second before you accept further input (logic)". It would then rather be the logic that determines whether your input is processed, and graphics are only a result (you could say mapping/function) of the current game logic state. Wiring dependencies this way has many advantages: you can completely reconstruct a graphical scene from the current logic state, you can change graphics (fire animation duration) without affecting the cooldown time -- but still do it vice versa if you wanted, and so on.

By the way, thanks a lot for having a closer look at Thor and giving feedback based on usage in another project, this is very valuable. Thanks also for the blog post! :)
Title: Re: Thor 2.0 released!
Post by: eXpl0it3r on December 11, 2016, 10:11:58 pm
Edit: Never mind, I figured it out:
system.connect("ACTION", std::bind(&ClassName::function, class_pointer, std::placeholders::_1));

How do you pass a context to an action callback? All I can see is that one example where you have a fixed function signature for a free function, but how do you do it for class functions? Not even using the fixed function signature works for those.
Title: Re: Thor 2.0 released!
Post by: eXpl0it3r on December 13, 2016, 05:19:19 pm
After having tried to use Thor's actions for the LD Jam, I've ran into some issues that I'm not sure of whether I'm just missing the solution or whether it's a limit of the system.

For simple key presses one action is enough and you can build useful action maps, however when it comes to events that provide specific data, like for example the TextEntered event or MouseMove event, you need to have a context which then will provide you that information. From reading the tutorials and the documentation I saw only one way to get the context and that is by defining a function with the fixed signature void(thor::ActionContext<ActionId>). This is rather limiting as one sometimes would want to use different functions or no function at all. How is the isActive function useful for such events? "Okay text has been entered, but what exactly?"

Am I missing a way to get a specific context or is this really just a limitation of the system?
Title: Re: Thor 2.0 released!
Post by: Nexus on December 18, 2016, 05:37:50 pm
The Thor.Action system is built around callbacks, so you're right, thor::ActionContext is indeed the intended way to get access to the original event information. With lambda expressions and std::bind(), it should be possible to use it in a quite compact and concise way.

ActionMap::isActive() is for very simple use cases and does not provide the same level of features as callbacks. Using a procedural approach like this is already quite limited due to its nature. For example, it cannot track whether an event has occured one or multiple times, the boolean return type just allows to query whether it has been fired at least once. In contrast, a callback is invoked exactly once per event.

In order to support such scenarios procedurally, a different paradigma similar to SFML's while (window.pollEvent(event)) would be necessary, but this somehow misses the point of Thor's event-dispatcher abstraction. On the other hand, one might ask why isActive() is still there. And one could be right, it may not fit entirely, but it could help users understand the concept of combining actions and checking if they trigger.

A while ago I considered a design for a slightly higher-level abstraction that would be simpler to use. In particular, it would get rid of boilerplate code such as defining identifiers, and let you directly map from thor::Action to a callback. If you think about it, user-chosen identifiers don't make much sense if they're not queried in a isActive()-style way. In my opinion, such a action->listener map would rather be the way to go for Thor.