File: color.cpp

package info (click to toggle)
openmw 0.50.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 37,076 kB
  • sloc: cpp: 380,958; xml: 2,192; sh: 1,449; python: 911; makefile: 26; javascript: 5
file content (73 lines) | stat: -rw-r--r-- 2,000 bytes parent folder | download
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
#include "color.hpp"

#include <algorithm>
#include <array>
#include <charconv>
#include <sstream>
#include <system_error>

#include <components/sceneutil/util.hpp>

namespace Misc
{
    Color::Color(float r, float g, float b, float a)
        : mValue(std::clamp(r, 0.f, 1.f), std::clamp(g, 0.f, 1.f), std::clamp(b, 0.f, 1.f), std::clamp(a, 0.f, 1.f))
    {
    }

    std::string Color::toString() const
    {
        std::ostringstream ss;
        ss << "(" << r() << ", " << g() << ", " << b() << ", " << a() << ')';
        return ss.str();
    }

    Color Color::fromHex(std::string_view hex)
    {
        if (hex.size() != 6)
            throw std::logic_error(std::string("Invalid hex color: ") += hex);
        Color col;
        col.mValue.a() = 1;
        for (size_t i = 0; i < 3; i++)
        {
            auto sub = hex.substr(i * 2, 2);
            int v = 0;
            auto [_, ec] = std::from_chars(sub.data(), sub.data() + sub.size(), v, 16);
            if (ec != std::errc())
                throw std::logic_error(std::string("Invalid hex color: ") += hex);
            col.mValue[i] = v / 255.0f;
        }
        return col;
    }

    Color Color::fromRGB(unsigned int value)
    {
        return Color(SceneUtil::colourFromRGB(value));
    }

    Color Color::fromVec(osg::Vec4f value)
    {
        return Color(std::move(value));
    }

    std::string Color::toHex() const
    {
        std::string result(6, '0');
        for (size_t i = 0; i < 3; i++)
        {
            int b = static_cast<int>(mValue[i] * 255.0f);
            char* start = result.data() + i * 2;
            if (b < 16)
                start++;
            auto [_, ec] = std::to_chars(start, result.data() + (i + 1) * 2, b, 16);
            if (ec != std::errc())
                throw std::logic_error("Error when converting number to base 16");
        }
        return result;
    }

    bool operator==(const Color& l, const Color& r)
    {
        return l.mValue == r.mValue;
    }
}