xref: /webtrees/app/ColorGenerator.php (revision 76692c8b291f16d9251d67f27078779f6737fe7e)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2015 webtrees development team
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16namespace Fisharebest\Webtrees;
17
18/**
19 * Generate a range of colurs for the lifespan chart.
20 */
21class ColorGenerator {
22	/** @var int Current hue */
23	private $hue;
24
25	/** @var int Initial hue*/
26	private $basehue;
27
28	/** @var int Saturation */
29	private $saturation;
30
31	/** @var int Lightness */
32	private $lightness;
33
34	/** @var int Initial lightness*/
35	private $baselightness;
36
37	/** @var int Alpha transparancy */
38	private $alpha;
39
40	/** @var int Clockwise or anticlockwise color wheel */
41	private $range;
42
43	/**
44	 * Create a color generator.
45	 *
46	 * @param int $hue (0Deg = Red, 120Deg = green, 240Deg = blue)
47	 * @param int $saturation
48	 * @param int $lightness
49	 * @param int $alpha
50	 * @param int $range (sign determines direction. positive = clockwise, negative = anticlockwise)
51	 */
52	public function __construct($hue, $saturation, $lightness, $alpha, $range) {
53		$this->hue           = $hue;
54		$this->basehue       = $hue;
55		$this->saturation    = $saturation;
56		$this->lightness     = $lightness;
57		$this->baselightness = $lightness;
58		$this->alpha         = $alpha;
59		$this->range         = $range;
60	}
61
62	/**
63	 * Function getNextColor
64	 *
65	 * $lightness cycles between $baselightness and 100% in $lightnessStep steps
66	 * $hue cycles on each complete $lightness cycle
67	 * between $basehue and $basehue + $range degrees in $hueStep degrees
68	 *
69	 * @param int $lightnessStep
70	 * @param int $hueStep
71	 *
72	 * @return string
73	 */
74	public function getNextColor($lightnessStep = 10, $hueStep = 15) {
75		$lightness = $this->lightness + $lightnessStep;
76		$hue       = $this->hue;
77
78		if ($lightness >= 100) {
79			$lightness = $this->baselightness;
80			$hue += $hueStep * (abs($this->range) / $this->range);
81			if (($hue - $this->basehue) * ($hue - ($this->basehue + $this->range)) >= 0) {
82				$hue = $this->basehue;
83			}
84			$this->hue = $hue;
85		}
86		$this->lightness = $lightness;
87
88		return sprintf("hsla(%s, %s%%, %s%%, %s)",
89			$this->hue,
90			$this->saturation,
91			$this->lightness,
92			$this->alpha);
93	}
94
95}
96