Custom element registration
This commit is contained in:
51
src/elements/health_bar_element.cpp
Normal file
51
src/elements/health_bar_element.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
#include "health_bar_element.hpp"
|
||||
#include <RmlUi/Core/Factory.h>
|
||||
#include <RmlUi/Core/ID.h>
|
||||
#include <RmlUi/Core/Math.h>
|
||||
#include <RmlUi/Core/Property.h>
|
||||
#include <RmlUi/Core/Types.h>
|
||||
#include <RmlUi/Core/Unit.h>
|
||||
|
||||
HealthBarElement::HealthBarElement(const Rml::String& tag) : Rml::Element(tag) {
|
||||
Rml::XMLAttributes attributes;
|
||||
|
||||
Rml::ElementPtr track = Rml::Factory::InstanceElement(this, "div", "div", attributes);
|
||||
track->SetClass("healthbar-track", true);
|
||||
|
||||
Rml::ElementPtr fillElement = Rml::Factory::InstanceElement(this, "div", "div", attributes);
|
||||
fillElement->SetClass("healthbar-fill", true);
|
||||
fill = fillElement.get();
|
||||
|
||||
track->AppendChild(std::move(fillElement));
|
||||
AppendChild(std::move(track));
|
||||
|
||||
UpdateFill();
|
||||
}
|
||||
|
||||
void HealthBarElement::OnAttributeChange(const Rml::ElementAttributes &changed_attributes) {
|
||||
Rml::Element::OnAttributeChange(changed_attributes);
|
||||
if (changed_attributes.find("current") != changed_attributes.end() ||
|
||||
changed_attributes.find("max") != changed_attributes.end()) {
|
||||
UpdateFill();
|
||||
}
|
||||
}
|
||||
|
||||
void HealthBarElement::UpdateFill() {
|
||||
int current = GetAttribute<int>("current", 0);
|
||||
int max = GetAttribute<int>("max", 100);
|
||||
if (max <= 0) max = 1;
|
||||
|
||||
float pct = Rml::Math::Clamp(static_cast<float>(current) / static_cast<float>(max), 0.0f, 1.0f) * 100.0f;
|
||||
|
||||
if (fill) {
|
||||
fill->SetProperty(Rml::PropertyId::Width, Rml::Property(pct, Rml::Unit::PERCENT));
|
||||
|
||||
if (current >= 90) {
|
||||
fill->SetProperty(Rml::PropertyId::BackgroundColor, Rml::Property("#33cc33", Rml::Unit::COLOUR));
|
||||
} else if (current >= 50) {
|
||||
fill->SetProperty(Rml::PropertyId::BackgroundColor, Rml::Property("#cccc33", Rml::Unit::COLOUR));
|
||||
} else if (current >= 0) {
|
||||
fill->SetProperty(Rml::PropertyId::BackgroundColor, Rml::Property("#cc3333", Rml::Unit::COLOUR));
|
||||
}
|
||||
}
|
||||
}
|
||||
14
src/elements/health_bar_element.hpp
Normal file
14
src/elements/health_bar_element.hpp
Normal file
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
#include <RmlUi/Core/Element.h>
|
||||
#include <RmlUi/Core/Types.h>
|
||||
|
||||
class HealthBarElement : public Rml::Element {
|
||||
public:
|
||||
explicit HealthBarElement(const Rml::String& tag);
|
||||
|
||||
void OnAttributeChange(const Rml::ElementAttributes &changed_attributes) override;
|
||||
|
||||
private:
|
||||
void UpdateFill();
|
||||
Rml::Element* fill = nullptr;
|
||||
};
|
||||
Reference in New Issue
Block a user