Debian Codegraph @

src/com/github/weisj/jsvg/paint/impl/jdk/SVGRadialGradientPaintContext.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 /*
2 * MIT License
3 *
4 * Copyright (c) 2023-2025 Jannis Weis
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7 * associated documentation files (the "Software"), to deal in the Software without restriction,
8 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
9 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all copies or
13 * substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
16 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 *
21 */
22 package com.github.weisj.jsvg.paint.impl.jdk;
23
24 import java.awt.*;
25 import java.awt.geom.AffineTransform;
26
27 import org.jetbrains.annotations.NotNull;
28
29 /*
30 * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. DO NOT ALTER OR
31 * REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
32 *
33 * This code is free software; you can redistribute it and/or modify it under the terms of the GNU
34 * General Public License version 2 only, as published by the Free Software Foundation. Oracle
35 * designates this particular file as subject to the "Classpath" exception as provided by Oracle in
36 * the LICENSE file that accompanied this code.
37 *
38 * This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
39 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40 * General Public License version 2 for more details (a copy is included in the LICENSE file that
41 * accompanied this code).
42 *
43 * You should have received a copy of the GNU General Public License version 2 along with this work;
44 * if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
45 * 02110-1301 USA.
46 *
47 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or visit www.oracle.com
48 * if you need additional information or have any questions.
49 */
50
51 /**
52 * Provides the actual implementation for the RadialGradientPaint.
53 * This is where the pixel processing is done. A RadialGradientPaint
54 * only supports circular gradients, but it should be possible to scale
55 * the circle to look approximately elliptical, by means of a
56 * gradient transform passed into the RadialGradientPaint constructor.
57 *
58 * @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
59 */
60 final class SVGRadialGradientPaintContext extends SVGMultipleGradientPaintContext {
61
62 /** True when (focus == center) and (focus radius == 0). */
63 private final boolean isSimpleFocus;
64
65 /** True when (cycleMethod == NO_CYCLE). */
66 private final boolean isNonCyclic;
67
68 /** Variables representing center and focus points. */
69 private final float centerX;
70 private final float centerY;
71 private float focusX;
72 private float focusY;
73
74 /** Radius of the gradient circle an focus circle squared. */
75 private final float radiusSq;
76 private final float focusRadius;
77 private final float focusRadiusSq;
78
79 /** Constant part of X, Y user space coordinates. */
80 private final float constA;
81 private final float constB;
82
83 /** Constant second order delta for simple loop. */
84 private final float gDeltaDelta;
85
86 /**
87 * This value represents the solution when focusX == X. It is called
88 * trivial because it is easier to calculate than the general case.
89 */
90 private final float trivial;
91
92 /** Amount for offset when clamping focus. */
93 private static final float FOCUS_CLAMP_DOWNSCALE = .99f;
94
95 /**
96 * Constructor for RadialGradientPaintContext.
97 *
98 * @param paint the {@code RadialGradientPaint} from which this context
99 * is created
100 * @param t the {@code AffineTransform} from user
101 * space into device space (gradientTransform should be
102 * concatenated with this)
103 * @param cx the center X coordinate in user space of the circle defining
104 * the gradient. The last color of the gradient is mapped to
105 * the perimeter of this circle.
106 * @param cy the center Y coordinate in user space of the circle defining
107 * the gradient. The last color of the gradient is mapped to
108 * the perimeter of this circle.
109 * @param r the radius of the circle defining the extents of the
110 * color gradient
111 * @param fx the X coordinate in user space to which the first color
112 * is mapped
113 * @param fy the Y coordinate in user space to which the first color
114 * is mapped
115 * @param fractions the fractions specifying the gradient distribution
116 * @param colors the gradient colors
117 * @param cycleMethod either NO_CYCLE, REFLECT, or REPEAT
118 * @param colorSpace which colorspace to use for interpolation,
119 * either SRGB or LINEAR_RGB
120 */
121 SVGRadialGradientPaintContext(@NotNull SVGRadialGradientPaint paint, @NotNull AffineTransform t,
122 float cx, float cy, float r,
123 float fx, float fy, float fr,
124 float @NotNull [] fractions, @NotNull Color @NotNull [] colors,
125 MultipleGradientPaint.CycleMethod cycleMethod, MultipleGradientPaint.ColorSpaceType colorSpace) {
126 super(paint, t, fractions, colors, cycleMethod, colorSpace);
127
128 // copy some parameters
129 centerX = cx;
130 centerY = cy;
131 focusX = fx;
132 focusY = fy;
133 /* Radius of the outermost circle defining the 100% gradient stop. */
134
135 this.isSimpleFocus = (focusX == centerX) && (focusY == centerY) && (fr == 0);
136 this.isNonCyclic = (cycleMethod == MultipleGradientPaint.CycleMethod.NO_CYCLE);
137
138 // for use in the quadratic equation
139 radiusSq = r * r;
140 focusRadius = fr;
141 focusRadiusSq = fr * fr;
142
143 float dX = focusX - centerX;
144 float dY = focusY - centerY;
145
146 double distSq = (dX * dX) + (dY * dY);
147
148 // test if distance from focus to center is greater than the radius
149 if (distSq > radiusSq * FOCUS_CLAMP_DOWNSCALE) {
150 // clamp focus to radius
151 float scale = (float) Math.sqrt(radiusSq * FOCUS_CLAMP_DOWNSCALE / distSq);
152 dX = dX * scale;
153 dY = dY * scale;
154 focusX = centerX + dX;
155 focusY = centerY + dY;
156 }
157
158 // calculate the solution to be used in the case where X == focusX
159 // in cyclicCircularGradientFillRaster()
160 trivial = (float) Math.sqrt(radiusSq - (dX * dX));
161
162 // constant parts of X, Y user space coordinates
163 constA = a02 - centerX;
164 constB = a12 - centerY;
165
166 // constant second order delta for simple loop
167 gDeltaDelta = 2 * (a00 * a00 + a10 * a10) / radiusSq;
168 }
169
170 /**
171 * Return a Raster containing the colors generated for the graphics
172 * operation.
173 *
174 * @param x,y,w,h the area in device space for which colors are
175 * generated.
176 */
177 @Override
178 protected void fillRaster(int[] pixels, int off, int adjust,
179 int x, int y, int w, int h) {
180 if (isSimpleFocus && isNonCyclic && isSimpleLookup) {
181 simpleNonCyclicFillRaster(pixels, off, adjust, x, y, w, h);
182 } else {
183 cyclicCircularGradientFillRaster(pixels, off, adjust, x, y, w, h);
184 }
185 }
186
187 /**
188 * This code works in the simplest of cases, where the focus == center
189 * point, the gradient is non-cyclic, and the gradient lookup method is
190 * fast (single array index, no conversion necessary).
191 */
192 private void simpleNonCyclicFillRaster(int[] pixels, int off, int adjust, int x, int y, int w, int h) {
193 /*
194 * We calculate sqrt(X^2 + Y^2) relative to the radius size to get the fraction for the color to
195 * use.
196 *
197 * Each step along the scanline adds (a00, a10) to (X, Y). If we precalculate: gRel = X^2+Y^2 for
198 * the start of the row, then for each step we need to calculate: gRel' = (X+a00)^2 + (Y+a10)^2 =
199 * X^2 + 2*X*a00 + a00^2 + Y^2 + 2*Y*a10 + a10^2 = (X^2+Y^2) + 2*(X*a00+Y*a10) + (a00^2+a10^2) =
200 * gRel + 2*(X*a00+Y*a10) + (a00^2+a10^2) = gRel + 2*DP + SD (where DP = dot product between X,Y and
201 * a00,a10 and SD = dot product square of the delta vector) For the step after that we get: gRel'' =
202 * (X+2*a00)^2 + (Y+2*a10)^2 = X^2 + 4*X*a00 + 4*a00^2 + Y^2 + 4*Y*a10 + 4*a10^2 = (X^2+Y^2) +
203 * 4*(X*a00+Y*a10) + 4*(a00^2+a10^2) = gRel + 4*DP + 4*SD = gRel' + 2*DP + 3*SD The increment
204 * changed by: (gRel'' - gRel') - (gRel' - gRel) = (2*DP + 3*SD) - (2*DP + SD) = 2*SD Note that this
205 * value depends only on the (inverse of the) transformation matrix and so is a constant for the
206 * loop. To make this all relative to the unit circle, we need to divide all values as follows: [XY]
207 * /= radius gRel /= radiusSq DP /= radiusSq SD /= radiusSq
208 */
209 // coordinates of UL corner in "user space" relative to center
210 float rowX = (a00 * x) + (a01 * y) + constA;
211 float rowY = (a10 * x) + (a11 * y) + constB;
212
213 // second order delta calculated in constructor
214 float deltaDelta = this.gDeltaDelta;
215
216 // adjust is (scan-w) of pixels array, we need (scan)
217 adjust += w;
218
219 // rgb of the 1.0 color used when the distance exceeds gradient radius
220 int rgbclip = gradient[fastGradientArraySize];
221
222 for (int j = 0; j < h; j++) {
223 // these values depend on the coordinates of the start of the row
224 float gRel = (rowX * rowX + rowY * rowY) / radiusSq;
225 float gDelta = (2 * (a00 * rowX + a10 * rowY) / radiusSq +
226 deltaDelta / 2);
227
228 /*
229 * Use optimized loops for any cases where gRel >= 1. We do not need to calculate sqrt(gRel) for
230 * these values since sqrt(N>=1) == (M>=1). Note that gRel follows a parabola which can only be < 1
231 * for a small region around the center on each scanline. In particular: gDeltaDelta is always
232 * positive gDelta is <0 until it crosses the midpoint, then >0 To the left and right of that
233 * region, it will always be >=1 out to infinity, so we can process the line in 3 regions: out to
234 * the left - quick fill until gRel < 1, updating gRel in the heart - slow fraction=sqrt fill while
235 * gRel < 1 out to the right - quick fill rest of scanline, ignore gRel
236 */
237 int i = 0;
238 // Quick fill for "out to the left"
239 while (i < w && gRel >= 1.0f) {
240 pixels[off + i] = rgbclip;
241 gRel += gDelta;
242 gDelta += deltaDelta;
243 i++;
244 }
245 // Slow fill for "in the heart"
246 while (i < w && gRel < 1.0f) {
247 int gIndex;
248
249 if (gRel <= 0) {
250 gIndex = 0;
251 } else {
252 float fIndex = gRel * SQRT_LUT_SIZE;
253 int iIndex = (int) fIndex;
254 float s0 = sqrtLookup[iIndex];
255 float s1 = sqrtLookup[iIndex + 1] - s0;
256 fIndex = s0 + (fIndex - iIndex) * s1;
257 gIndex = (int) (fIndex * fastGradientArraySize);
258 }
259
260 // store the color at this point
261 pixels[off + i] = gradient[gIndex];
262
263 // incremental calculation
264 gRel += gDelta;
265 gDelta += deltaDelta;
266 i++;
267 }
268 // Quick fill to end of line for "out to the right"
269 while (i < w) {
270 pixels[off + i] = rgbclip;
271 i++;
272 }
273
274 off += adjust;
275 rowX += a01;
276 rowY += a11;
277 }
278 }
279
280 // SQRT_LUT_SIZE must be a power of 2 for the test above to work.
281 private static final int SQRT_LUT_SIZE = (1 << 11);
282 private static final float[] sqrtLookup = new float[SQRT_LUT_SIZE + 1];
283 static {
284 for (int i = 0; i < sqrtLookup.length; i++) {
285 sqrtLookup[i] = (float) Math.sqrt(i / ((float) SQRT_LUT_SIZE));
286 }
287 }
288
289 /**
290 * Fill the raster, cycling the gradient colors when a point falls outside
291 * the perimeter of the 100% stop circle.
292 * <p>
293 * This calculation first computes the intersection point of the line
294 * from the focus through the current point in the raster, and the
295 * perimeter of the gradient circle.
296 * <p>
297 * Then it determines the percentage distance of the current point along
298 * that line (focus is 0%, perimeter is 100%).
299 * <p>
300 * Equation of a circle centered at (a,b) with radius r:
301 * (x-a)^2 + (y-b)^2 = r^2
302 * Equation of a line with slope m and y-intercept b:
303 * y = mx + b
304 * Replacing y in the circle equation and solving using the quadratic
305 * formula produces the following set of equations. Constant factors have
306 * been extracted out of the inner loop.
307 */
308 private void cyclicCircularGradientFillRaster(int[] pixels, int off, int adjust, int x, int y, int w, int h) {
309 // constant part of the C factor of the quadratic equation
310 final double constC = -radiusSq + (centerX * centerX) + (centerY * centerY);
311
312 // constant parts of X, Y coordinates
313 final float constX = (a00 * x) + (a01 * y) + a02;
314 final float constY = (a10 * x) + (a11 * y) + a12;
315
316 // constants in inner loop quadratic formula
317 final float precalc2 = 2 * centerY;
318 final float precalc3 = -2 * centerX;
319
320 // used to index pixels array
321 int indexer = off;
322
323 // incremental index change for pixels array
324 final int pixInc = w + adjust;
325
326 // for every row
327 for (int j = 0; j < h; j++) {
328
329 // user space point; these are constant from column to column
330 float userX = (a01 * j) + constX;
331 float userY = (a11 * j) + constY;
332
333 // for every column (inner loop begins here)
334 for (int i = 0; i < w; i++) {
335
336 // intersection with circle X,Y coordinate
337 double solutionX;
338 double solutionY;
339 if (userX == focusX) {
340 // special case to avoid divide by zero
341 solutionX = focusX;
342 solutionY = centerY;
343 solutionY += (userY > focusY) ? trivial : -trivial;
344 } else {
345 // slope and y-intercept of the focus-perimeter line
346 float slope = (userY - focusY) / (userX - focusX);
347 float yIntercept = userY - (slope * userX);
348
349 // use the quadratic formula to calculate the
350 // intersection point
351 double a = (slope * slope) + 1;
352 double b = precalc3 + (-2 * slope * (centerY - yIntercept));
353 double c = constC + (yIntercept * (yIntercept - precalc2));
354
355 // determinant of quadratic formula (should always be > 0)
356 float det = (float) Math.sqrt((b * b) - (4 * a * c));
357 solutionX = -b;
358
359 // choose the positive or negative root depending
360 // on where the X coord lies with respect to the focus
361 solutionX += (userX < focusX) ? -det : det;
362 solutionX = solutionX / (2 * a); // divisor
363 solutionY = (slope * solutionX) + yIntercept;
364 }
365
366 int colorAtPoint = getColorAtPoint(userX, userY, (float) solutionX, (float) solutionY);
367
368 // store the color at this point
369 pixels[indexer + i] = colorAtPoint;
370
371 // incremental change in X, Y
372 userX += a00;
373 userY += a10;
374 } // end inner loop
375
376 indexer += pixInc;
377 } // end outer loop
378 }
379
380 private int getColorAtPoint(float userX, float userY, float solutionX, float solutionY) {
381 float currentToFocusSq = getCurrentToFocusSq(userX, userY);
382 if (currentToFocusSq <= focusRadiusSq) {
383 // If we are inside the focus circle use the first color stop.
384 return indexIntoGradientsArrays(0);
385 } else {
386 return getColorAtPointOutsideFocusCircle(solutionX, solutionY, currentToFocusSq);
387 }
388 }
389
390 private float getCurrentToFocusSq(float x, float y) {
391 float deltaXSq = x - focusX;
392 deltaXSq = deltaXSq * deltaXSq;
393
394 float deltaYSq = y - focusY;
395 deltaYSq = deltaYSq * deltaYSq;
396
397 // sq distance from the current point to focus
398 return deltaXSq + deltaYSq;
399 }
400
401 private int getColorAtPointOutsideFocusCircle(float solutionX, float solutionY, float currentToFocusSq) {
402 // Otherwise remap the interval (0-1) which usually span from the focus to the circle boundary
403 // to the line from the outside of the focus circle to the outside.
404 float intersectToFocusSq = getCurrentToFocusSq(solutionX, solutionY);
405
406 float gradientPosition = computeGradientPosition(currentToFocusSq, intersectToFocusSq);
407 return indexIntoGradientsArrays(gradientPosition);
408 }
409
410 private float computeGradientPosition(float currentToFocusSq, float intersectToFocusSq) {
411 // get the percentage (0-1) of the current point along the focus-circumference line
412 // Adjust for the focus radius
413 float gradientPosition;
414 if (focusRadius > 0) {
415 float currentToFocus = (float) Math.sqrt(currentToFocusSq);
416 float intersectToFocus = (float) Math.sqrt(intersectToFocusSq);
417 gradientPosition = (currentToFocus - focusRadius) / (intersectToFocus - focusRadius);
418 } else {
419 gradientPosition = (float) Math.sqrt(currentToFocusSq / intersectToFocusSq);
420 }
421 return gradientPosition;
422 }
423 }