Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

Load .cube 3D LUT support (#7088)

Rodney1720fbc865fc
diff --git a/toonz/sources/include/toonzqt/lutcalibrator.h b/toonz/sources/include/toonzqt/lutcalibrator.h
index 8ed759fe7..a8e68f004 100644
--- a/toonz/sources/include/toonzqt/lutcalibrator.h
+++ b/toonz/sources/include/toonzqt/lutcalibrator.h
@@ -40,6 +40,8 @@ class DVAPI LutCalibrator : public QOpenGLFunctions {
int texUniform = -1;
int lutUniform = -1;
int lutSizeUniform = -1;
+ int domainMinUniform = -1;
+ int domainMaxUniform = -1;
int vertexAttrib = -1;
int texCoordAttrib = -1;
} m_shader;
@@ -78,8 +80,10 @@ class DVAPI LutManager // singleton
LutManager();
struct Lut {
- int meshSize;
- float* data = nullptr;
+ int meshSize = 0;
+ float* data = nullptr;
+ float domainMin[3] = {0.0f, 0.0f, 0.0f};
+ float domainMax[3] = {1.0f, 1.0f, 1.0f};
} m_lut;
public:
@@ -90,6 +94,8 @@ public:
bool isValid() { return m_isValid; }
int meshSize() const { return m_lut.meshSize; }
const float* data() const { return m_lut.data; }
+ const float* domainMin() const { return m_lut.domainMin; }
+ const float* domainMax() const { return m_lut.domainMax; }
bool loadLutFile(const QString& fp);
@@ -105,4 +111,4 @@ public:
void update();
};
-#endif
\ No newline at end of file
+#endif
diff --git a/toonz/sources/toonz/preferencespopup.cpp b/toonz/sources/toonz/preferencespopup.cpp
index 21376290a..c70775f8a 100644
--- a/toonz/sources/toonz/preferencespopup.cpp
+++ b/toonz/sources/toonz/preferencespopup.cpp
@@ -1107,12 +1107,13 @@ QWidget* PreferencesPopup::createUI(PreferencesItemId id,
case QMetaType::QVariantMap: // used in colorCalibrationLutPaths
{
DVGui::FileField* field = new DVGui::FileField(
- this, QString("- Please specify 3DLUT file (.3dl) -"), false, true);
+ this, QString("- Please specify 3D LUT file (.3dl or .cube) -"), false,
+ true);
QString lutPath = m_pref->getColorCalibrationLutPath(
LutManager::instance()->getMonitorName());
if (!lutPath.isEmpty()) field->setPath(lutPath);
field->setFileMode(QFileDialog::ExistingFile);
- QStringList lutFileTypes = {"3dl"};
+ QStringList lutFileTypes = {"3dl", "cube"};
field->setFilters(lutFileTypes);
connect(field, &FileField::pathChanged, this,
&PreferencesPopup::onLutPathChanged);
diff --git a/toonz/sources/toonzqt/lutcalibrator.cpp b/toonz/sources/toonzqt/lutcalibrator.cpp
index f72534279..7121d2fc0 100644
--- a/toonz/sources/toonzqt/lutcalibrator.cpp
+++ b/toonz/sources/toonzqt/lutcalibrator.cpp
@@ -13,18 +13,283 @@
#include <QOpenGLContext>
#include <QOffscreenSurface>
#include <QFile>
+#include <QFileInfo>
#include <QColor>
+#include <QStringList>
+#include <QTextStream>
+
+#include <algorithm>
+#include <cmath>
+#include <vector>
namespace {
inline bool execWarning(const QString& s) {
DVGui::MsgBox(DVGui::WARNING, s);
return false;
}
+
+constexpr int kMax3DLutSize = 129;
+
+struct ParsedLut {
+ int meshSize = 0;
+ std::vector<float> data;
+ float domainMin[3] = {0.0f, 0.0f, 0.0f};
+ float domainMax[3] = {1.0f, 1.0f, 1.0f};
+};
+
+bool readDataLine(QTextStream& stream, QString& line, int& lineNumber) {
+ while (!stream.atEnd()) {
+ ++lineNumber;
+ line = stream.readLine().trimmed();
+ if (!line.isEmpty() && !line.startsWith('#')) return true;
+ }
+ return false;
+}
+
+QStringList splitFields(const QString& line) {
+ return line.simplified().split(' ', Qt::SkipEmptyParts);
+}
+
+bool parseFiniteFloat(const QString& text, float& value) {
+ bool ok = false;
+ value = text.toFloat(&ok);
+ return ok && std::isfinite(value);
+}
+
+float clamp01(float value) {
+ return value < 0.0f ? 0.0f : value > 1.0f ? 1.0f : value;
+}
+
+bool parseFloatTriple(const QStringList& fields, float values[3]) {
+ if (fields.size() != 3) return false;
+ for (int channel = 0; channel < 3; ++channel)
+ if (!parseFiniteFloat(fields.at(channel), values[channel])) return false;
+ return true;
+}
+
+QString lineError(int lineNumber, const QString& message) {
+ return QObject::tr("Line %1: %2").arg(lineNumber).arg(message);
+}
+
+bool parse3dl(QTextStream& stream, ParsedLut& lut, QString& error) {
+ QString line;
+ int lineNumber = 0;
+
+ if (!readDataLine(stream, line, lineNumber) || line != "3DMESH") {
+ error = lineError(lineNumber, QObject::tr("Expected the 3DMESH keyword."));
+ return false;
+ }
+
+ if (!readDataLine(stream, line, lineNumber)) {
+ error = QObject::tr("The Mesh header is missing.");
+ return false;
+ }
+
+ QStringList fields = splitFields(line);
+ bool inputOk = false, outputOk = false;
+ int inputBitDepth = fields.size() == 3 ? fields.at(1).toInt(&inputOk) : 0;
+ int outputBitDepth = fields.size() == 3 ? fields.at(2).toInt(&outputOk) : 0;
+ if (fields.size() != 3 || fields.at(0) != "Mesh" || !inputOk || !outputOk ||
+ inputBitDepth < 0 || inputBitDepth > 7 || outputBitDepth < 1 ||
+ outputBitDepth > 30) {
+ error = lineError(
+ lineNumber,
+ QObject::tr("Expected Mesh [input bit depth] [output bit depth]."));
+ return false;
+ }
+
+ lut.meshSize = (1 << inputBitDepth) + 1;
+ if (lut.meshSize > kMax3DLutSize) {
+ error = QObject::tr("The LUT grid may not exceed %1 points per axis.")
+ .arg(kMax3DLutSize);
+ return false;
+ }
+
+ if (!readDataLine(stream, line, lineNumber)) {
+ error = QObject::tr("The input grid line is missing.");
+ return false;
+ }
+ fields = splitFields(line);
+ if (fields.size() != lut.meshSize) {
+ error = lineError(lineNumber,
+ QObject::tr("The input grid has the wrong size."));
+ return false;
+ }
+
+ const size_t entryCount =
+ static_cast<size_t>(lut.meshSize) * lut.meshSize * lut.meshSize;
+ lut.data.resize(entryCount * 3);
+ const float maxValue = std::ldexp(1.0f, outputBitDepth) - 1.0f;
+
+ size_t entry = 0;
+ for (int r = 0; r < lut.meshSize; ++r) {
+ for (int g = 0; g < lut.meshSize; ++g) {
+ for (int b = 0; b < lut.meshSize; ++b, ++entry) {
+ if (!readDataLine(stream, line, lineNumber)) {
+ error = QObject::tr("The LUT contains %1 entries; expected %2.")
+ .arg(static_cast<qulonglong>(entry))
+ .arg(static_cast<qulonglong>(entryCount));
+ return false;
+ }
+ fields = splitFields(line);
+ if (fields.size() != 3) {
+ error = lineError(
+ lineNumber, QObject::tr("Expected three integer color values."));
+ return false;
+ }
+ const size_t offset =
+ (static_cast<size_t>(b) * lut.meshSize * lut.meshSize +
+ static_cast<size_t>(g) * lut.meshSize + r) *
+ 3;
+ for (int channel = 0; channel < 3; ++channel) {
+ bool ok = false;
+ const int value = fields.at(channel).toInt(&ok);
+ if (!ok) {
+ error =
+ lineError(lineNumber,
+ QObject::tr("Expected three integer color values."));
+ return false;
+ }
+ lut.data[offset + channel] = static_cast<float>(value) / maxValue;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool parseCube(QTextStream& stream, ParsedLut& lut, QString& error) {
+ QString line;
+ int lineNumber = 0;
+ bool hasSize = false;
+ bool dataHasBegun = false;
+ bool hasDomainTags = false;
+ bool hasRangeTag = false;
+
+ while (readDataLine(stream, line, lineNumber)) {
+ const QStringList fields = splitFields(line);
+ float firstValue = 0.0f;
+ if (parseFiniteFloat(fields.at(0), firstValue)) {
+ if (!hasSize) {
+ error = lineError(lineNumber,
+ QObject::tr("LUT_3D_SIZE must precede LUT data."));
+ return false;
+ }
+ dataHasBegun = true;
+ float values[3];
+ if (!parseFloatTriple(fields, values)) {
+ error = lineError(lineNumber,
+ QObject::tr("Expected three floating-point values."));
+ return false;
+ }
+ lut.data.insert(lut.data.end(), values, values + 3);
+ const size_t expectedValues =
+ static_cast<size_t>(lut.meshSize) * lut.meshSize * lut.meshSize * 3;
+ if (lut.data.size() > expectedValues) {
+ error = QObject::tr("The .cube file contains too many LUT entries.");
+ return false;
+ }
+ continue;
+ }
+
+ if (dataHasBegun) {
+ error = lineError(lineNumber,
+ QObject::tr("Only color triples may follow LUT data."));
+ return false;
+ }
+
+ const QString keyword = fields.at(0).toUpper();
+ if (keyword == "TITLE") {
+ continue;
+ } else if (keyword == "LUT_1D_SIZE" || keyword == "LUT_1D_INPUT_RANGE") {
+ error =
+ lineError(lineNumber,
+ QObject::tr("1D and shaper .cube LUTs are not supported."));
+ return false;
+ } else if (keyword == "LUT_2D_SIZE") {
+ error = lineError(lineNumber,
+ QObject::tr("2D .cube LUTs are not supported."));
+ return false;
+ } else if (keyword == "LUT_3D_SIZE") {
+ bool ok = false;
+ const int size = fields.size() == 2 ? fields.at(1).toInt(&ok) : 0;
+ if (!ok || size < 2 || size > kMax3DLutSize || hasSize) {
+ error = lineError(
+ lineNumber,
+ QObject::tr("LUT_3D_SIZE must be a single value from 2 to %1.")
+ .arg(kMax3DLutSize));
+ return false;
+ }
+ lut.meshSize = size;
+ lut.data.reserve(static_cast<size_t>(size) * size * size * 3);
+ hasSize = true;
+ } else if (keyword == "DOMAIN_MIN" || keyword == "DOMAIN_MAX") {
+ float values[3];
+ if (hasRangeTag || fields.size() != 4 ||
+ !parseFloatTriple(fields.mid(1), values)) {
+ error = lineError(
+ lineNumber,
+ QObject::tr("%1 must contain three floating-point values and may "
+ "not be combined with LUT_3D_INPUT_RANGE.")
+ .arg(keyword));
+ return false;
+ }
+ float* domain = keyword == "DOMAIN_MIN" ? lut.domainMin : lut.domainMax;
+ std::copy(values, values + 3, domain);
+ hasDomainTags = true;
+ } else if (keyword == "LUT_3D_INPUT_RANGE") {
+ float values[2];
+ if (hasDomainTags || fields.size() != 3 ||
+ !parseFiniteFloat(fields.at(1), values[0]) ||
+ !parseFiniteFloat(fields.at(2), values[1])) {
+ error = lineError(
+ lineNumber,
+ QObject::tr("LUT_3D_INPUT_RANGE must contain two floating-point "
+ "values and may not be combined with DOMAIN_MIN/MAX."));
+ return false;
+ }
+ for (int channel = 0; channel < 3; ++channel) {
+ lut.domainMin[channel] = values[0];
+ lut.domainMax[channel] = values[1];
+ }
+ hasRangeTag = true;
+ } else {
+ error = lineError(lineNumber,
+ QObject::tr("Unsupported .cube header: %1").arg(line));
+ return false;
+ }
+ }
+
+ if (!hasSize) {
+ error = QObject::tr("The .cube file does not contain LUT_3D_SIZE.");
+ return false;
+ }
+
+ const size_t expectedValues =
+ static_cast<size_t>(lut.meshSize) * lut.meshSize * lut.meshSize * 3;
+ if (lut.data.size() != expectedValues) {
+ error = QObject::tr("The .cube file contains %1 entries; expected %2.")
+ .arg(static_cast<qulonglong>(lut.data.size() / 3))
+ .arg(static_cast<qulonglong>(expectedValues / 3));
+ return false;
+ }
+
+ for (int channel = 0; channel < 3; ++channel) {
+ if (lut.domainMin[channel] >= lut.domainMax[channel]) {
+ error = QObject::tr(
+ "Each .cube input-domain minimum must be less than "
+ "its maximum.");
+ return false;
+ }
+ }
+
+ return true;
+}
}; // namespace
#ifdef WIN32
-#include <QStringList>
#include <QSettings>
#include <QByteArray>
@@ -262,8 +527,11 @@ bool LutCalibrator::initializeLutTextureShader() {
"uniform sampler2D tex; \n"
"uniform sampler3D lut; \n"
"uniform vec3 lutSize; \n"
+ "uniform vec3 domainMin; \n"
+ "uniform vec3 domainMax; \n"
"void main() { \n"
- " vec3 rawColor = texture(tex,UV).rgb; \n"
+ " vec3 rawColor = clamp((texture(tex,UV).rgb - domainMin) / "
+ "(domainMax - domainMin), 0.0, 1.0); \n"
" vec3 scale = (lutSize - 1.0) / lutSize; \n"
" vec3 offset = 1.0 / (2.0 * lutSize); \n"
" color = vec4(texture(lut, scale * rawColor + offset).rgb, 1.0); \n"
@@ -308,6 +576,14 @@ bool LutCalibrator::initializeLutTextureShader() {
if (m_shader.lutSizeUniform == -1)
return execWarning(QObject::tr("Failed to get uniform location of %1", "gl")
.arg("lutSize"));
+ m_shader.domainMinUniform = m_shader.program->uniformLocation("domainMin");
+ if (m_shader.domainMinUniform == -1)
+ return execWarning(QObject::tr("Failed to get uniform location of %1", "gl")
+ .arg("domainMin"));
+ m_shader.domainMaxUniform = m_shader.program->uniformLocation("domainMax");
+ if (m_shader.domainMaxUniform == -1)
+ return execWarning(QObject::tr("Failed to get uniform location of %1", "gl")
+ .arg("domainMax"));
return true;
}
@@ -350,6 +626,12 @@ void LutCalibrator::onEndDraw(QOpenGLFramebufferObject* fbo) {
2); // use texture unit 2
GLfloat size = (GLfloat)LutManager::instance()->meshSize();
m_shader.program->setUniformValue(m_shader.lutSizeUniform, size, size, size);
+ const float* domainMin = LutManager::instance()->domainMin();
+ const float* domainMax = LutManager::instance()->domainMax();
+ m_shader.program->setUniformValue(m_shader.domainMinUniform, domainMin[0],
+ domainMin[1], domainMin[2]);
+ m_shader.program->setUniformValue(m_shader.domainMaxUniform, domainMax[0],
+ domainMax[1], domainMax[2]);
m_shader.program->enableAttributeArray(m_shader.vertexAttrib);
m_shader.program->enableAttributeArray(m_shader.texCoordAttrib);
@@ -400,7 +682,13 @@ void LutCalibrator::assignLutTexture() {
void LutCalibrator::update(bool textureChanged) {
m_isValid = LutManager::instance()->isValid();
- if (textureChanged) assignLutTexture();
+
+ // PreferencesPopup notifies each viewer immediately after
+ // LutManager::update(). The viewer then rebuilds the calibrator while its
+ // OpenGL context is current. Do not upload the texture here: this method runs
+ // from the preferences UI, where none of the viewers' OpenGL contexts is
+ // guaranteed to be current.
+ (void)textureChanged;
}
//=============================================================================
@@ -460,92 +748,34 @@ QString& LutManager::getMonitorName() const {
//-----------------------------------------------------------------------------
bool LutManager::loadLutFile(const QString& fp) {
- struct locals {
- // skip empty or comment lines
- static inline QString readDataLine(QTextStream& stream) {
- while (1) {
- if (stream.atEnd()) return QString();
- QString ret = stream.readLine();
- if (!ret.isEmpty() && ret[0] != QChar('#')) return ret;
- }
- }
-
- static inline int lutCoords(int r, int g, int b, int meshSize) {
- return b * meshSize * meshSize * 3 + g * meshSize * 3 + r * 3;
- }
- };
-
QFile file(fp);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
- return execWarning(QObject::tr("Failed to Open 3DLUT File."));
+ return execWarning(QObject::tr("Failed to Open 3D LUT File."));
QTextStream stream(&file);
- QString line;
-
- //---- read the 3DLUT files
-
- // The first line should start from "3DMESH" keyword (case sensitive)
- line = locals::readDataLine(stream);
- if (line != "3DMESH") {
- file.close();
- return execWarning(
- QObject::tr("Failed to Load 3DLUT File.\nIt should start with "
- "\"3DMESH\" keyword."));
- }
+ ParsedLut parsed;
+ QString error;
+ const QString suffix = QFileInfo(fp).suffix();
+ bool loaded = false;
+ if (suffix.compare("cube", Qt::CaseInsensitive) == 0)
+ loaded = parseCube(stream, parsed, error);
+ else if (suffix.compare("3dl", Qt::CaseInsensitive) == 0)
+ loaded = parse3dl(stream, parsed, error);
+ else
+ error = QObject::tr("Supported file types are .3dl and .cube.");
- // The second line is "Mesh [Input bit depth] [Output bit depth]"
- // "Mesh" is a keyword (case sensitive) 
- line = locals::readDataLine(stream);
- QStringList list = line.split(" ");
- if (list.size() != 3 || list.at(0) != "Mesh") {
- file.close();
+ file.close();
+ if (!loaded)
return execWarning(
- QObject::tr("Failed to Load 3DLUT File.\nThe second line should be "
- "\"Mesh [Input bit depth] [Output bit depth]\""));
- }
-
- int inputBitDepth = list.at(1).toInt();
- int outputBitDepth = list.at(2).toInt();
-
- m_lut.meshSize = (int)pow(2.0, inputBitDepth) + 1;
-
- float maxValue = pow(2.0, outputBitDepth) - 1.0f;
-
- // The third line is corrections of values at each LUT grid
- line = locals::readDataLine(stream);
- list = line.split(" ", Qt::SkipEmptyParts);
- if (list.size() != m_lut.meshSize) {
- file.close();
- return execWarning(QObject::tr("Failed to Load 3DLUT File."));
- }
+ QObject::tr("Failed to Load 3D LUT File.\n%1").arg(error));
+ float* data = new float[parsed.data.size()];
+ std::copy(parsed.data.begin(), parsed.data.end(), data);
if (m_lut.data) delete[] m_lut.data;
- m_lut.data = new float[m_lut.meshSize * m_lut.meshSize * m_lut.meshSize * 3];
-
- for (int k = 0; k < m_lut.meshSize; ++k) // r
- {
- for (int j = 0; j < m_lut.meshSize; ++j) // g
- {
- for (int i = 0; i < m_lut.meshSize; ++i) // b
- {
- line = locals::readDataLine(stream);
- list = line.split(" ", Qt::SkipEmptyParts);
- if (list.size() != 3) {
- file.close();
- delete[] m_lut.data;
- return execWarning(QObject::tr("Failed to Load 3DLUT File."));
- }
- float* lut = m_lut.data + locals::lutCoords(k, j, i, m_lut.meshSize);
- *lut = (float)(list.at(0).toInt()) / maxValue;
- lut++;
- *lut = (float)(list.at(1).toInt()) / maxValue;
- lut++;
- *lut = (float)(list.at(2).toInt()) / maxValue;
- }
- }
- }
-
- file.close();
+ m_lut.data = data;
+ m_lut.meshSize = parsed.meshSize;
+ std::copy(parsed.domainMin, parsed.domainMin + 3, m_lut.domainMin);
+ std::copy(parsed.domainMax, parsed.domainMax + 3, m_lut.domainMax);
return true;
}
//-----------------------------------------------------------------------------
@@ -566,9 +796,11 @@ void LutManager::convert(float& r, float& g, float& b) {
float ratio[3]; // RGB軸
int index[3][2]; // rgb インデックス
float rawVal[3] = {r, g, b};
- // clamp values (for HDR image)
- for (int c = 0; c < 3; c++)
- rawVal[c] = (rawVal[c] < 0.f) ? 0.f : (rawVal[c] > 1.f) ? 1.f : rawVal[c];
+ for (int c = 0; c < 3; c++) {
+ rawVal[c] = (rawVal[c] - m_lut.domainMin[c]) /
+ (m_lut.domainMax[c] - m_lut.domainMin[c]);
+ rawVal[c] = clamp01(rawVal[c]);
+ }
float vertex_color[2][2][2][3]; // 補間用の1ボクセルの頂点色
@@ -605,9 +837,11 @@ void LutManager::convert(float& r, float& g, float& b) {
ratio[0]);
}
- r = result[0];
- g = result[1];
- b = result[2];
+ // CPU-converted UI colors use normalized integer-backed color types. Match
+ // the framebuffer's clipping when a floating-point .cube stores HDR values.
+ r = clamp01(result[0]);
+ g = clamp01(result[1]);
+ b = clamp01(result[2]);
}
//-----------------------------------------------------------------------------