Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[core] operator== hook #1455

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open

Conversation

jpeletier
Copy link
Contributor

Note, requires #1454 to be merged first.

Building on the previous PR, this one adds a hook for operator==. It will detect this operator in a component definition and bind a hook to it that can be used to test components for equality.

If this operator is not defined but the compare operator is, Flecs will automatically derive this operator.

    class Vec2D {
    public:
        float x, y;
    
        Vec2D(float x = 0.0f, float y = 0.0f) : x(x), y(y) {}
    
        // Function to calculate the modulus (magnitude) of the vector
        float modulus() const {
            return std::sqrt(x * x + y * y);
        }
    
        // Overload operator< to compare vectors based on their modulus
        bool operator<(const Vec2D& other) const {
            return this->modulus() < other.modulus();
        }
    
        // Overload operator== to compare vectors with a precision tolerance of 0.001
        bool operator==(const Vec2D& other) const {
            return std::fabs(this->x - other.x) < 0.001 && std::fabs(this->y - other.y) < 0.001;
        }
    };

    flecs::world ecs;

    auto vtype =
        ecs.component<Vec2D>();  // will automatically register the above hooks.

    Vec2D a(1, 2);
    Vec2D b(2, 3);
    Vec2D c(1.00001, 1.9999999);

    const ecs_type_info_t *ti = ecs_get_type_info(ecs, vtype);

    assert(ti->hooks.equals(&a, &b, ti) == false); // ok!
    assert(ti->hooks.equals(&a, &c, ti) == true);  // ok!
    assert(ti->hooks.cmp(&b, &a, ti) > 0);         // ok!



@jpeletier jpeletier force-pushed the equals-hook branch 5 times, most recently from 38dce50 to fa1a619 Compare December 5, 2024 16:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant