Scoop API

scoop:scoop.ui.component:0.1.0

src/chart/pie.scoop

Selected production source · src/chart/pie.scoop

1package scoop.ui.component
3import scoop.graphics.*
4import scoop.math.*
6internal fun chartPie(plan: ChartPlan, size: Size): ChartGeometry {
7 val layout = ChartPolarLayout(plan, size)
8 val result = ArrayList<ChartSeriesGeometry>()
9 val input = plan.input
10 val count = plan.snapshot.data.datums.size
11 val band = (layout.radius - layout.hole) / lowerBound(plan.prepared.series.size.toDouble(), 1.0)
12 val start = chartAngle(input.startAngle)
13 val sweep = input.endAngle - input.startAngle
14 var ring = 0L
15 for (series in plan.prepared.series) {
16 // Scaling before summing preserves proportions when finite values have an overflowing sum.
17 var maximum = 0.0
18 for (sample in series.samples)
19 when (sample) {
20 case Some(val value) -> maximum = lowerBound(maximum, value.value);
21 case None -> {}
22 }
23 var total = 0.0
24 if (maximum > 0.0)
25 for (sample in series.samples)
26 when (sample) {
27 case Some(val value) -> total += value.value / maximum;
28 case None -> {}
29 }
30 val outer = layout.radius - ring.toDouble() * band
31 val gap =
32 if (plan.prepared.series.size > 1L)
33 upperBound(2.0 * plan.appearance.density, band * 0.1)
34 else
35 0.0
36 val inner = lowerBound(layout.hole, outer - band + gap)
37 var fraction = 0.0
38 val samples = ArrayList<ChartSample?>()
39 for (at in 0L ..< count) {
40 samples.add(
41 when (series.samples[at]) {
42 case None -> None
43 case Some(val value) -> {
44 if (total == 0.0 || value.value == 0.0 || outer <= inner)
45 None
46 else {
47 val weight = (value.value / maximum) / total
48 val arc =
49 ChartSector(
50 layout.center,
51 inner,
52 outer,
53 start + sweep * fraction,
54 sweep * weight,
55 chartSectorColor(plan, series, at),
56 4.0 * plan.appearance.density
57 )
58 fraction += weight
59 Some(
60 ChartSample(
61 chartPolarSelection(plan, series, at),
62 value.value,
63 chartPolarPoint(
64 layout.center,
65 (inner + outer) / 2.0,
66 arc.start + arc.sweep / 2.0
67 ),
68 layout.center,
69 ChartShape.Sector(arc),
70 arc.sweep != 0.0
71 )
72 )
73 }
74 }
75 }
76 )
77 }
78 result.add(ChartSeriesGeometry(series, samples.toArray()));
79 ring += 1L
80 }
81 return ChartGeometry(
82 size,
83 layout.plot,
84 result.toArray(),
85 [],
86 [],
87 ChartKind.Pie,
88 contentBounds = layout.content
89 )