1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#pragma once
#include <functional>
#include "ientity.h"
#include "irender.h"
namespace entity
{
/**
* greebo: this is a class encapsulating the "_color" spawnarg
* of entity, observing it and maintaining the corresponding shader.
*/
class ColourKey :
public KeyObserver
{
private:
ShaderPtr _colourShader;
Vector3 _colour;
RenderSystemWeakPtr _renderSystem;
std::function<void(const std::string&)> _onColourChanged;
public:
// The given callback will be invoked after the _color spawnarg has been changed
ColourKey(const std::function<void(const std::string&)>& onColourChanged) :
_colour(1,1,1),
_onColourChanged(onColourChanged)
{
captureShader();
}
const Vector3& getColour() const
{
return _colour;
}
// Called when "_color" keyvalue changes
void onKeyValueChanged(const std::string& value) override
{
// Initialise the colour with white, in case the string parse fails
_colour[0] = _colour[1] = _colour[2] = 1;
// Use a stringstream to parse the string
std::stringstream strm(value);
strm << std::skipws;
strm >> _colour.x();
strm >> _colour.y();
strm >> _colour.z();
captureShader();
if (_onColourChanged)
{
_onColourChanged(value);
}
}
void setRenderSystem(const RenderSystemPtr& renderSystem)
{
_renderSystem = renderSystem;
captureShader();
}
/// Return a (possibly empty) reference to the Shader
const ShaderPtr& getColourShader() const
{
return _colourShader;
}
private:
void captureShader()
{
auto renderSystem = _renderSystem.lock();
if (renderSystem)
{
_colourShader = renderSystem->capture(ColourShaderType::CameraAndOrthoview, _colour);
}
else
{
_colourShader.reset();
}
}
};
} // namespace entity
|