Debian Codegraph @

src/com/github/weisj/jsvg/paint/impl/jdk/SVGMultipleGradientPaintContext.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 import java.awt.geom.NoninvertibleTransformException;
27 import java.awt.image.ColorModel;
28 import java.awt.image.DataBufferInt;
29 import java.awt.image.DirectColorModel;
30 import java.awt.image.Raster;
31 import java.awt.image.SinglePixelPackedSampleModel;
32 import java.lang.ref.SoftReference;
33 import java.lang.ref.WeakReference;
34 import java.util.Objects;
35
36 import org.jetbrains.annotations.NotNull;
37
38 import com.github.weisj.jsvg.util.ColorUtil;
39
40 /*
41 * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. DO NOT ALTER OR
42 * REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
43 *
44 * This code is free software; you can redistribute it and/or modify it under the terms of the GNU
45 * General Public License version 2 only, as published by the Free Software Foundation. Oracle
46 * designates this particular file as subject to the "Classpath" exception as provided by Oracle in
47 * the LICENSE file that accompanied this code.
48 *
49 * This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
50 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
51 * General Public License version 2 for more details (a copy is included in the LICENSE file that
52 * accompanied this code).
53 *
54 * You should have received a copy of the GNU General Public License version 2 along with this work
55 * if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
56 * 02110-1301 USA.
57 *
58 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA or visit www.oracle.com
59 * if you need additional information or have any questions.
60 */
61
62 /**
63 * This is the superclass for all PaintContexts which use a multiple color
64 * gradient to fill in their raster. It provides the actual color
65 * interpolation functionality. Subclasses only have to deal with using
66 * the gradient to fill pixels in a raster.
67 *
68 * @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans
69 */
70 abstract class SVGMultipleGradientPaintContext implements PaintContext {
71
72 private static final float MIN_INTERVAL_LENGTH = 0.001f;
73
74 /**
75 * The PaintContext's ColorModel. This is ARGB if colors are not all
76 * opaque, otherwise it is RGB.
77 */
78 protected ColorModel model;
79
80 /**
81 * Color model used if gradient colors are all opaque.
82 */
83 private static final ColorModel XRGB_MODEL =
84 new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
85
86 /**
87 * The cached ColorModel.
88 */
89 protected static ColorModel cachedModel;
90
91 /**
92 * The cached raster, which is reusable among instances.
93 */
94 protected static WeakReference<Raster> cached;
95
96 /**
97 * Raster is reused whenever possible.
98 */
99 protected Raster saved;
100
101 /**
102 * The method to use when painting out of the gradient bounds.
103 */
104 protected MultipleGradientPaint.CycleMethod cycleMethod;
105
106 /**
107 * The ColorSpace in which to perform the interpolation
108 */
109 protected MultipleGradientPaint.ColorSpaceType colorSpace;
110
111 /**
112 * Elements of the inverse transform matrix.
113 */
114 protected float a00;
115 protected float a01;
116 protected float a10;
117 protected float a11;
118 protected float a02;
119 protected float a12;
120
121 /**
122 * This boolean specifies whether we are in simple lookup mode, where an
123 * input value between 0 and 1 may be used to directly index into a single
124 * array of gradient colors. If this boolean value is false, then we have
125 * to use a 2-step process where we have to determine which gradient array
126 * we fall into, then determine the index into that array.
127 */
128 protected boolean isSimpleLookup;
129
130 /**
131 * Size of gradients array for scaling the 0-1 index when looking up
132 * colors the fast way.
133 */
134 protected int fastGradientArraySize;
135
136 /**
137 * Array which contains the interpolated color values for each interval,
138 * used by calculateSingleArrayGradient(). It is protected for possible
139 * direct access by subclasses.
140 */
141 protected int[] gradient;
142
143 /**
144 * Array of gradient arrays, one array for each interval. Used by
145 * calculateMultipleArrayGradient().
146 */
147 private int[][] gradients;
148
149 /**
150 * Normalized intervals array.
151 */
152 private float[] normalizedIntervals;
153
154 /**
155 * Fractions array.
156 */
157 private final float[] fractions;
158
159 /**
160 * Used to determine if gradient colors are all opaque.
161 */
162 private int transparencyTest;
163
164 /**
165 * Constant number of max colors between any 2 arbitrary colors.
166 * Used for creating and indexing gradients arrays.
167 */
168 protected static final int GRADIENT_SIZE = 256;
169 protected static final int GRADIENT_SIZE_INDEX = GRADIENT_SIZE - 1;
170
171 /**
172 * Maximum length of the fast single-array. If the estimated array size
173 * is greater than this, switch over to the slow lookup method.
174 * No particular reason for choosing this number, but it seems to provide
175 * satisfactory performance for the common case (fast lookup).
176 */
177 private static final int MAX_GRADIENT_ARRAY_SIZE = 5000;
178
179 /**
180 * Constructor for MultipleGradientPaintContext superclass.
181 */
182 protected SVGMultipleGradientPaintContext(@NotNull SVGMultipleGradientPaint mgp,
183 @NotNull AffineTransform t, float @NotNull [] fractions, @NotNull Color @NotNull [] colors,
184 MultipleGradientPaint.CycleMethod cycleMethod, MultipleGradientPaint.ColorSpaceType colorSpace) {
185 // The inverse transform is needed to go from device to user space.
186 // Get all the components of the inverse transform matrix.
187 AffineTransform tInv;
188 try {
189 // the following assumes that the caller has copied the incoming
190 // transform and is not concerned about it being modified
191 t.invert();
192 tInv = t;
193 } catch (NoninvertibleTransformException e) {
194 // just use identity transform in this case; better to show
195 // (incorrect) results than to throw an exception and/or no-op
196 tInv = new AffineTransform();
197 }
198 double[] m = new double[6];
199 tInv.getMatrix(m);
200 a00 = (float) m[0];
201 a10 = (float) m[1];
202 a01 = (float) m[2];
203 a11 = (float) m[3];
204 a02 = (float) m[4];
205 a12 = (float) m[5];
206
207 // copy some flags
208 this.cycleMethod = cycleMethod;
209 this.colorSpace = colorSpace;
210
211 // we can avoid copying this array since we do not modify its values
212 this.fractions = fractions;
213
214 // note that only one of these values can ever be non-null (we either
215 // store the fast gradient array or the slow one, but never both
216 // at the same time)
217 int[] grad =
218 (mgp.gradient != null) ? mgp.gradient.get() : null;
219 int[][] grads =
220 (mgp.gradients != null) ? mgp.gradients.get() : null;
221
222 if (grad == null && grads == null) {
223 // we need to (re)create the appropriate values
224 calculateLookupData(colors);
225
226 // now cache the calculated values in the
227 // MultipleGradientPaint instance for future use
228 mgp.model = this.model;
229 mgp.normalizedIntervals = this.normalizedIntervals;
230 mgp.isSimpleLookup = this.isSimpleLookup;
231 if (isSimpleLookup) {
232 // only cache the fast array
233 mgp.fastGradientArraySize = this.fastGradientArraySize;
234 mgp.gradient = new SoftReference<>(this.gradient);
235 } else {
236 // only cache the slow array
237 mgp.gradients = new SoftReference<>(this.gradients);
238 }
239 } else {
240 // use the values cached in the MultipleGradientPaint instance
241 this.model = mgp.model;
242 this.normalizedIntervals = mgp.normalizedIntervals;
243 this.isSimpleLookup = mgp.isSimpleLookup;
244 this.gradient = grad;
245 this.fastGradientArraySize = mgp.fastGradientArraySize;
246 this.gradients = grads;
247 }
248 }
249
250 /**
251 * This function is the meat of this class. It calculates an array of
252 * gradient colors based on an array of fractions and color values at
253 * those fractions.
254 */
255 private void calculateLookupData(Color[] colors) {
256 Color[] normalizedColors;
257 if (colorSpace == MultipleGradientPaint.ColorSpaceType.LINEAR_RGB) {
258 // create a new colors array
259 normalizedColors = new Color[colors.length];
260 // convert the colors using the lookup table
261 for (int i = 0; i < colors.length; i++) {
262 int argb = colors[i].getRGB();
263 normalizedColors[i] = new Color(ColorUtil.sRGBtoLinearRGB(argb), true);
264 }
265 } else {
266 // we can just use this array by reference since we do not
267 // modify its values in the case of SRGB
268 normalizedColors = colors;
269 }
270
271 // this will store the intervals (distances) between gradient stops
272 normalizedIntervals = new float[fractions.length - 1];
273
274 // convert from fractions into intervals
275 for (int i = 0; i < normalizedIntervals.length; i++) {
276 // interval distance is equal to the difference in positions
277 normalizedIntervals[i] = this.fractions[i + 1] - this.fractions[i];
278 }
279
280 // initialize to be fully opaque for ANDing with colors
281 transparencyTest = 0xff000000;
282
283 // array of interpolation arrays
284 gradients = new int[normalizedIntervals.length][];
285
286 // find smallest interval
287 float minInterval = 1;
288 for (float interval : normalizedIntervals) {
289 if (interval > MIN_INTERVAL_LENGTH) {
290 minInterval = Math.min(minInterval, interval);
291 }
292 }
293
294 // Estimate the size of the entire gradients array.
295 // This is to prevent a tiny interval from causing the size of array
296 // to explode. If the estimated size is too large, break to using
297 // separate arrays for each interval, and using an indexing scheme at
298 // look-up time.
299 int estimatedSize = 0;
300 for (float normalizedInterval : normalizedIntervals) {
301 estimatedSize += (int) ((normalizedInterval / minInterval) * GRADIENT_SIZE);
302 }
303
304 if (estimatedSize > MAX_GRADIENT_ARRAY_SIZE) {
305 // slow method
306 calculateMultipleArrayGradient(normalizedColors);
307 } else {
308 // fast method
309 calculateSingleArrayGradient(normalizedColors, minInterval);
310 }
311
312 // use the most "economical" model
313 if ((transparencyTest >>> 24) == 0xff) {
314 model = XRGB_MODEL;
315 } else {
316 model = ColorModel.getRGBdefault();
317 }
318 }
319
320 /**
321 * FAST LOOKUP METHOD
322 * <p>
323 * This method calculates the gradient color values and places them in a
324 * single int array, gradient[]. It does this by allocating space for
325 * each interval based on its size relative to the smallest interval in
326 * the array. The smallest interval is allocated 255 interpolated values
327 * (the maximum number of unique in-between colors in a 24 bit color
328 * system), and all other intervals are allocated
329 * size = (255 * the ratio of their size to the smallest interval).
330 * <p>
331 * This scheme expedites a speedy retrieval because the colors are
332 * distributed along the array according to their user-specified
333 * distribution. All that is needed is a relative index from 0 to 1.
334 * <p>
335 * The only problem with this method is that the possibility exists for
336 * the array size to balloon in the case where there is a
337 * disproportionately small gradient interval. In this case the other
338 * intervals will be allocated huge space, but much of that data is
339 * redundant. We thus need to use the space conserving scheme below.
340 *
341 * @param minInterval the size of the smallest interval
342 */
343 private void calculateSingleArrayGradient(Color[] colors, float minInterval) {
344 // set the flag, so we know later it is a simple (fast) lookup
345 isSimpleLookup = true;
346
347 // 2 colors to interpolate
348 int rgb1;
349 int rgb2;
350
351 // the eventual size of the single array
352 int gradientsTot = 1;
353
354 // for every interval (transition between 2 colors)
355 for (int i = 0; i < gradients.length; i++) {
356 // create an array whose size is based on the ratio to the
357 // smallest interval
358 int nGradients = (int) ((normalizedIntervals[i] / minInterval) * 255f);
359 gradientsTot += nGradients;
360 gradients[i] = new int[nGradients];
361
362 // the 2 colors (keyframes) to interpolate between
363 rgb1 = colors[i].getRGB();
364 rgb2 = colors[i + 1].getRGB();
365
366 // fill this array with the colors in between rgb1 and rgb2
367 interpolate(rgb1, rgb2, gradients[i]);
368
369 // if the colors are opaque, transparency should still
370 // be 0xff000000
371 transparencyTest &= rgb1;
372 transparencyTest &= rgb2;
373 }
374
375 // put all gradients in a single array
376 gradient = new int[gradientsTot];
377 int curOffset = 0;
378 for (int[] ints : gradients) {
379 System.arraycopy(ints, 0, gradient, curOffset, ints.length);
380 curOffset += ints.length;
381 }
382 gradient[gradient.length - 1] = colors[colors.length - 1].getRGB();
383
384 // if interpolation occurred in Linear RGB space, convert the
385 // gradients back to sRGB using the lookup table
386 if (colorSpace == MultipleGradientPaint.ColorSpaceType.LINEAR_RGB) {
387 for (int i = 0; i < gradient.length; i++) {
388 gradient[i] = ColorUtil.linearRGBtoSRGB(gradient[i]);
389 }
390 }
391
392 fastGradientArraySize = gradient.length - 1;
393 }
394
395 /**
396 * SLOW LOOKUP METHOD
397 * <p>
398 * This method calculates the gradient color values for each interval and
399 * places each into its own 255 size array. The arrays are stored in
400 * gradients[][]. (255 is used because this is the maximum number of
401 * unique colors between 2 arbitrary colors in a 24 bit color system.)
402 * <p>
403 * This method uses the minimum amount of space (only 255 * number of
404 * intervals), but it aggravates the lookup procedure, because now we
405 * have to find out which interval to select, then calculate the index
406 * within that interval. This causes a significant performance hit,
407 * because it requires this calculation be done for every point in
408 * the rendering loop.
409 * <p>
410 * For those of you who are interested, this is a classic example of the
411 * time-space tradeoff.
412 */
413 private void calculateMultipleArrayGradient(Color[] colors) {
414 // set the flag, so we know later it is a non-simple lookup
415 isSimpleLookup = false;
416
417 // 2 colors to interpolate
418 int rgb1;
419 int rgb2;
420
421 // for every interval (transition between 2 colors)
422 for (int i = 0; i < gradients.length; i++) {
423 // create an array of the maximum theoretical size for
424 // each interval
425 gradients[i] = new int[GRADIENT_SIZE];
426
427 // get the 2 colors
428 rgb1 = colors[i].getRGB();
429 rgb2 = colors[i + 1].getRGB();
430
431 // fill this array with the colors in between rgb1 and rgb2
432 interpolate(rgb1, rgb2, gradients[i]);
433
434 // if the colors are opaque, transparency should still
435 // be 0xff000000
436 transparencyTest &= rgb1;
437 transparencyTest &= rgb2;
438 }
439
440 // if interpolation occurred in Linear RGB space, convert the
441 // gradients back to SRGB using the lookup table
442 if (colorSpace == MultipleGradientPaint.ColorSpaceType.LINEAR_RGB) {
443 for (int j = 0; j < gradients.length; j++) {
444 for (int i = 0; i < gradients[j].length; i++) {
445 gradients[j][i] = ColorUtil.linearRGBtoSRGB(gradients[j][i]);
446 }
447 }
448 }
449 }
450
451 /**
452 * Yet another helper function. This one linearly interpolates between
453 * 2 colors, filling up the output array.
454 *
455 * @param rgb1 the start color
456 * @param rgb2 the end color
457 * @param output the output array of colors; must not be null
458 */
459 private void interpolate(int rgb1, int rgb2, int[] output) {
460 // step between interpolated values
461 float stepSize = 1.0f / output.length;
462
463 // extract color components from packed integer
464 int a1 = (rgb1 >> 24) & 0xff;
465 int r1 = (rgb1 >> 16) & 0xff;
466 int g1 = (rgb1 >> 8) & 0xff;
467 int b1 = rgb1 & 0xff;
468
469 // calculate the total change in alpha, red, green, blue
470 int da = ((rgb2 >> 24) & 0xff) - a1;
471 int dr = ((rgb2 >> 16) & 0xff) - r1;
472 int dg = ((rgb2 >> 8) & 0xff) - g1;
473 int db = (rgb2 & 0xff) - b1;
474
475 // for each step in the interval calculate the in-between color by
476 // multiplying the normalized current position by the total color
477 // change (0.5 is added to prevent truncation round-off error)
478 for (int i = 0; i < output.length; i++) {
479 output[i] = ((int) ((a1 + i * da * stepSize) + 0.5) << 24) |
480 ((int) ((r1 + i * dr * stepSize) + 0.5) << 16) |
481 ((int) ((g1 + i * dg * stepSize) + 0.5) << 8) |
482 ((int) ((b1 + i * db * stepSize) + 0.5));
483 }
484 }
485
486 private static float mod1(float x) {
487 float result = x - (int) x;
488 if (result < 0) {
489 result += 1;
490 }
491 return result;
492 }
493
494 private static float mod1Reflect(float x) {
495 float result = Math.abs(x);
496 int part = (int) x;
497 result = result - part;
498 if (part % 2 == 1) {
499 // integer part is odd, get reflected color instead
500 result = 1 - result;
501 }
502 return result;
503 }
504
505 /**
506 * Helper function to index into the gradients array. This is necessary
507 * because each interval has an array of colors with uniform size 255.
508 * However, the color intervals are not necessarily of uniform length, so
509 * a conversion is required.
510 *
511 * @param position the unmanipulated position, which will be mapped
512 * into the range 0 to 1
513 * @return integer color to display
514 */
515 protected final int indexIntoGradientsArrays(float position) {
516 // first, manipulate position value depending on the cycle method
517 if (cycleMethod == MultipleGradientPaint.CycleMethod.NO_CYCLE) {
518 position = Math.min(1, Math.max(0, position));
519 } else if (cycleMethod == MultipleGradientPaint.CycleMethod.REPEAT) {
520 // get the fractional part
521 position = mod1(position);
522 } else { // cycleMethod == CycleMethod.REFLECT
523 position = mod1Reflect(position);
524 }
525
526 // now, get the color based on this 0-1 position...
527
528 if (isSimpleLookup) {
529 // easy to compute: just scale index by array size
530 return gradient[(int) (position * fastGradientArraySize)];
531 } else {
532 // more complicated computation, to save space
533
534 // for all the gradient interval arrays
535 for (int i = 0; i < gradients.length; i++) {
536 if (position < fractions[i + 1]) {
537 // this is the array we want
538 float delta = position - fractions[i];
539
540 // this is the interval we want
541 int index = (int) ((delta / normalizedIntervals[i]) * GRADIENT_SIZE_INDEX);
542
543 return gradients[i][index];
544 }
545 }
546 }
547
548 return gradients[gradients.length - 1][GRADIENT_SIZE_INDEX];
549 }
550
551 @Override
552 public final Raster getRaster(int x, int y, int w, int h) {
553 // If working raster is big enough, reuse it. Otherwise,
554 // build a large enough new one.
555 Raster raster = saved;
556 if (raster == null || raster.getWidth() < w || raster.getHeight() < h) {
557 raster = getCachedRaster(model, w, h);
558 saved = raster;
559 }
560
561 // Access raster internal int array. Because we use a DirectColorModel,
562 // we know the DataBuffer is of type DataBufferInt and the SampleModel
563 // is SinglePixelPackedSampleModel.
564 // Adjust for initial offset in DataBuffer and also for the scanline
565 // stride.
566 // These calls make the DataBuffer non-acceleratable, but the
567 // Raster is never Stable long enough to accelerate anyway...
568 DataBufferInt rasterDB = (DataBufferInt) raster.getDataBuffer();
569 int[] pixels = rasterDB.getData(0);
570 int off = rasterDB.getOffset();
571 int scanlineStride = ((SinglePixelPackedSampleModel) raster.getSampleModel()).getScanlineStride();
572 int adjust = scanlineStride - w;
573
574 fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass
575
576 return raster;
577 }
578
579 protected abstract void fillRaster(int[] pixels, int off, int adjust, int x, int y, int w, int h);
580
581
582 /**
583 * Took this cacheRaster code from GradientPaint. It appears to recycle
584 * rasters for use by any other instance, as long as they are sufficiently
585 * large.
586 */
587 private static synchronized Raster getCachedRaster(ColorModel cm, int w, int h) {
588 if (Objects.equals(cm, cachedModel) && cached != null) {
589 Raster ras = cached.get();
590 if (ras != null && ras.getWidth() >= w && ras.getHeight() >= h) {
591 cached = null;
592 return ras;
593 }
594 }
595
596 return cm.createCompatibleWritableRaster(w, h);
597 }
598
599 /**
600 * Took this cacheRaster code from GradientPaint. It appears to recycle
601 * rasters for use by any other instance, as long as they are sufficiently
602 * large.
603 */
604 private static synchronized void putCachedRaster(ColorModel cm, Raster ras) {
605 if (cached != null) {
606 Raster cras = cached.get();
607 if (cras != null) {
608 int cw = cras.getWidth();
609 int ch = cras.getHeight();
610 int iw = ras.getWidth();
611 int ih = ras.getHeight();
612 if (cw >= iw && ch >= ih) {
613 return;
614 }
615 if (cw * ch >= iw * ih) {
616 return;
617 }
618 }
619 }
620 cachedModel = cm;
621 cached = new WeakReference<>(ras);
622 }
623
624 @Override
625 public final void dispose() {
626 if (saved != null) {
627 putCachedRaster(model, saved);
628 saved = null;
629 }
630 }
631
632 @Override
633 public final ColorModel getColorModel() {
634 return model;
635 }
636 }