| 1 |
/* |
| 2 |
* Copyright 2022 Google LLC |
| 3 |
* |
| 4 |
* Use of this source code is governed by a BSD-style license that can be |
| 5 |
* found in the LICENSE file. |
| 6 |
*/ |
| 7 |
|
| 8 |
#include "src/shaders/gradients/SkGradientBaseShader.h" |
| 9 |
|
| 10 |
#include "include/core/SkAlphaType.h" |
| 11 |
#include "include/core/SkColor.h" |
| 12 |
#include "include/core/SkColorSpace.h" |
| 13 |
#include "include/core/SkColorType.h" |
| 14 |
#include "include/core/SkData.h" |
| 15 |
#include "include/core/SkImageInfo.h" |
| 16 |
#include "include/core/SkShader.h" |
| 17 |
#include "include/core/SkTileMode.h" |
| 18 |
#include "include/private/base/SkFloatingPoint.h" |
| 19 |
#include "include/private/base/SkMalloc.h" |
| 20 |
#include "include/private/base/SkTArray.h" |
| 21 |
#include "include/private/base/SkTPin.h" |
| 22 |
#include "include/private/base/SkTo.h" |
| 23 |
#include "modules/skcms/skcms.h" |
| 24 |
#include "src/base/SkArenaAlloc.h" |
| 25 |
#include "src/base/SkFloatBits.h" |
| 26 |
#include "src/base/SkVx.h" |
| 27 |
#include "src/core/SkColorData.h" |
| 28 |
#include "src/core/SkColorSpacePriv.h" |
| 29 |
#include "src/core/SkColorSpaceXformSteps.h" |
| 30 |
#include "src/core/SkConvertPixels.h" |
| 31 |
#include "src/core/SkEffectPriv.h" |
| 32 |
#include "src/core/SkPicturePriv.h" |
| 33 |
#include "src/core/SkRasterPipeline.h" |
| 34 |
#include "src/core/SkRasterPipelineOpContexts.h" |
| 35 |
#include "src/core/SkRasterPipelineOpList.h" |
| 36 |
#include "src/core/SkReadBuffer.h" |
| 37 |
#include "src/core/SkWriteBuffer.h" |
| 38 |
|
| 39 |
#include <algorithm> |
| 40 |
#include <cmath> |
| 41 |
#include <optional> |
| 42 |
#include <utility> |
| 43 |
|
| 44 |
using namespace skia_private; |
| 45 |
|
| 46 |
enum GradientSerializationFlags { |
| 47 |
// Bits 29:31 used for various boolean flags |
| 48 |
kHasPosition_GSF = 0x80000000, |
| 49 |
kHasLegacyLocalMatrix_GSF = 0x40000000, |
| 50 |
kHasColorSpace_GSF = 0x20000000, |
| 51 |
|
| 52 |
// Bits 12:28 unused |
| 53 |
|
| 54 |
// Bits 8:11 for fTileMode |
| 55 |
kTileModeShift_GSF = 8, |
| 56 |
kTileModeMask_GSF = 0xF, |
| 57 |
|
| 58 |
// Bits 4:7 for fInterpolation.fColorSpace |
| 59 |
kInterpolationColorSpaceShift_GSF = 4, |
| 60 |
kInterpolationColorSpaceMask_GSF = 0xF, |
| 61 |
|
| 62 |
// Bits 1:3 for fInterpolation.fHueMethod |
| 63 |
kInterpolationHueMethodShift_GSF = 1, |
| 64 |
kInterpolationHueMethodMask_GSF = 0x7, |
| 65 |
|
| 66 |
// Bit 0 for fInterpolation.fInPremul |
| 67 |
kInterpolationInPremul_GSF = 0x1, |
| 68 |
}; |
| 69 |
|
| 70 |
void SkGradientBaseShader::flatten(SkWriteBuffer& buffer) const { |
| 71 |
uint32_t flags = 0; |
| 72 |
if (fPositions) { |
| 73 |
flags |= kHasPosition_GSF; |
| 74 |
} |
| 75 |
sk_sp<SkData> colorSpaceData = fColorSpace ? fColorSpace->serialize() : nullptr; |
| 76 |
if (colorSpaceData) { |
| 77 |
flags |= kHasColorSpace_GSF; |
| 78 |
} |
| 79 |
if (fInterpolation.fInPremul == Interpolation::InPremul::kYes) { |
| 80 |
flags |= kInterpolationInPremul_GSF; |
| 81 |
} |
| 82 |
SkASSERT(static_cast<uint32_t>(fTileMode) <= kTileModeMask_GSF); |
| 83 |
flags |= ((uint32_t)fTileMode << kTileModeShift_GSF); |
| 84 |
SkASSERT(static_cast<uint32_t>(fInterpolation.fColorSpace) <= kInterpolationColorSpaceMask_GSF); |
| 85 |
flags |= ((uint32_t)fInterpolation.fColorSpace << kInterpolationColorSpaceShift_GSF); |
| 86 |
SkASSERT(static_cast<uint32_t>(fInterpolation.fHueMethod) <= kInterpolationHueMethodMask_GSF); |
| 87 |
flags |= ((uint32_t)fInterpolation.fHueMethod << kInterpolationHueMethodShift_GSF); |
| 88 |
|
| 89 |
buffer.writeUInt(flags); |
| 90 |
|
| 91 |
// If we injected implicit first/last stops at construction time, omit those when serializing: |
| 92 |
size_t colorCount = fColorCount; |
| 93 |
const SkColor4f* colors = fColors; |
| 94 |
const SkScalar* positions = fPositions; |
| 95 |
if (fFirstStopIsImplicit) { |
| 96 |
colorCount--; |
| 97 |
colors++; |
| 98 |
if (positions) { |
| 99 |
positions++; |
| 100 |
} |
| 101 |
} |
| 102 |
if (fLastStopIsImplicit) { |
| 103 |
colorCount--; |
| 104 |
} |
| 105 |
|
| 106 |
buffer.writeColor4fArray({colors, colorCount}); |
| 107 |
if (colorSpaceData) { |
| 108 |
buffer.writeDataAsByteArray(colorSpaceData.get()); |
| 109 |
} |
| 110 |
if (positions) { |
| 111 |
buffer.writeScalarArray({positions, colorCount}); |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
template <int N, typename T, bool MEM_MOVE> |
| 116 |
static bool validate_array(SkReadBuffer& buffer, size_t count, STArray<N, T, MEM_MOVE>* array) { |
| 117 |
if (!buffer.validateCanReadN<T>(count)) { |
| 118 |
return false; |
| 119 |
} |
| 120 |
|
| 121 |
array->resize_back(count); |
| 122 |
return true; |
| 123 |
} |
| 124 |
|
| 125 |
std::optional<SkGradient> SkGradientScope::unflatten(SkReadBuffer& buffer, |
| 126 |
SkMatrix* legacyLocalMatrix) { |
| 127 |
// New gradient format. Includes floating point color, color space, densely packed flags |
| 128 |
uint32_t flags = buffer.readUInt(); |
| 129 |
|
| 130 |
auto tm = (SkTileMode)((flags >> kTileModeShift_GSF) & kTileModeMask_GSF); |
| 131 |
|
| 132 |
auto cs = (SkGradient::Interpolation::ColorSpace)( |
| 133 |
(flags >> kInterpolationColorSpaceShift_GSF) & kInterpolationColorSpaceMask_GSF); |
| 134 |
auto hm = (SkGradient::Interpolation::HueMethod)( |
| 135 |
(flags >> kInterpolationHueMethodShift_GSF) & kInterpolationHueMethodMask_GSF); |
| 136 |
auto pm = (flags & kInterpolationInPremul_GSF) ? SkGradient::Interpolation::InPremul::kYes |
| 137 |
: SkGradient::Interpolation::InPremul::kNo; |
| 138 |
|
| 139 |
const size_t count = buffer.getArrayCount(); |
| 140 |
|
| 141 |
if (!(validate_array(buffer, count, &fColorStorage) && |
| 142 |
buffer.readColor4fArray({fColorStorage.data(), count}))) { |
| 143 |
return {}; |
| 144 |
} |
| 145 |
SkSpan<const SkColor4f> colors = {fColorStorage.begin(), count}; |
| 146 |
|
| 147 |
sk_sp<SkColorSpace> colorSpace; |
| 148 |
if (flags & kHasColorSpace_GSF) { |
| 149 |
if (auto data = buffer.readByteArrayAsData()) { |
| 150 |
colorSpace = SkColorSpace::Deserialize(data->data(), data->size()); |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
SkSpan<const float> pos; |
| 155 |
if (flags & kHasPosition_GSF) { |
| 156 |
if (!(validate_array(buffer, count, &fPositionStorage) && |
| 157 |
buffer.readScalarArray({fPositionStorage.data(), count}))) { |
| 158 |
return {}; |
| 159 |
} |
| 160 |
pos = {fPositionStorage.begin(), count}; |
| 161 |
} |
| 162 |
|
| 163 |
if (flags & kHasLegacyLocalMatrix_GSF) { |
| 164 |
SkASSERT(buffer.isVersionLT(SkPicturePriv::Version::kNoShaderLocalMatrix)); |
| 165 |
buffer.readMatrix(legacyLocalMatrix); |
| 166 |
} else { |
| 167 |
*legacyLocalMatrix = SkMatrix::I(); |
| 168 |
} |
| 169 |
|
| 170 |
if (buffer.isValid()) { |
| 171 |
return SkGradient({colors, pos, tm, std::move(colorSpace)}, |
| 172 |
{pm, cs, hm}); |
| 173 |
} |
| 174 |
return {}; |
| 175 |
} |
| 176 |
|
| 177 |
//////////////////////////////////////////////////////////////////////////////////////////// |
| 178 |
|
| 179 |
sk_sp<SkColorSpace> srgb_if_null(sk_sp<SkColorSpace> cs) { |
| 180 |
return cs ? cs : SkColorSpace::MakeSRGB(); |
| 181 |
} |
| 182 |
|
| 183 |
SkGradientBaseShader::SkGradientBaseShader(const SkGradient& desc, const SkMatrix& ptsToUnit) |
| 184 |
: fPtsToUnit(ptsToUnit) |
| 185 |
, fColorSpace(srgb_if_null(desc.colors().colorSpace())) |
| 186 |
, fFirstStopIsImplicit(false) |
| 187 |
, fLastStopIsImplicit(false) |
| 188 |
, fColorsAreOpaque(true) { |
| 189 |
auto colors = desc.colors().colors(); |
| 190 |
auto pos = desc.colors().positions(); |
| 191 |
|
| 192 |
fPtsToUnit.getType(); // Precache so reads are threadsafe. |
| 193 |
SkASSERT(colors.size() > 1); |
| 194 |
|
| 195 |
fInterpolation = desc.interpolation(); |
| 196 |
|
| 197 |
SkASSERT((unsigned)desc.colors().tileMode() < kSkTileModeCount); |
| 198 |
fTileMode = desc.colors().tileMode(); |
| 199 |
|
| 200 |
/* Note: we let the caller skip the first and/or last position. |
| 201 |
i.e. pos[0] = 0.3, pos[1] = 0.7 |
| 202 |
In these cases, we insert entries to ensure that the final data |
| 203 |
will be bracketed by [0, 1]. |
| 204 |
i.e. our_pos[0] = 0, our_pos[1] = 0.3, our_pos[2] = 0.7, our_pos[3] = 1 |
| 205 |
|
| 206 |
Thus colorCount (the caller's value, and fColorCount (our value) may |
| 207 |
differ by up to 2. In the above example: |
| 208 |
colorCount = 2 |
| 209 |
fColorCount = 4 |
| 210 |
*/ |
| 211 |
fColorCount = colors.size(); |
| 212 |
|
| 213 |
// Check if we need to add in start and/or end position/colors |
| 214 |
if (pos.size() > 0) { |
| 215 |
fFirstStopIsImplicit = pos.front() > 0; |
| 216 |
fLastStopIsImplicit = pos.back() != SK_Scalar1; |
| 217 |
fColorCount += fFirstStopIsImplicit + fLastStopIsImplicit; |
| 218 |
} |
| 219 |
|
| 220 |
size_t storageSize = |
| 221 |
fColorCount * (sizeof(SkColor4f) + (pos.size() > 0 ? sizeof(SkScalar) : 0)); |
| 222 |
fColors = reinterpret_cast<SkColor4f*>(fStorage.reset(storageSize)); |
| 223 |
fPositions = pos.size() > 0 ? reinterpret_cast<float*>(fColors + fColorCount) : nullptr; |
| 224 |
|
| 225 |
// Now copy over the colors, adding the duplicates at t=0 and t=1 as needed |
| 226 |
SkColor4f* colorPtr = fColors; |
| 227 |
if (fFirstStopIsImplicit) { |
| 228 |
*colorPtr++ = colors[0]; |
| 229 |
} |
| 230 |
for (size_t i = 0; i < colors.size(); ++i) { |
| 231 |
colorPtr[i] = colors[i]; |
| 232 |
fColorsAreOpaque = fColorsAreOpaque && (colors[i].fA == 1); |
| 233 |
} |
| 234 |
if (fLastStopIsImplicit) { |
| 235 |
colorPtr += colors.size(); |
| 236 |
*colorPtr = colors.back(); |
| 237 |
} |
| 238 |
|
| 239 |
if (pos.size() > 0) { |
| 240 |
SkScalar prev = 0; |
| 241 |
SkScalar* positions = fPositions; |
| 242 |
*positions++ = prev; // force the first pos to 0 |
| 243 |
|
| 244 |
size_t startIndex = fFirstStopIsImplicit ? 0 : 1; |
| 245 |
size_t count = pos.size() + fLastStopIsImplicit; |
| 246 |
|
| 247 |
bool uniformStops = true; |
| 248 |
const SkScalar uniformStep = pos[startIndex] - prev; |
| 249 |
for (size_t i = startIndex; i < count; i++) { |
| 250 |
// Pin the last value to 1.0, and make sure pos is monotonic. |
| 251 |
float curr = 1.0f; |
| 252 |
if (i != pos.size()) { |
| 253 |
curr = SkTPin(pos[i], prev, 1.0f); |
| 254 |
|
| 255 |
// If a value is clamped to 1.0 before the last stop, the last stop |
| 256 |
// actually isn't implicit if we thought it was. |
| 257 |
if (curr == 1.0f && fLastStopIsImplicit) { |
| 258 |
fLastStopIsImplicit = false; |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
uniformStops &= SkScalarNearlyEqual(uniformStep, curr - prev); |
| 263 |
|
| 264 |
*positions++ = prev = curr; |
| 265 |
} |
| 266 |
|
| 267 |
if (uniformStops) { |
| 268 |
// If the stops are uniform, treat them as implicit. |
| 269 |
fPositions = nullptr; |
| 270 |
} else { |
| 271 |
// Remove duplicate stops with more than two of the same stop, |
| 272 |
// keeping the leftmost and rightmost stop colors. |
| 273 |
// i.e. 0, 0, 0, 0.2, 0.2, 0.3, 0.3, 0.3, 1, 1 |
| 274 |
// w/ clamp 0, 0, 0.2, 0.2, 0.3, 0.3, 1, 1 |
| 275 |
// w/o clamp 0, 0.2, 0.2, 0.3, 0.3, 1 |
| 276 |
size_t i = 0; |
| 277 |
size_t dedupedColorCount = 0; |
| 278 |
for (size_t j = 1; j <= fColorCount; j++) { |
| 279 |
// We can compare the current positions at i and j since once these fPosition |
| 280 |
// values are overwritten, our i and j pointers will be past the overwritten values. |
| 281 |
if (j == fColorCount || fPositions[i] != fPositions[j]) { |
| 282 |
SkASSERT(j >= i); |
| 283 |
bool dupStop = j - i > 1; |
| 284 |
|
| 285 |
// Ignore the leftmost stop (i) if it is a non-clamp tilemode with |
| 286 |
// a duplicate stop on t = 0. |
| 287 |
bool ignoreLeftmost = dupStop && fTileMode != SkTileMode::kClamp |
| 288 |
&& fPositions[i] == 0; |
| 289 |
if (!ignoreLeftmost) { |
| 290 |
fPositions[dedupedColorCount] = fPositions[i]; |
| 291 |
fColors[dedupedColorCount] = fColors[i]; |
| 292 |
dedupedColorCount++; |
| 293 |
} |
| 294 |
|
| 295 |
// Include the rightmost stop (j-1) only if the stop has a duplicate, |
| 296 |
// ignoring the rightmost stop if it is a non-clamp tilemode with t = 1. |
| 297 |
bool ignoreRightmost = fTileMode != SkTileMode::kClamp |
| 298 |
&& fPositions[j - 1] == 1; |
| 299 |
if (dupStop && !ignoreRightmost) { |
| 300 |
fPositions[dedupedColorCount] = fPositions[j - 1]; |
| 301 |
fColors[dedupedColorCount] = fColors[j - 1]; |
| 302 |
dedupedColorCount++; |
| 303 |
} |
| 304 |
i = j; |
| 305 |
} |
| 306 |
} |
| 307 |
fColorCount = dedupedColorCount; |
| 308 |
} |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
SkGradientBaseShader::~SkGradientBaseShader() {} |
| 313 |
|
| 314 |
static void add_stop_color(SkRasterPipelineContexts::GradientCtx* ctx, |
| 315 |
size_t stop, |
| 316 |
const SkPMColor4f& Fs, |
| 317 |
const SkPMColor4f& Bs) { |
| 318 |
(ctx->factors[0])[stop] = Fs.fR; |
| 319 |
(ctx->factors[1])[stop] = Fs.fG; |
| 320 |
(ctx->factors[2])[stop] = Fs.fB; |
| 321 |
(ctx->factors[3])[stop] = Fs.fA; |
| 322 |
|
| 323 |
(ctx->biases[0])[stop] = Bs.fR; |
| 324 |
(ctx->biases[1])[stop] = Bs.fG; |
| 325 |
(ctx->biases[2])[stop] = Bs.fB; |
| 326 |
(ctx->biases[3])[stop] = Bs.fA; |
| 327 |
} |
| 328 |
|
| 329 |
static void add_const_color(SkRasterPipelineContexts::GradientCtx* ctx, |
| 330 |
size_t stop, |
| 331 |
const SkPMColor4f& color) { |
| 332 |
add_stop_color(ctx, stop, {0, 0, 0, 0}, color); |
| 333 |
} |
| 334 |
|
| 335 |
// Calculate a factor F and a bias B so that color = F*t + B when t is in range of |
| 336 |
// the stop. Assume that all stops have width 1/gapCount and the stop parameter |
| 337 |
// refers to the nth stop. |
| 338 |
static void init_stop_evenly(SkRasterPipelineContexts::GradientCtx* ctx, |
| 339 |
float gapCount, |
| 340 |
size_t stop, |
| 341 |
const SkPMColor4f& leftC, |
| 342 |
const SkPMColor4f& rightC) { |
| 343 |
auto left = skvx::float4::Load(leftC.vec()); |
| 344 |
auto right = skvx::float4::Load(rightC.vec()); |
| 345 |
|
| 346 |
SkPMColor4f factor, bias; |
| 347 |
|
| 348 |
// We start with the following 2 linear equations and 2 unknowns (factor, bias) |
| 349 |
// left = factor * t + bias |
| 350 |
// right = factor * (t + gap) + bias |
| 351 |
// gap = 1/gapCount |
| 352 |
// t = gap * stop |
| 353 |
|
| 354 |
// right - left = factor * (t + gap) - factor * t |
| 355 |
// right - left = factor * gap |
| 356 |
// factor = (right - left) / gap (and gap = 1/gapCount) |
| 357 |
auto factor4 = ((right - left) * gapCount); |
| 358 |
(left - (factor4 * (stop / gapCount))).store(bias.vec()); |
| 359 |
factor4.store(factor.vec()); |
| 360 |
|
| 361 |
add_stop_color(ctx, stop, factor, bias); |
| 362 |
} |
| 363 |
|
| 364 |
// Calculate a factor F and a bias B so that color = F*t + B when t is in range of |
| 365 |
// the stop. Unlike init_stop_evenly, this handles stops |
| 366 |
static void init_stop_pos(SkRasterPipelineContexts::GradientCtx* ctx, |
| 367 |
size_t stop, |
| 368 |
float t_l, |
| 369 |
float gapReciprocal, |
| 370 |
const SkPMColor4f& leftC, |
| 371 |
const SkPMColor4f& rightC) { |
| 372 |
// gapReciprocal is 1/gapWidth. If two colors were on top of each other, we should |
| 373 |
// have skipped that as a "stop". |
| 374 |
SkASSERT(SkIsFinite(gapReciprocal)); |
| 375 |
|
| 376 |
auto left = skvx::float4::Load(leftC.vec()); |
| 377 |
auto right = skvx::float4::Load(rightC.vec()); |
| 378 |
|
| 379 |
SkPMColor4f factor, bias; |
| 380 |
|
| 381 |
// See init_stop_evenly for this derivation, noting that gap = 1/gapReciprocal |
| 382 |
// and t = t_l |
| 383 |
auto factor4 = ((right - left) * gapReciprocal); |
| 384 |
(left - (factor4 * t_l)).store(bias.vec()); |
| 385 |
factor4.store(factor.vec()); |
| 386 |
|
| 387 |
ctx->ts[stop] = t_l; |
| 388 |
add_stop_color(ctx, stop, factor, bias); |
| 389 |
} |
| 390 |
|
| 391 |
void SkGradientBaseShader::AppendGradientFillStages(SkRasterPipeline* p, |
| 392 |
SkArenaAlloc* alloc, |
| 393 |
const SkPMColor4f* pmColors, |
| 394 |
const SkScalar* positions, |
| 395 |
int count) { |
| 396 |
// The two-stop case with stops at 0 and 1. |
| 397 |
if (count == 2 && positions == nullptr) { |
| 398 |
const SkPMColor4f c_l = pmColors[0], c_r = pmColors[1]; |
| 399 |
|
| 400 |
auto ctx = alloc->make<SkRasterPipelineContexts::EvenlySpaced2StopGradientCtx>(); |
| 401 |
(skvx::float4::Load(c_r.vec()) - skvx::float4::Load(c_l.vec())).store(ctx->factor); |
| 402 |
(skvx::float4::Load(c_l.vec())).store(ctx->bias); |
| 403 |
|
| 404 |
p->append(SkRasterPipelineOp::evenly_spaced_2_stop_gradient, ctx); |
| 405 |
return; |
| 406 |
} |
| 407 |
// Linear gradients with evenly spaced stops involve doing calculations to interpolate |
| 408 |
// between color n and color n+1 based on t (in range [0.0,1.0]). |
| 409 |
// color_n * (t - t_n) / gap_n + color_{n+1} * (t_{n+1} - t) / gap_n |
| 410 |
// We could just stick the colors and the gaps calculation in RP and do this calculation, |
| 411 |
// but instead we can precompute things to make the RP calculation simpler and faster. |
| 412 |
// For each gap, we calculate four linear equations in the form y = m*x + b, or rather |
| 413 |
// color_channel = factor * t + bias |
| 414 |
// We do this pre-computation in init_stop_evenly and init_stop_pos. |
| 415 |
|
| 416 |
auto* ctx = alloc->make<SkRasterPipelineContexts::GradientCtx>(); |
| 417 |
|
| 418 |
// Allocate at least enough for the AVX2 gather from a YMM register. |
| 419 |
constexpr int kMaxRegisterSize = 8; |
| 420 |
|
| 421 |
// There are n - 1 gaps between n colors plus 2 regions to the left and right |
| 422 |
// of the gradient to account for colors. For evenly spaced gradients, we cheat |
| 423 |
// and skip the left gap, using one block of floats unused. |
| 424 |
const size_t factorBiasFloats = std::max(count + 1, kMaxRegisterSize); |
| 425 |
const size_t tsForArbitraryStops = count + 1; |
| 426 |
using SkRasterPipelineContexts::kRGBAChannels; |
| 427 |
|
| 428 |
// We need space for all factors and biases, and while we are at it, some space |
| 429 |
// if we need to include the arbitrary stops. |
| 430 |
const size_t toAlloc = 2 * kRGBAChannels * factorBiasFloats + tsForArbitraryStops; |
| 431 |
float* gradientCtxBuffer = alloc->makeArray<float>(toAlloc); |
| 432 |
for (size_t i = 0; i < kRGBAChannels; i++) { |
| 433 |
ctx->factors[i] = gradientCtxBuffer; |
| 434 |
gradientCtxBuffer += factorBiasFloats; |
| 435 |
ctx->biases[i] = gradientCtxBuffer; |
| 436 |
gradientCtxBuffer += factorBiasFloats; |
| 437 |
} |
| 438 |
|
| 439 |
if (positions == nullptr) { |
| 440 |
// Handle evenly distributed stops. |
| 441 |
|
| 442 |
size_t stopCount = count; |
| 443 |
float gapCount = stopCount - 1; |
| 444 |
|
| 445 |
SkPMColor4f c_l = pmColors[0]; |
| 446 |
for (size_t i = 0; i < gapCount; i++) { |
| 447 |
SkPMColor4f c_r = pmColors[i + 1]; |
| 448 |
init_stop_evenly(ctx, gapCount, i, c_l, c_r); |
| 449 |
c_l = c_r; |
| 450 |
} |
| 451 |
add_const_color(ctx, stopCount - 1, c_l); |
| 452 |
|
| 453 |
ctx->stopCount = stopCount; |
| 454 |
p->append(SkRasterPipelineOp::evenly_spaced_gradient, ctx); |
| 455 |
return; |
| 456 |
} |
| 457 |
|
| 458 |
// Handle arbitrary stops. |
| 459 |
ctx->ts = gradientCtxBuffer; |
| 460 |
|
| 461 |
// Remove the default stops inserted by SkGradientBaseShader::SkGradientBaseShader |
| 462 |
// because they are naturally handled by the search method. |
| 463 |
int firstStop; |
| 464 |
int lastStop; |
| 465 |
if (count > 2) { |
| 466 |
firstStop = pmColors[0] != pmColors[1] ? 0 : 1; |
| 467 |
lastStop = pmColors[count - 2] != pmColors[count - 1] ? count - 1 : count - 2; |
| 468 |
} else { |
| 469 |
firstStop = 0; |
| 470 |
lastStop = 1; |
| 471 |
} |
| 472 |
|
| 473 |
size_t stopCount = 0; |
| 474 |
float t_l = positions[firstStop]; |
| 475 |
SkPMColor4f c_l = pmColors[firstStop]; |
| 476 |
add_const_color(ctx, stopCount++, c_l); |
| 477 |
|
| 478 |
for (int i = firstStop; i < lastStop; i++) { |
| 479 |
float t_r = positions[i + 1]; |
| 480 |
SkPMColor4f c_r = pmColors[i + 1]; |
| 481 |
SkASSERT(t_l <= t_r); |
| 482 |
if (t_l < t_r) { |
| 483 |
float c_scale = sk_ieee_float_divide(1, t_r - t_l); |
| 484 |
if (SkIsFinite(c_scale)) { |
| 485 |
init_stop_pos(ctx, stopCount, t_l, c_scale, c_l, c_r); |
| 486 |
stopCount += 1; |
| 487 |
} |
| 488 |
} |
| 489 |
t_l = t_r; |
| 490 |
c_l = c_r; |
| 491 |
} |
| 492 |
|
| 493 |
ctx->ts[stopCount] = t_l; |
| 494 |
add_const_color(ctx, stopCount++, c_l); |
| 495 |
|
| 496 |
ctx->stopCount = stopCount; |
| 497 |
p->append(SkRasterPipelineOp::gradient, ctx); |
| 498 |
} |
| 499 |
|
| 500 |
void SkGradientBaseShader::AppendInterpolatedToDstStages(SkRasterPipeline* p, |
| 501 |
SkArenaAlloc* alloc, |
| 502 |
bool colorsAreOpaque, |
| 503 |
const Interpolation& interpolation, |
| 504 |
const SkColorSpace* intermediateColorSpace, |
| 505 |
const SkColorSpace* dstColorSpace) { |
| 506 |
using ColorSpace = Interpolation::ColorSpace; |
| 507 |
bool colorIsPremul = static_cast<bool>(interpolation.fInPremul); |
| 508 |
|
| 509 |
// If we interpolated premul colors in any of the special color spaces, we need to unpremul |
| 510 |
if (colorIsPremul && !colorsAreOpaque) { |
| 511 |
switch (interpolation.fColorSpace) { |
| 512 |
case ColorSpace::kLab: |
| 513 |
case ColorSpace::kOKLab: |
| 514 |
case ColorSpace::kOKLabGamutMap: |
| 515 |
p->append(SkRasterPipelineOp::unpremul); |
| 516 |
colorIsPremul = false; |
| 517 |
break; |
| 518 |
case ColorSpace::kLCH: |
| 519 |
case ColorSpace::kOKLCH: |
| 520 |
case ColorSpace::kOKLCHGamutMap: |
| 521 |
case ColorSpace::kHSL: |
| 522 |
case ColorSpace::kHWB: |
| 523 |
p->append(SkRasterPipelineOp::unpremul_polar); |
| 524 |
colorIsPremul = false; |
| 525 |
break; |
| 526 |
default: |
| 527 |
break; |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
// Convert colors in exotic spaces back to their intermediate SkColorSpace |
| 532 |
switch (interpolation.fColorSpace) { |
| 533 |
case ColorSpace::kLab: p->append(SkRasterPipelineOp::css_lab_to_xyz); break; |
| 534 |
case ColorSpace::kOKLab: p->append(SkRasterPipelineOp::css_oklab_to_linear_srgb); break; |
| 535 |
case ColorSpace::kOKLabGamutMap: |
| 536 |
p->append(SkRasterPipelineOp::css_oklab_gamut_map_to_linear_srgb); |
| 537 |
break; |
| 538 |
case ColorSpace::kLCH: p->append(SkRasterPipelineOp::css_hcl_to_lab); |
| 539 |
p->append(SkRasterPipelineOp::css_lab_to_xyz); break; |
| 540 |
case ColorSpace::kOKLCH: p->append(SkRasterPipelineOp::css_hcl_to_lab); |
| 541 |
p->append(SkRasterPipelineOp::css_oklab_to_linear_srgb); break; |
| 542 |
case ColorSpace::kOKLCHGamutMap: |
| 543 |
p->append(SkRasterPipelineOp::css_hcl_to_lab); |
| 544 |
p->append(SkRasterPipelineOp::css_oklab_gamut_map_to_linear_srgb); |
| 545 |
break; |
| 546 |
case ColorSpace::kHSL: p->append(SkRasterPipelineOp::css_hsl_to_srgb); break; |
| 547 |
case ColorSpace::kHWB: p->append(SkRasterPipelineOp::css_hwb_to_srgb); break; |
| 548 |
default: break; |
| 549 |
} |
| 550 |
|
| 551 |
// Now transform from intermediate to destination color space. |
| 552 |
// See comments in GrGradientShader.cpp about the decisions here. |
| 553 |
if (!dstColorSpace) { |
| 554 |
dstColorSpace = sk_srgb_singleton(); |
| 555 |
} |
| 556 |
SkAlphaType intermediateAlphaType = colorIsPremul ? kPremul_SkAlphaType : kUnpremul_SkAlphaType; |
| 557 |
// TODO(skbug.com/40044213): Get dst alpha type correctly |
| 558 |
SkAlphaType dstAlphaType = kPremul_SkAlphaType; |
| 559 |
|
| 560 |
if (colorsAreOpaque) { |
| 561 |
intermediateAlphaType = dstAlphaType = kUnpremul_SkAlphaType; |
| 562 |
} |
| 563 |
|
| 564 |
alloc->make<SkColorSpaceXformSteps>( |
| 565 |
intermediateColorSpace, intermediateAlphaType, dstColorSpace, dstAlphaType) |
| 566 |
->apply(p); |
| 567 |
} |
| 568 |
|
| 569 |
bool SkGradientBaseShader::appendStages(const SkStageRec& rec, |
| 570 |
const SkShaders::MatrixRec& mRec) const { |
| 571 |
SkRasterPipeline* p = rec.fPipeline; |
| 572 |
SkArenaAlloc* alloc = rec.fAlloc; |
| 573 |
SkRasterPipelineContexts::DecalTileCtx* decal_ctx = nullptr; |
| 574 |
|
| 575 |
std::optional<SkShaders::MatrixRec> newMRec = mRec.apply(rec, fPtsToUnit); |
| 576 |
if (!newMRec.has_value()) { |
| 577 |
return false; |
| 578 |
} |
| 579 |
|
| 580 |
SkRasterPipeline_<256> postPipeline; |
| 581 |
|
| 582 |
this->appendGradientStages(alloc, p, &postPipeline); |
| 583 |
|
| 584 |
switch (fTileMode) { |
| 585 |
case SkTileMode::kMirror: |
| 586 |
p->append(SkRasterPipelineOp::mirror_x_1); |
| 587 |
break; |
| 588 |
case SkTileMode::kRepeat: |
| 589 |
p->append(SkRasterPipelineOp::repeat_x_1); |
| 590 |
break; |
| 591 |
case SkTileMode::kDecal: |
| 592 |
decal_ctx = alloc->make<SkRasterPipelineContexts::DecalTileCtx>(); |
| 593 |
decal_ctx->limit_x = SkBits2Float(SkFloat2Bits(1.0f) + 1); |
| 594 |
// reuse mask + limit_x stage, or create a custom decal_1 that just stores the mask |
| 595 |
p->append(SkRasterPipelineOp::decal_x, decal_ctx); |
| 596 |
[[fallthrough]]; |
| 597 |
|
| 598 |
case SkTileMode::kClamp: |
| 599 |
if (!fPositions) { |
| 600 |
// We clamp only when the stops are evenly spaced. |
| 601 |
// If not, there may be hard stops, and clamping ruins hard stops at 0 and/or 1. |
| 602 |
// In that case, we must make sure we're using the general "gradient" stage, |
| 603 |
// which is the only stage that will correctly handle unclamped t. |
| 604 |
p->append(SkRasterPipelineOp::clamp_x_1); |
| 605 |
} |
| 606 |
break; |
| 607 |
} |
| 608 |
|
| 609 |
// Transform all of the colors to destination color space, possibly premultiplied |
| 610 |
SkColor4fXformer xformedColors(this, rec.fDstCS); |
| 611 |
AppendGradientFillStages(p, alloc, |
| 612 |
xformedColors.fColors.begin(), |
| 613 |
xformedColors.fPositions, |
| 614 |
xformedColors.fColors.size()); |
| 615 |
AppendInterpolatedToDstStages(p, alloc, fColorsAreOpaque, fInterpolation, |
| 616 |
xformedColors.fIntermediateColorSpace.get(), rec.fDstCS); |
| 617 |
|
| 618 |
if (decal_ctx) { |
| 619 |
p->append(SkRasterPipelineOp::check_decal_mask, decal_ctx); |
| 620 |
} |
| 621 |
|
| 622 |
p->extend(postPipeline); |
| 623 |
|
| 624 |
return true; |
| 625 |
} |
| 626 |
|
| 627 |
bool SkGradientBaseShader::isOpaque() const { |
| 628 |
return fColorsAreOpaque && (this->getTileMode() != SkTileMode::kDecal); |
| 629 |
} |
| 630 |
|
| 631 |
bool SkGradientBaseShader::onAsLuminanceColor(SkColor4f* lum) const { |
| 632 |
// We just compute an average color. There are several things we could do better: |
| 633 |
// 1) We already have a different average_gradient_color helper later in this file, that weights |
| 634 |
// contribution by the relative size of each band. |
| 635 |
// 2) Colors should be converted to some standard color space! These could be in any space. |
| 636 |
// 3) Do we want to average in the source space, sRGB, or some linear space? |
| 637 |
SkColor4f color{0, 0, 0, 1}; |
| 638 |
for (size_t i = 0; i < fColorCount; ++i) { |
| 639 |
color.fR += fColors[i].fR; |
| 640 |
color.fG += fColors[i].fG; |
| 641 |
color.fB += fColors[i].fB; |
| 642 |
} |
| 643 |
const float scale = 1.0f / fColorCount; |
| 644 |
color.fR *= scale; |
| 645 |
color.fG *= scale; |
| 646 |
color.fB *= scale; |
| 647 |
*lum = color; |
| 648 |
return true; |
| 649 |
} |
| 650 |
|
| 651 |
static sk_sp<SkColorSpace> intermediate_color_space(SkGradient::Interpolation::ColorSpace cs, |
| 652 |
SkColorSpace* dst) { |
| 653 |
using ColorSpace = SkGradient::Interpolation::ColorSpace; |
| 654 |
switch (cs) { |
| 655 |
case ColorSpace::kDestination: |
| 656 |
return sk_ref_sp(dst); |
| 657 |
|
| 658 |
// css-color-4 allows XYZD50 and XYZD65. For gradients, those are redundant. Interpolating |
| 659 |
// in any linear RGB space, (regardless of white point), gives the same answer. |
| 660 |
case ColorSpace::kSRGBLinear: |
| 661 |
return SkColorSpace::MakeSRGBLinear(); |
| 662 |
|
| 663 |
case ColorSpace::kSRGB: |
| 664 |
case ColorSpace::kHSL: |
| 665 |
case ColorSpace::kHWB: |
| 666 |
return SkColorSpace::MakeSRGB(); |
| 667 |
|
| 668 |
case ColorSpace::kLab: |
| 669 |
case ColorSpace::kLCH: |
| 670 |
// Conversion to Lab (and LCH) starts with XYZD50 |
| 671 |
return SkColorSpace::MakeRGB(SkNamedTransferFn::kLinear, SkNamedGamut::kXYZ); |
| 672 |
|
| 673 |
case ColorSpace::kOKLab: |
| 674 |
case ColorSpace::kOKLabGamutMap: |
| 675 |
case ColorSpace::kOKLCH: |
| 676 |
case ColorSpace::kOKLCHGamutMap: |
| 677 |
// The "standard" conversion to these spaces starts with XYZD65. That requires extra |
| 678 |
// effort to conjure. The author also has reference code for going directly from linear |
| 679 |
// sRGB, so we use that. |
| 680 |
// TODO(skbug.com/40044213): Even better would be to have an LMS color space, because the first |
| 681 |
// part of the conversion is a matrix multiply, which could be absorbed into the |
| 682 |
// color space xform. |
| 683 |
return SkColorSpace::MakeSRGBLinear(); |
| 684 |
|
| 685 |
// These rectangular color spaces have their own transfer curves. |
| 686 |
case ColorSpace::kDisplayP3: |
| 687 |
return SkColorSpace::MakeRGB(SkNamedTransferFn::kSRGB, SkNamedGamut::kDisplayP3); |
| 688 |
|
| 689 |
case ColorSpace::kRec2020: |
| 690 |
return SkColorSpace::MakeRGB(SkNamedTransferFn::kRec2020, SkNamedGamut::kRec2020); |
| 691 |
|
| 692 |
case ColorSpace::kProphotoRGB: { |
| 693 |
static SkOnce once; |
| 694 |
static skcms_Matrix3x3 lin_proPhoto_to_XYZ_D50; |
| 695 |
once([] { SkNamedPrimaries::kProPhotoRGB.toXYZD50(&lin_proPhoto_to_XYZ_D50); }); |
| 696 |
return SkColorSpace::MakeRGB(SkNamedTransferFn::kProPhotoRGB, lin_proPhoto_to_XYZ_D50); |
| 697 |
} |
| 698 |
|
| 699 |
case ColorSpace::kA98RGB: |
| 700 |
return SkColorSpace::MakeRGB(SkNamedTransferFn::kA98RGB, SkNamedGamut::kAdobeRGB); |
| 701 |
} |
| 702 |
SkUNREACHABLE; |
| 703 |
} |
| 704 |
|
| 705 |
using ConvertColorProc = SkPMColor4f(*)(SkPMColor4f, bool*); |
| 706 |
using PremulColorProc = SkPMColor4f(*)(SkPMColor4f); |
| 707 |
|
| 708 |
static SkPMColor4f srgb_to_hsl(SkPMColor4f rgb, bool* hueIsPowerless) { |
| 709 |
float mx = std::max({rgb.fR, rgb.fG, rgb.fB}); |
| 710 |
float mn = std::min({rgb.fR, rgb.fG, rgb.fB}); |
| 711 |
float hue = 0, sat = 0, light = (mn + mx) / 2; |
| 712 |
float d = mx - mn; |
| 713 |
|
| 714 |
if (d != 0) { |
| 715 |
sat = (light == 0 || light == 1) ? 0 : (mx - light) / std::min(light, 1 - light); |
| 716 |
if (mx == rgb.fR) { |
| 717 |
hue = (rgb.fG - rgb.fB) / d + (rgb.fG < rgb.fB ? 6 : 0); |
| 718 |
} else if (mx == rgb.fG) { |
| 719 |
hue = (rgb.fB - rgb.fR) / d + 2; |
| 720 |
} else { |
| 721 |
hue = (rgb.fR - rgb.fG) / d + 4; |
| 722 |
} |
| 723 |
|
| 724 |
hue *= 60; |
| 725 |
} |
| 726 |
if (sat == 0) { |
| 727 |
*hueIsPowerless = true; |
| 728 |
} |
| 729 |
return {hue, sat * 100, light * 100, rgb.fA}; |
| 730 |
} |
| 731 |
|
| 732 |
static SkPMColor4f srgb_to_hwb(SkPMColor4f rgb, bool* hueIsPowerless) { |
| 733 |
SkPMColor4f hsl = srgb_to_hsl(rgb, hueIsPowerless); |
| 734 |
float white = std::min({rgb.fR, rgb.fG, rgb.fB}); |
| 735 |
float black = 1 - std::max({rgb.fR, rgb.fG, rgb.fB}); |
| 736 |
return {hsl.fR, white * 100, black * 100, rgb.fA}; |
| 737 |
} |
| 738 |
|
| 739 |
static SkPMColor4f xyzd50_to_lab(SkPMColor4f xyz, bool* /*hueIsPowerless*/) { |
| 740 |
constexpr float D50[3] = {0.3457f / 0.3585f, 1.0f, (1.0f - 0.3457f - 0.3585f) / 0.3585f}; |
| 741 |
|
| 742 |
constexpr float e = 216.0f / 24389; |
| 743 |
constexpr float k = 24389.0f / 27; |
| 744 |
|
| 745 |
SkPMColor4f f; |
| 746 |
for (int i = 0; i < 3; ++i) { |
| 747 |
float v = xyz[i] / D50[i]; |
| 748 |
f[i] = (v > e) ? std::cbrtf(v) : (k * v + 16) / 116; |
| 749 |
} |
| 750 |
|
| 751 |
return {(116 * f[1]) - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2]), xyz.fA}; |
| 752 |
} |
| 753 |
|
| 754 |
// The color space is technically LCH, but we produce HCL, so that all polar spaces have hue in the |
| 755 |
// first component. This simplifies the hue handling for HueMethod and premul/unpremul. |
| 756 |
static SkPMColor4f xyzd50_to_hcl(SkPMColor4f xyz, bool* hueIsPowerless) { |
| 757 |
SkPMColor4f Lab = xyzd50_to_lab(xyz, hueIsPowerless); |
| 758 |
float hue = sk_float_radians_to_degrees(atan2f(Lab[2], Lab[1])); |
| 759 |
float chroma = sqrtf(Lab[1] * Lab[1] + Lab[2] * Lab[2]); |
| 760 |
// The LCH math produces small-ish (but not tiny) chroma values for achromatic colors: |
| 761 |
constexpr float kMaxChromaForPowerlessHue = 1e-2f; |
| 762 |
if (chroma <= kMaxChromaForPowerlessHue) { |
| 763 |
*hueIsPowerless = true; |
| 764 |
} |
| 765 |
return {hue >= 0 ? hue : hue + 360, chroma, Lab[0], xyz.fA}; |
| 766 |
} |
| 767 |
|
| 768 |
// https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab |
| 769 |
static SkPMColor4f lin_srgb_to_oklab(SkPMColor4f rgb, bool* /*hueIsPowerless*/) { |
| 770 |
float l = 0.4122214708f * rgb.fR + 0.5363325363f * rgb.fG + 0.0514459929f * rgb.fB; |
| 771 |
float m = 0.2119034982f * rgb.fR + 0.6806995451f * rgb.fG + 0.1073969566f * rgb.fB; |
| 772 |
float s = 0.0883024619f * rgb.fR + 0.2817188376f * rgb.fG + 0.6299787005f * rgb.fB; |
| 773 |
l = std::cbrtf(l); |
| 774 |
m = std::cbrtf(m); |
| 775 |
s = std::cbrtf(s); |
| 776 |
return {0.2104542553f * l + 0.7936177850f * m - 0.0040720468f * s, |
| 777 |
1.9779984951f * l - 2.4285922050f * m + 0.4505937099f * s, |
| 778 |
0.0259040371f * l + 0.7827717662f * m - 0.8086757660f * s, |
| 779 |
rgb.fA}; |
| 780 |
} |
| 781 |
|
| 782 |
// The color space is technically OkLCH, but we produce HCL, so that all polar spaces have hue in |
| 783 |
// the first component. This simplifies the hue handling for HueMethod and premul/unpremul. |
| 784 |
static SkPMColor4f lin_srgb_to_okhcl(SkPMColor4f rgb, bool* hueIsPowerless) { |
| 785 |
SkPMColor4f OKLab = lin_srgb_to_oklab(rgb, hueIsPowerless); |
| 786 |
float hue = sk_float_radians_to_degrees(atan2f(OKLab[2], OKLab[1])); |
| 787 |
float chroma = sqrtf(OKLab[1] * OKLab[1] + OKLab[2] * OKLab[2]); |
| 788 |
// The OKLCH math produces very small chroma values for achromatic colors: |
| 789 |
constexpr float kMaxChromaForPowerlessHue = 1e-6f; |
| 790 |
if (chroma <= kMaxChromaForPowerlessHue) { |
| 791 |
*hueIsPowerless = true; |
| 792 |
} |
| 793 |
return {hue >= 0 ? hue : hue + 360, chroma, OKLab[0], rgb.fA}; |
| 794 |
} |
| 795 |
|
| 796 |
static SkPMColor4f premul_polar(SkPMColor4f hsl) { |
| 797 |
return {hsl.fR, hsl.fG * hsl.fA, hsl.fB * hsl.fA, hsl.fA}; |
| 798 |
} |
| 799 |
|
| 800 |
static SkPMColor4f premul_rgb(SkPMColor4f rgb) { |
| 801 |
return {rgb.fR * rgb.fA, rgb.fG * rgb.fA, rgb.fB * rgb.fA, rgb.fA}; |
| 802 |
} |
| 803 |
|
| 804 |
static bool color_space_is_polar(SkGradient::Interpolation::ColorSpace cs) { |
| 805 |
using ColorSpace = SkGradient::Interpolation::ColorSpace; |
| 806 |
switch (cs) { |
| 807 |
case ColorSpace::kLCH: |
| 808 |
case ColorSpace::kOKLCH: |
| 809 |
case ColorSpace::kHSL: |
| 810 |
case ColorSpace::kHWB: |
| 811 |
return true; |
| 812 |
default: |
| 813 |
return false; |
| 814 |
} |
| 815 |
} |
| 816 |
|
| 817 |
// Given `colors` in `src` color space, an interpolation space, and a `dst` color space, |
| 818 |
// we are doing several things. First, some definitions: |
| 819 |
// |
| 820 |
// The interpolation color space is "special" if it can't be represented as an SkColorSpace. This |
| 821 |
// applies to any color space that isn't an RGB space, like Lab or HSL. These need special handling |
| 822 |
// because we have to run bespoke code to do the conversion (before interpolation here, and after |
| 823 |
// interpolation in the backend shader/pipeline). |
| 824 |
// |
| 825 |
// The interpolation color space is "polar" if it involves hue (HSL, HWB, LCH, Oklch). These need |
| 826 |
// special handling, becuase hue is never premultiplied, and because HueMethod comes into play. |
| 827 |
// |
| 828 |
// 1) Pick an `intermediate` SkColorSpace. If the interpolation color space is not "special", |
| 829 |
// (kDestination, kSRGB, etc... ), then `intermediate` is exact. Otherwise, `intermediate` is the |
| 830 |
// RGB space that prepares us to do the final conversion. For example, conversion to Lab starts |
| 831 |
// with XYZD50, so `intermediate` will be XYZD50 if we're actually interpolating in Lab. |
| 832 |
// 2) Transform all colors to the `intermediate` color space, leaving them unpremultiplied. |
| 833 |
// 3) If the interpolation color space is "special", transform the colors to that space. |
| 834 |
// 4) If the interpolation color space is "polar", adjust the angles to respect HueMethod. |
| 835 |
// 5) If premul interpolation is requested, apply that. For "polar" interpolated colors, don't |
| 836 |
// premultiply hue, only the other two channels. Note that there are four polar spaces. |
| 837 |
// Two have hue as the first component, and two have it as the third component. To reduce |
| 838 |
// complexity, we always store hue in the first component, swapping it with luminance for |
| 839 |
// LCH and Oklch. The backend code (eg, shaders) needs to know about this. |
| 840 |
SkColor4fXformer::SkColor4fXformer(const SkGradientBaseShader* shader, |
| 841 |
SkColorSpace* dst, |
| 842 |
bool forceExplicitPositions) { |
| 843 |
using ColorSpace = SkGradient::Interpolation::ColorSpace; |
| 844 |
using HueMethod = SkGradient::Interpolation::HueMethod; |
| 845 |
|
| 846 |
size_t colorCount = shader->colors().size(); |
| 847 |
const auto& interpolation = shader->interpolation(); |
| 848 |
|
| 849 |
// 0) Copy the shader's position pointer. Certain interpolation modes might force us to add |
| 850 |
// new stops, in which case we'll allocate & edit the positions. |
| 851 |
fPositions = shader->positions().data(); |
| 852 |
|
| 853 |
// 1) Determine the color space of our intermediate colors. |
| 854 |
fIntermediateColorSpace = intermediate_color_space(interpolation.fColorSpace, dst); |
| 855 |
|
| 856 |
// 2) Convert all colors to the intermediate color space |
| 857 |
auto info = SkImageInfo::Make(colorCount, 1, kRGBA_F32_SkColorType, kUnpremul_SkAlphaType); |
| 858 |
|
| 859 |
auto dstInfo = info.makeColorSpace(fIntermediateColorSpace); |
| 860 |
auto srcInfo = info.makeColorSpace(shader->colorSpace()); |
| 861 |
|
| 862 |
fColors.reset(colorCount); |
| 863 |
SkAssertResult(SkConvertPixels(dstInfo, |
| 864 |
fColors.begin(), |
| 865 |
info.minRowBytes(), |
| 866 |
srcInfo, |
| 867 |
shader->colors().data(), |
| 868 |
info.minRowBytes())); |
| 869 |
|
| 870 |
// 3) Transform to the interpolation color space (if it's special) |
| 871 |
ConvertColorProc convertFn = nullptr; |
| 872 |
switch (interpolation.fColorSpace) { |
| 873 |
case ColorSpace::kHSL: convertFn = srgb_to_hsl; break; |
| 874 |
case ColorSpace::kHWB: convertFn = srgb_to_hwb; break; |
| 875 |
case ColorSpace::kLab: convertFn = xyzd50_to_lab; break; |
| 876 |
case ColorSpace::kLCH: convertFn = xyzd50_to_hcl; break; |
| 877 |
case ColorSpace::kOKLab: convertFn = lin_srgb_to_oklab; break; |
| 878 |
case ColorSpace::kOKLabGamutMap: convertFn = lin_srgb_to_oklab; break; |
| 879 |
case ColorSpace::kOKLCH: convertFn = lin_srgb_to_okhcl; break; |
| 880 |
case ColorSpace::kOKLCHGamutMap: convertFn = lin_srgb_to_okhcl; break; |
| 881 |
default: break; |
| 882 |
} |
| 883 |
|
| 884 |
skia_private::STArray<4, bool> hueIsPowerless; |
| 885 |
bool anyPowerlessHue = false; |
| 886 |
hueIsPowerless.push_back_n(colorCount, false); |
| 887 |
if (convertFn) { |
| 888 |
for (size_t i = 0; i < colorCount; ++i) { |
| 889 |
fColors[i] = convertFn(fColors[i], hueIsPowerless.data() + i); |
| 890 |
anyPowerlessHue = anyPowerlessHue || hueIsPowerless[i]; |
| 891 |
} |
| 892 |
} |
| 893 |
|
| 894 |
if (anyPowerlessHue) { |
| 895 |
// In theory, if we knew we were just going to adjust the existing colors (without adding |
| 896 |
// new ones), we could do it all in-place. To keep things simple, we always generate the |
| 897 |
// new colors in separate storage. |
| 898 |
ColorStorage newColors; |
| 899 |
PositionStorage newPositions; |
| 900 |
|
| 901 |
for (size_t i = 0; i < colorCount; ++i) { |
| 902 |
const SkPMColor4f& curColor = fColors[i]; |
| 903 |
float curPos = shader->getPos(i); |
| 904 |
|
| 905 |
if (!hueIsPowerless[i]) { |
| 906 |
newColors.push_back(curColor); |
| 907 |
newPositions.push_back(curPos); |
| 908 |
continue; |
| 909 |
} |
| 910 |
|
| 911 |
auto colorWithHueFrom = [](const SkPMColor4f& color, const SkPMColor4f& hueColor) { |
| 912 |
// If we have any powerless hue, then all colors are already in (some) polar space, |
| 913 |
// and they all store their hue in the red channel. |
| 914 |
return SkPMColor4f{hueColor.fR, color.fG, color.fB, color.fA}; |
| 915 |
}; |
| 916 |
|
| 917 |
// In each case, we might be copying a powerless (invalid) hue from the neighbor, but |
| 918 |
// that should be fine, as it will match that neighbor perfectly, and any hue is ok. |
| 919 |
if (i != 0) { |
| 920 |
newPositions.push_back(curPos); |
| 921 |
newColors.push_back(colorWithHueFrom(curColor, fColors[i - 1])); |
| 922 |
} |
| 923 |
if (i != colorCount - 1) { |
| 924 |
newPositions.push_back(curPos); |
| 925 |
newColors.push_back(colorWithHueFrom(curColor, fColors[i + 1])); |
| 926 |
} |
| 927 |
} |
| 928 |
|
| 929 |
fColors.swap(newColors); |
| 930 |
fPositionStorage.swap(newPositions); |
| 931 |
fPositions = fPositionStorage.data(); |
| 932 |
colorCount = fColors.size(); |
| 933 |
} |
| 934 |
|
| 935 |
// 4) For polar colors, adjust hue values to respect the hue method. We're using a trick here... |
| 936 |
// The specification looks at adjacent colors, and adjusts one or the other. Because we store |
| 937 |
// the stops in uniforms (and our backend conversions normalize the hue angle), we can |
| 938 |
// instead always apply the adjustment to the *second* color. That lets us keep a running |
| 939 |
// total, and do a single pass across all the colors to respect the requested hue method, |
| 940 |
// without needing to do any extra work per-pixel. |
| 941 |
if (color_space_is_polar(interpolation.fColorSpace)) { |
| 942 |
float delta = 0; |
| 943 |
for (size_t i = 0; i < colorCount - 1; ++i) { |
| 944 |
float h1 = fColors[i].fR; |
| 945 |
float& h2 = fColors[i + 1].fR; |
| 946 |
h2 += delta; |
| 947 |
switch (interpolation.fHueMethod) { |
| 948 |
case HueMethod::kShorter: |
| 949 |
if (h2 - h1 > 180) { |
| 950 |
h2 -= 360; // i.e. h1 += 360 |
| 951 |
delta -= 360; |
| 952 |
} else if (h2 - h1 < -180) { |
| 953 |
h2 += 360; |
| 954 |
delta += 360; |
| 955 |
} |
| 956 |
break; |
| 957 |
case HueMethod::kLonger: |
| 958 |
if ((i == 0 && shader->firstStopIsImplicit()) || |
| 959 |
(i == colorCount - 2 && shader->lastStopIsImplicit())) { |
| 960 |
// Do nothing. We don't want to introduce a full revolution for these stops |
| 961 |
// Full rationale at skbug.com/40044215 |
| 962 |
} else if (0 < h2 - h1 && h2 - h1 < 180) { |
| 963 |
h2 -= 360; // i.e. h1 += 360 |
| 964 |
delta -= 360; |
| 965 |
} else if (-180 < h2 - h1 && h2 - h1 <= 0) { |
| 966 |
h2 += 360; |
| 967 |
delta += 360; |
| 968 |
} |
| 969 |
break; |
| 970 |
case HueMethod::kIncreasing: |
| 971 |
if (h2 < h1) { |
| 972 |
h2 += 360; |
| 973 |
delta += 360; |
| 974 |
} |
| 975 |
break; |
| 976 |
case HueMethod::kDecreasing: |
| 977 |
if (h1 < h2) { |
| 978 |
h2 -= 360; // i.e. h1 += 360; |
| 979 |
delta -= 360; |
| 980 |
} |
| 981 |
break; |
| 982 |
} |
| 983 |
} |
| 984 |
} |
| 985 |
|
| 986 |
// 5) Apply premultiplication |
| 987 |
PremulColorProc premulFn = nullptr; |
| 988 |
if (static_cast<bool>(interpolation.fInPremul)) { |
| 989 |
switch (interpolation.fColorSpace) { |
| 990 |
case ColorSpace::kHSL: |
| 991 |
case ColorSpace::kHWB: |
| 992 |
case ColorSpace::kLCH: |
| 993 |
case ColorSpace::kOKLCH: |
| 994 |
premulFn = premul_polar; |
| 995 |
break; |
| 996 |
default: |
| 997 |
premulFn = premul_rgb; |
| 998 |
break; |
| 999 |
} |
| 1000 |
} |
| 1001 |
|
| 1002 |
if (premulFn) { |
| 1003 |
for (size_t i = 0; i < colorCount; ++i) { |
| 1004 |
fColors[i] = premulFn(fColors[i]); |
| 1005 |
} |
| 1006 |
} |
| 1007 |
|
| 1008 |
// Ganesh requires that the positions be explicit (rather than implicitly evenly spaced) |
| 1009 |
if (forceExplicitPositions && !fPositions) { |
| 1010 |
fPositionStorage.reserve_exact(colorCount); |
| 1011 |
float posScale = 1.0f / (colorCount - 1); |
| 1012 |
for (size_t i = 0; i < colorCount; i++) { |
| 1013 |
fPositionStorage.push_back(i * posScale); |
| 1014 |
} |
| 1015 |
fPositions = fPositionStorage.data(); |
| 1016 |
} |
| 1017 |
} |
| 1018 |
|
| 1019 |
void SkGradientBaseShader::commonAsAGradient(GradientInfo* info) const { |
| 1020 |
if (info) { |
| 1021 |
const int colorCount = SkToInt(fColorCount); |
| 1022 |
if (info->fColorCount >= colorCount) { |
| 1023 |
if (info->fColors) { |
| 1024 |
for (int i = 0; i < colorCount; ++i) { |
| 1025 |
info->fColors[i] = fColors[i]; |
| 1026 |
} |
| 1027 |
} |
| 1028 |
if (info->fColorOffsets) { |
| 1029 |
for (int i = 0; i < colorCount; ++i) { |
| 1030 |
info->fColorOffsets[i] = this->getPos(i); |
| 1031 |
} |
| 1032 |
} |
| 1033 |
} |
| 1034 |
info->fColorCount = colorCount; |
| 1035 |
info->fTileMode = fTileMode; |
| 1036 |
info->fPremulInterp = this->interpolateInPremul(); |
| 1037 |
} |
| 1038 |
} |
| 1039 |
|
| 1040 |
// Return true if these parameters are valid/legal/safe to construct a gradient |
| 1041 |
// |
| 1042 |
bool SkGradientBaseShader::ValidGradient(SkSpan<const SkColor4f> colors, |
| 1043 |
SkTileMode tileMode, |
| 1044 |
const Interpolation& interpolation) { |
| 1045 |
return colors.data() && !colors.empty() && (unsigned)tileMode < kSkTileModeCount && |
| 1046 |
(unsigned)interpolation.fColorSpace < Interpolation::kColorSpaceCount && |
| 1047 |
(unsigned)interpolation.fHueMethod < Interpolation::kHueMethodCount; |
| 1048 |
} |
| 1049 |
|
| 1050 |
static SkColor4f average_gradient_color(SkSpan<const SkColor4f> colors, |
| 1051 |
SkSpan<const float> pos) { |
| 1052 |
// The gradient is a piecewise linear interpolation between colors. For a given interval, |
| 1053 |
// the integral between the two endpoints is 0.5 * (ci + cj) * (pj - pi), which provides that |
| 1054 |
// intervals average color. The overall average color is thus the sum of each piece. The thing |
| 1055 |
// to keep in mind is that the provided gradient definition may implicitly use p=0 and p=1. |
| 1056 |
skvx::float4 blend(0.0f); |
| 1057 |
for (size_t i = 0; i < colors.size() - 1; ++i) { |
| 1058 |
// Calculate the average color for the interval between pos(i) and pos(i+1) |
| 1059 |
auto c0 = skvx::float4::Load(&colors[i]); |
| 1060 |
auto c1 = skvx::float4::Load(&colors[i + 1]); |
| 1061 |
|
| 1062 |
// when pos == null, there are colorCount uniformly distributed stops, going from 0 to 1, |
| 1063 |
// so pos[i + 1] - pos[i] = 1/(colorCount-1) |
| 1064 |
SkScalar w; |
| 1065 |
if (!pos.empty()) { |
| 1066 |
// Match position fixing in SkGradientShader's constructor, clamping positions outside |
| 1067 |
// [0, 1] and forcing the sequence to be monotonic |
| 1068 |
SkScalar p0 = SkTPin(pos[i], 0.f, 1.f); |
| 1069 |
SkScalar p1 = SkTPin(pos[i + 1], p0, 1.f); |
| 1070 |
w = p1 - p0; |
| 1071 |
|
| 1072 |
// And account for any implicit intervals at the start or end of the positions |
| 1073 |
if (i == 0) { |
| 1074 |
if (p0 > 0.0f) { |
| 1075 |
// The first color is fixed between p = 0 to pos[0], so 0.5*(ci + cj)*(pj - pi) |
| 1076 |
// becomes 0.5*(c + c)*(pj - 0) = c * pj |
| 1077 |
auto c = skvx::float4::Load(&colors[0]); |
| 1078 |
blend += p0 * c; |
| 1079 |
} |
| 1080 |
} |
| 1081 |
if (i == colors.size() - 2) { |
| 1082 |
if (p1 < 1.f) { |
| 1083 |
// The last color is fixed between pos[n-1] to p = 1, so 0.5*(ci + cj)*(pj - pi) |
| 1084 |
// becomes 0.5*(c + c)*(1 - pi) = c * (1 - pi) |
| 1085 |
auto c = skvx::float4::Load(&colors.back()); |
| 1086 |
blend += (1.f - p1) * c; |
| 1087 |
} |
| 1088 |
} |
| 1089 |
} else { |
| 1090 |
w = 1.f / (colors.size() - 1); |
| 1091 |
} |
| 1092 |
|
| 1093 |
blend += 0.5f * w * (c1 + c0); |
| 1094 |
} |
| 1095 |
|
| 1096 |
SkColor4f avg; |
| 1097 |
blend.store(&avg); |
| 1098 |
return avg; |
| 1099 |
} |
| 1100 |
|
| 1101 |
// Except for special circumstances of clamped gradients, every gradient shape--when degenerate-- |
| 1102 |
// can be mapped to the same fallbacks. The specific shape factories must account for special |
| 1103 |
// clamped conditions separately, this will always return the last color for clamped gradients. |
| 1104 |
sk_sp<SkShader> SkGradientBaseShader::MakeDegenerateGradient(const SkGradient::Colors& c) { |
| 1105 |
switch (c.tileMode()) { |
| 1106 |
case SkTileMode::kDecal: |
| 1107 |
// normally this would reject the area outside of the interpolation region, so since |
| 1108 |
// inside region is empty when the radii are equal, the entire draw region is empty |
| 1109 |
return SkShaders::Empty(); |
| 1110 |
case SkTileMode::kRepeat: |
| 1111 |
case SkTileMode::kMirror: |
| 1112 |
// repeat and mirror are treated the same: the border colors are never visible, |
| 1113 |
// but approximate the final color as infinite repetitions of the colors, so |
| 1114 |
// it can be represented as the average color of the gradient. |
| 1115 |
return SkShaders::Color(average_gradient_color(c.colors(), c.positions()), |
| 1116 |
c.colorSpace()); |
| 1117 |
case SkTileMode::kClamp: |
| 1118 |
// Depending on how the gradient shape degenerates, there may be a more specialized |
| 1119 |
// fallback representation for the factories to use, but this is a reasonable default. |
| 1120 |
return SkShaders::Color(c.colors().back(), c.colorSpace()); |
| 1121 |
} |
| 1122 |
SkDEBUGFAIL("Should not be reached"); |
| 1123 |
return nullptr; |
| 1124 |
} |