// Copyright (c) 2023 Dominic Masters // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include "Color.hpp" #include "util/parser/TypeParsers.hpp" using namespace Dawn; struct Color Color::fromString(std::string str) { // Convert to lowercase auto lower = stringToLowercase(str); if(stringIncludes(lower, "cornflower")) { return COLOR_CORNFLOWER_BLUE; } else if(stringIncludes(lower, "magenta")) { return COLOR_MAGENTA; } else if(stringIncludes(lower, "white")) { return COLOR_WHITE; } else if(stringIncludes(lower, "black")) { return COLOR_BLACK; } else if(stringIncludes(lower, "red")) { return COLOR_RED; } else if(stringIncludes(lower, "green")) { return COLOR_GREEN; } else if(stringIncludes(lower, "blue")) { return COLOR_BLUE; } else if(stringIncludes(lower, "transparent")) { return COLOR_TRANSPARENT; } // Hex code? if(lower[0] == '#') { // Remove the hash lower = lower.substr(1); // Convert to RGB if(lower.length() == 3) { // Convert to 6 digit hex lower = lower[0] + lower[0] + lower[1] + lower[1] + lower[2] + lower[2]; } // Convert to RGB return { (float_t)std::stoi(lower.substr(0, 2), nullptr, 16) / 255.0f, (float_t)std::stoi(lower.substr(2, 2), nullptr, 16) / 255.0f, (float_t)std::stoi(lower.substr(4, 2), nullptr, 16) / 255.0f, 1.0f }; } // Split by comma auto splitByComma = stringSplit(str, ","); if(splitByComma.size() == 3) { // RGB return { (float_t)std::stof(splitByComma[0]), (float_t)std::stof(splitByComma[1]), (float_t)std::stof(splitByComma[2]), 1.0f }; } else if(splitByComma.size() == 4) { // RGBA return { (float_t)std::stof(splitByComma[0]), (float_t)std::stof(splitByComma[1]), (float_t)std::stof(splitByComma[2]), (float_t)std::stof(splitByComma[3]) }; } // TODO: Parse other kinds of colors assertUnreachable("Failed to find a color match for " + str); return {}; }