chart: 9 новых типов диаграмм (scatter/bubble/radar/stock/ofPie/surface2D/bar3D/area3D/line3D)
PR checks / web (pull_request) Successful in 55s
PR checks / java (pull_request) Successful in 1m6s
Main: tests, deploy, autotests / web (push) Successful in 32s
Main: tests, deploy, autotests / images-web (push) Successful in 35s
Main: tests, deploy, autotests / java (push) Successful in 2m17s
Main: tests, deploy, autotests / images-app (push) Successful in 31s
Main: tests, deploy, autotests / deploy (push) Successful in 1m46s
Main: tests, deploy, autotests / autotests (push) Successful in 52s
Main: tests, deploy, autotests / rollback (push) Has been skipped

- ChartSpec: enum +9 типов, readGroup 9 веток, два c:valAx для scatter/bubble
  (X — первый), автозаголовок OF_PIE как у круговых
- ChartRenderer: диспетчер + легенда высотных полос для SURFACE
- Пейнтеры: ScatterPainter, RadarPainter, StockPainter, OfPiePainter,
  Surface2dPainter, Cartesian3dPainter (камера Surface3dPainter.project)
- Фикстура samples/chart-types.docx (ChartTypesDocxGenerator, chart-XML
  литералами) + регрессия WordPdfConverterTest#chartTypes_allTypesRenderAsImages
- docs/standards: полные наборы XSD strict/transitional + validate-fixtures.py;
  все 13 фикстур валидны по ECMA-376 (битые атрибуты в старых фикстурах
  исправлены в генераторе и пересозданных .docx)
- AGENTS.md/README обновлены
This commit was merged in pull request #42.
This commit is contained in:
Pjandro
2026-10-25 02:13:28 +00:00
parent 6ab732b1b4
commit fbdada1fda
81 changed files with 33512 additions and 87 deletions
@@ -0,0 +1,425 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Объёмные декартовы графики: c:bar3DChart, c:line3DChart, c:area3DChart
* (ECMA-376 §21.2.2.19/.101/.122). Камера — та же, что у поверхности
* ({@link Surface3dPainter#project}): u — категория (ширина), v — ряд
* (глубина), w — значение (высота); вписка равномерным масштабом в поля
* {@link Surface3dPainter#GUTTER_LEFT} и т.д.
*
* bar3D: кластерные колонки — ряды уходят в глубину (ширина полосы
* c:gapWidth, ширина колонки — полоса·(1−max(0,c:overlap))/nSer); торец
* затемняется (псевдо-свет, калибровка — Cartesian3dPainterTest).
* line3D: полилиния ряда на своей глубине, лента-толщина не имитируется;
* area3D: стена ряда от пола до значений, полупрозрачная, как AREA.
* Ограничения: c:shape (cylinder/cone/pyramid…) рисуется как box;
* c:barDir="bar" — горизонтальная ориентация тех же боксов.
*
* Регрессия — Cartesian3dPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
final class Cartesian3dPainter {
private Cartesian3dPainter() {
}
/** Линия/область рисуется только из двух и более точек (как у CartesianPainter). */
private static final int MIN_POLYLINE_POINTS = 2;
/** Вписка модельно-экранных координат в box (как у Surface3dPainter). */
private record Fit(double scale, double offX, double offY) {
}
/** Одна 3D-колонка: 8 спроецированных углов + цвет + глубина центра. */
private record Column(Surface3dPainter.Node center,
Surface3dPainter.Node[][][] corners, Color color) {
}
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
int nSer = spec.series.size();
int nCat = 0;
for (ChartSpec.Series s : spec.series) {
nCat = Math.max(nCat, s.values.size());
}
if (nSer == 0 || nCat == 0) {
return;
}
ChartSpec.AxisSpec valAxis = spec.valAxis != null
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null
? spec.catAxis : new ChartSpec.AxisSpec();
double[] range = ChartRenderer.valueRange(spec);
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1]);
double lo = bounds[0];
double hi = bounds[1];
double unit = bounds[2];
double span = Math.max(1e-9, hi - lo);
double rotX = Math.toRadians(spec.rotX);
double rotY = -Math.toRadians(spec.rotY);
double persp = spec.perspective;
double leftGutter = Surface3dPainter.GUTTER_LEFT * box.getWidth();
double rightGutter = Surface3dPainter.GUTTER_RIGHT * box.getWidth();
double topGutter = Surface3dPainter.GUTTER_TOP * box.getHeight();
double bottomGutter = Surface3dPainter.GUTTER_BOTTOM * box.getHeight();
double availW = Math.max(10, box.getWidth() - leftGutter - rightGutter);
double availH = Math.max(10, box.getHeight() - topGutter - bottomGutter);
double depthScale = Surface3dPainter.DEPTH_RATIO * Math.max(0.05,
spec.depthPercent / 100.0);
double heightScale = Surface3dPainter.HEIGHT_RATIO * availH / availW;
double floorW = -0.5 * heightScale;
boolean bar3d = spec.type == ChartSpec.Type.BAR3D;
boolean horizontal = bar3d && spec.bar3dHorizontal;
List<Surface3dPainter.Node> nodes = new ArrayList<>();
Surface3dPainter.Node[] floor = {
proj(-0.5, -0.5, floorW, rotX, rotY, depthScale, persp),
proj(0.5, -0.5, floorW, rotX, rotY, depthScale, persp),
proj(0.5, 0.5, floorW, rotX, rotY, depthScale, persp),
proj(-0.5, 0.5, floorW, rotX, rotY, depthScale, persp),
};
List<Double> tickValues = new ArrayList<>();
List<Surface3dPainter.Node> valueAnchors = new ArrayList<>();
for (double v = lo; v <= hi + unit / 2; v += unit) {
tickValues.add(v);
valueAnchors.add(horizontal
? proj(uVal(v, lo, span), -0.5, floorW, rotX, rotY, depthScale, persp)
: proj(-0.5, -0.5, wOf(v, lo, span, heightScale),
rotX, rotY, depthScale, persp));
}
List<Column> columns = new ArrayList<>();
double bw = 1.0 / nCat * 100.0 / (100.0 + spec.gapWidth);
double colW = bw * (100.0 - Math.max(0, spec.overlap)) / 100.0 / Math.max(1, nSer);
for (int si = 0; si < nSer; si++) {
ChartSpec.Series s = spec.series.get(si);
double v = vOf(si, nSer);
for (int c = 0; c < nCat; c++) {
Double val = c < s.values.size() ? s.values.get(c) : null;
if (val == null) {
continue;
}
if (bar3d) {
columns.add(makeColumn(s.fillAt(si, palette), c,
si - (nSer - 1) / 2.0, nCat, val, lo, span, heightScale,
floorW, bw, colW, horizontal, rotX, rotY, depthScale,
persp, nodes));
} else {
double w = wOf(val, lo, span, heightScale);
double u = uOf(c, nCat);
nodes.add(proj(u, v, w, rotX, rotY, depthScale, persp));
if (spec.type == ChartSpec.Type.AREA3D) {
nodes.add(proj(u, v, floorW, rotX, rotY, depthScale, persp));
}
}
}
}
nodes.addAll(List.of(floor));
nodes.addAll(valueAnchors);
Fit fit = fit(nodes, box, leftGutter, topGutter, availW, availH);
// Каркас: контур пола.
Color axisColor = catAxis.axisLineColor != null
? catAxis.axisLineColor : valAxis.axisLineColor;
if (axisColor != null) {
g.setColor(axisColor);
g.setStroke(new BasicStroke(0.75f));
Path2D outline = new Path2D.Double();
for (int i = 0; i < floor.length; i++) {
double[] p = screen(floor[i], fit);
if (i == 0) {
outline.moveTo(p[0], p[1]);
} else {
outline.lineTo(p[0], p[1]);
}
}
outline.closePath();
g.draw(outline);
}
if (bar3d) {
drawColumns(g, columns, fit);
} else if (spec.type == ChartSpec.Type.LINE3D) {
drawLines(g, spec, palette, lo, span, heightScale, nCat, nSer,
rotX, rotY, depthScale, persp, fit);
} else {
drawAreas(g, spec, palette, lo, span, heightScale, floorW, nCat, nSer,
rotX, rotY, depthScale, persp, fit);
}
drawLabels(g, spec, tickValues, valueAnchors, nCat, horizontal,
rotX, rotY, depthScale, floorW, persp, fit);
}
/** Колонка bar3D: вертикальная (значение по w) или горизонтальная (по u). */
private static Column makeColumn(Color color, int c, double serOffset, int nCat,
double val,
double lo, double span, double heightScale,
double floorW, double bw, double colW,
boolean horizontal,
double rotX, double rotY, double depthScale,
double persp, List<Surface3dPainter.Node> nodes) {
double u0;
double u1;
double v0;
double v1;
double wTop;
if (horizontal) {
double band = (c + 0.5) / nCat - 0.5;
double vc = band + serOffset * colW;
v0 = vc - colW / 2.0;
v1 = vc + colW / 2.0;
double ua = uVal(0, lo, span);
double ub = uVal(val, lo, span);
u0 = Math.min(ua, ub);
u1 = Math.max(ua, ub);
wTop = floorW + colW * heightScale;
} else {
double uc = uOf(c, nCat);
u0 = uc - bw / 2.0;
u1 = uc + bw / 2.0;
double vc = serOffset * colW;
v0 = vc - colW / 2.0;
v1 = vc + colW / 2.0;
wTop = wOf(val, lo, span, heightScale);
}
double[] us = {u0, u1};
double[] vs = {v0, v1};
double[] ws = {floorW, wTop};
Surface3dPainter.Node[][][] corners = new Surface3dPainter.Node[2][2][2];
for (int u = 0; u < 2; u++) {
for (int v = 0; v < 2; v++) {
for (int w = 0; w < 2; w++) {
corners[u][v][w] = proj(us[u], vs[v], ws[w],
rotX, rotY, depthScale, persp);
nodes.add(corners[u][v][w]);
}
}
}
Surface3dPainter.Node center = proj((u0 + u1) / 2.0, (v0 + v1) / 2.0,
(floorW + wTop) / 2.0, rotX, rotY, depthScale, persp);
return new Column(center, corners, color);
}
/** Колонки от дальних к ближним: верх/перед цветом ряда, торец темнее. */
private static void drawColumns(Graphics2D g, List<Column> columns, Fit fit) {
columns.sort(Comparator.comparingDouble((Column col) -> col.center.depth())
.reversed());
for (Column col : columns) {
g.setColor(col.color);
// верх: w = 1
quad(g, col, fit, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1);
// перед: v = 0 (при rotY=0 ближняя к камере сторона)
quad(g, col, fit, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1);
// торец u = max — затемнён (псевдо-свет, калибровка тестом)
g.setColor(col.color.darker());
quad(g, col, fit, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1);
}
}
/** Грань по четырём углам (u, v, w) — индексы массивов corners. */
private static void quad(Graphics2D g, Column col, Fit fit,
int u1, int v1, int w1, int u2, int v2, int w2,
int u3, int v3, int w3, int u4, int v4, int w4) {
int[] uu = {u1, u2, u3, u4};
int[] vv = {v1, v2, v3, v4};
int[] ww = {w1, w2, w3, w4};
Path2D p = new Path2D.Double();
for (int i = 0; i < 4; i++) {
double[] s = screen(col.corners[uu[i]][vv[i]][ww[i]], fit);
if (i == 0) {
p.moveTo(s[0], s[1]);
} else {
p.lineTo(s[0], s[1]);
}
}
p.closePath();
g.fill(p);
}
private static void drawLines(Graphics2D g, ChartSpec spec, List<Color> palette,
double lo, double span, double heightScale,
int nCat, int nSer,
double rotX, double rotY, double depthScale,
double persp, Fit fit) {
for (int si = 0; si < nSer; si++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
double v = vOf(si, nSer);
List<Double> xs = new ArrayList<>();
List<Double> ys = new ArrayList<>();
for (int i = 0; i < s.values.size(); i++) {
Double val = s.values.get(i);
if (val == null) {
continue;
}
double[] p = screen(proj(uOf(i, nCat), v,
wOf(val, lo, span, heightScale), rotX, rotY, depthScale, persp), fit);
xs.add(p[0]);
ys.add(p[1]);
}
if (xs.size() >= MIN_POLYLINE_POINTS) {
g.setColor(c);
g.setStroke(new BasicStroke((float) (s.lineWidth > 0 ? s.lineWidth : 2.25),
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.draw(ChartRenderer.polyline(xs, ys, false));
}
if (s.marker) {
for (int i = 0; i < xs.size(); i++) {
CartesianPainter.drawMarker(g, xs.get(i), ys.get(i), false, c);
}
}
}
}
/** Стены area3D: от дальних рядов к ближним, полупрозрачная заливка. */
private static void drawAreas(Graphics2D g, ChartSpec spec, List<Color> palette,
double lo, double span, double heightScale,
double floorW, int nCat, int nSer,
double rotX, double rotY, double depthScale,
double persp, Fit fit) {
for (int si = nSer - 1; si >= 0; si--) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.fill != null ? s.fill : s.fillAt(si, palette);
double v = vOf(si, nSer);
List<Double> xs = new ArrayList<>();
List<Double> ys = new ArrayList<>();
List<Double> baseX = new ArrayList<>();
List<Double> baseY = new ArrayList<>();
for (int i = 0; i < s.values.size(); i++) {
Double val = s.values.get(i);
if (val == null) {
continue;
}
double u = uOf(i, nCat);
double[] p = screen(proj(u, v, wOf(val, lo, span, heightScale),
rotX, rotY, depthScale, persp), fit);
double[] b = screen(proj(u, v, floorW, rotX, rotY, depthScale, persp), fit);
xs.add(p[0]);
ys.add(p[1]);
baseX.add(b[0]);
baseY.add(b[1]);
}
if (xs.size() < MIN_POLYLINE_POINTS) {
continue;
}
Path2D wall = new Path2D.Double();
wall.moveTo(xs.get(0), ys.get(0));
for (int i = 1; i < xs.size(); i++) {
wall.lineTo(xs.get(i), ys.get(i));
}
for (int i = baseX.size() - 1; i >= 0; i--) {
wall.lineTo(baseX.get(i), baseY.get(i));
}
wall.closePath();
g.setColor(DrawMlColor.withAlpha(c, 0.55));
g.fill(wall);
g.setColor(c);
g.setStroke(new BasicStroke(1.2f));
g.draw(ChartRenderer.polyline(xs, ys, false));
}
}
/** Подписи: значения — вдоль переднего левого ребра, категории — нижнего. */
private static void drawLabels(Graphics2D g, ChartSpec spec, List<Double> tickValues,
List<Surface3dPainter.Node> valueAnchors, int nCat,
boolean horizontal, double rotX, double rotY,
double depthScale, double floorW, double persp,
Fit fit) {
ChartSpec.AxisSpec valAxis = spec.valAxis != null
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null
? spec.catAxis : new ChartSpec.AxisSpec();
DrawMlText.Style vs = valAxis.labelStyle;
if (vs != null) {
double h = DrawMlText.textHeight(vs) + 2;
for (int i = 0; i < valueAnchors.size(); i++) {
double[] p = screen(valueAnchors.get(i), fit);
String label = ChartRenderer.formatValue(tickValues.get(i), valAxis.numFmt);
double w = DrawMlText.textWidth(label, vs);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, vs, "r")),
new Rectangle2D.Double(p[0] - w - 4, p[1] - h / 2, w, h),
"r", "ctr", 1.0);
}
}
DrawMlText.Style cs = catAxis.labelStyle;
if (cs != null) {
List<String> cats = CartesianPainter.categoriesOf(spec, nCat);
double h = DrawMlText.textHeight(cs) + 2;
for (int c = 0; c < nCat; c++) {
String label = cats.get(c);
if (label.isEmpty()) {
continue;
}
Surface3dPainter.Node n = horizontal
? proj(-0.5, (c + 0.5) / nCat - 0.5, floorW,
rotX, rotY, depthScale, persp)
: proj(uOf(c, nCat), -0.5, floorW, rotX, rotY, depthScale, persp);
double[] p = screen(n, fit);
double w = DrawMlText.textWidth(label, cs);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, cs, "ctr")),
new Rectangle2D.Double(p[0] - w / 2, p[1] + 8, w, h), "ctr", "t", 1.0);
}
}
}
private static Fit fit(List<Surface3dPainter.Node> nodes, Rectangle2D box,
double leftGutter, double topGutter,
double availW, double availH) {
double minX = Double.MAX_VALUE;
double maxX = -Double.MAX_VALUE;
double minY = Double.MAX_VALUE;
double maxY = -Double.MAX_VALUE;
for (Surface3dPainter.Node n : nodes) {
minX = Math.min(minX, n.x());
maxX = Math.max(maxX, n.x());
minY = Math.min(minY, n.y());
maxY = Math.max(maxY, n.y());
}
double scale = Math.min(availW / Math.max(1e-6, maxX - minX),
availH / Math.max(1e-6, maxY - minY));
double offX = box.getX() + leftGutter
+ (availW - (maxX - minX) * scale) / 2 - minX * scale;
double offY = box.getY() + topGutter
+ (availH - (maxY - minY) * scale) / 2 - minY * scale;
return new Fit(scale, offX, offY);
}
private static Surface3dPainter.Node proj(double u, double v, double w,
double rotX, double rotY,
double depthScale, double persp) {
return Surface3dPainter.project(u, v, w, rotX, rotY, depthScale, persp);
}
private static double[] screen(Surface3dPainter.Node n, Fit fit) {
return new double[]{n.x() * fit.scale() + fit.offX(),
n.y() * fit.scale() + fit.offY()};
}
private static double wOf(double v, double lo, double span, double heightScale) {
return ((v - lo) / span - 0.5) * heightScale;
}
/** Значение -> u горизонтальной оси bar3D (протяжка по ширине). */
private static double uVal(double v, double lo, double span) {
return (v - lo) / span - 0.5;
}
private static double uOf(int c, int nCat) {
return (c + 0.5) / nCat - 0.5;
}
private static double vOf(int r, int nSer) {
return nSer > 1 ? (double) r / (nSer - 1) - 0.5 : 0;
}
}
@@ -134,7 +134,7 @@ final class CartesianPainter {
drawValueLabels(g, valLabels, plot, valStyle, lo, hi, horizontal);
}
private static List<String> categoriesOf(ChartSpec spec, int nCat) {
static List<String> categoriesOf(ChartSpec spec, int nCat) {
List<String> cats = new ArrayList<>();
for (int i = 0; i < nCat; i++) {
String label = null;
@@ -248,21 +248,27 @@ final class CartesianPainter {
g.draw(ChartRenderer.polyline(along, cross, false));
}
if (s.marker) {
g.setColor(c);
for (int i = 0; i < along.size(); i++) {
double a = along.get(i);
double b = cross.get(i);
double r = 2.2;
if (horizontal) {
g.fill(new Rectangle2D.Double(a - r, b - r, 2 * r, 2 * r));
} else {
g.fill(new java.awt.geom.Ellipse2D.Double(a - r, b - r, 2 * r, 2 * r));
}
drawMarker(g, along.get(i), cross.get(i), horizontal, c);
}
}
}
}
/**
* Маркер-точка: круг (вертикальные графики) либо квадрат (горизонтальные),
* радиус 2,2 pt. Единая семантика маркера для LINE/SCATTER/RADAR/STOCK.
*/
static void drawMarker(Graphics2D g, double x, double y, boolean square, Color c) {
double r = 2.2;
g.setColor(c);
if (square) {
g.fill(new Rectangle2D.Double(x - r, y - r, 2 * r, 2 * r));
} else {
g.fill(new java.awt.geom.Ellipse2D.Double(x - r, y - r, 2 * r, 2 * r));
}
}
private static void drawAreas(Graphics2D g, ChartSpec spec, Rectangle2D plot,
List<Color> palette, double lo, double hi, int nCat,
boolean horizontal) {
@@ -101,6 +101,18 @@ final class ChartRenderer {
CartesianPainter.paint(g, spec, box, palette);
case SURFACE3D ->
Surface3dPainter.paint(g, spec, box, palette);
case SCATTER, BUBBLE ->
ScatterPainter.paint(g, spec, box, palette);
case RADAR ->
RadarPainter.paint(g, spec, box, palette);
case STOCK ->
StockPainter.paint(g, spec, box, palette);
case OF_PIE ->
OfPiePainter.paint(g, spec, box, palette);
case SURFACE ->
Surface2dPainter.paint(g, spec, box, palette);
case AREA3D, LINE3D, BAR3D ->
Cartesian3dPainter.paint(g, spec, box, palette);
default -> { /* UNSUPPORTED: вызывающий не должен сюда доходить */ }
}
if (legend != null && spec.legendOverlay) {
@@ -196,7 +208,7 @@ final class ChartRenderer {
Legend legend = new Legend();
legend.style = style;
switch (spec.type) {
case PIE, PIE3D, DOUGHNUT -> {
case PIE, PIE3D, DOUGHNUT, OF_PIE -> {
ChartSpec.Series s = spec.series.isEmpty() ? null : spec.series.get(0);
if (s == null) {
return null;
@@ -206,7 +218,7 @@ final class ChartRenderer {
legend.entries.add(new Legend.Entry(label, s.fillAt(i, palette)));
}
}
case SURFACE3D -> {
case SURFACE3D, SURFACE -> {
double min = Double.MAX_VALUE;
double max = -Double.MAX_VALUE;
for (ChartSpec.Series s : spec.series) {
@@ -238,7 +250,8 @@ final class ChartRenderer {
for (ChartSpec.Series s : spec.series) {
Color c = s.lineColor != null ? s.lineColor
: s.fillAt(0, palette);
boolean lineLike = spec.type == ChartSpec.Type.LINE;
boolean lineLike = spec.type == ChartSpec.Type.LINE
|| spec.type == ChartSpec.Type.SCATTER;
legend.entries.add(new Legend.Entry(s.name == null ? "" : s.name, c,
lineLike ? Math.max(1.0, s.lineWidth > 0 ? s.lineWidth : 2.25) : -1));
}
@@ -252,7 +265,7 @@ final class ChartRenderer {
// у прочих ~0,55 кегля (21 px), у линейных рядов — отрезок ~2,4 кегля
// (89 px) толщиной с линию ряда.
boolean pie = spec.type == ChartSpec.Type.PIE || spec.type == ChartSpec.Type.PIE3D
|| spec.type == ChartSpec.Type.DOUGHNUT;
|| spec.type == ChartSpec.Type.DOUGHNUT || spec.type == ChartSpec.Type.OF_PIE;
legend.square = style.sizePt() * (pie ? 0.32 : 0.55);
legend.lineLen = style.sizePt() * 2.4;
double width = 0;
@@ -7,6 +7,10 @@ import org.docx4j.dml.chart.CTAxPos;
import org.docx4j.dml.chart.CTBoolean;
import org.docx4j.dml.chart.CTBandFmt;
import org.docx4j.dml.chart.CTBandFmts;
import org.docx4j.dml.chart.CTArea3DChart;
import org.docx4j.dml.chart.CTBar3DChart;
import org.docx4j.dml.chart.CTBubbleChart;
import org.docx4j.dml.chart.CTBubbleSer;
import org.docx4j.dml.chart.CTBarChart;
import org.docx4j.dml.chart.CTBarSer;
import org.docx4j.dml.chart.CTCatAx;
@@ -20,15 +24,27 @@ import org.docx4j.dml.chart.CTLineChart;
import org.docx4j.dml.chart.CTLineSer;
import org.docx4j.dml.chart.CTMarker;
import org.docx4j.dml.chart.STMarkerStyle;
import org.docx4j.dml.chart.CTNumDataSource;
import org.docx4j.dml.chart.CTLine3DChart;
import org.docx4j.dml.chart.CTNumVal;
import org.docx4j.dml.chart.CTNumDataSource;
import org.docx4j.dml.chart.CTNumData;
import org.docx4j.dml.chart.CTPlotArea;
import org.docx4j.dml.chart.CTOfPieChart;
import org.docx4j.dml.chart.CTRadarChart;
import org.docx4j.dml.chart.CTRadarSer;
import org.docx4j.dml.chart.CTScatterChart;
import org.docx4j.dml.chart.CTScatterSer;
import org.docx4j.dml.chart.CTPie3DChart;
import org.docx4j.dml.chart.CTScaling;
import org.docx4j.dml.chart.CTSerAx;
import org.docx4j.dml.chart.CTSerTx;
import org.docx4j.dml.chart.CTSurface3DChart;
import org.docx4j.dml.chart.CTSurfaceSer;
import org.docx4j.dml.chart.CTScaling;
import org.docx4j.dml.chart.CTPie3DChart;
import org.docx4j.dml.chart.CTSurface3DChart;
import org.docx4j.dml.chart.CTStockChart;
import org.docx4j.dml.chart.CTSurfaceChart;
import org.docx4j.dml.chart.CTUnsignedInt;
import org.docx4j.dml.chart.CTUpDownBar;
import org.docx4j.dml.chart.CTUpDownBars;
import org.docx4j.dml.chart.CTPieChart;
import org.docx4j.dml.chart.CTPieSer;
import org.docx4j.dml.chart.CTStrVal;
@@ -69,7 +85,9 @@ final class ChartSpec {
static final int MAX_POINTS = 100_000;
enum Type {
PIE, PIE3D, DOUGHNUT, BAR, BAR_HORIZONTAL, LINE, AREA, SURFACE3D, UNSUPPORTED
PIE, PIE3D, DOUGHNUT, BAR, BAR_HORIZONTAL, LINE, AREA, SURFACE3D,
AREA3D, BAR3D, LINE3D, RADAR, SCATTER, BUBBLE, STOCK, OF_PIE, SURFACE,
UNSUPPORTED
}
/** Один ряд: значения + стили (ряд и переопределения по точкам). */
@@ -87,6 +105,10 @@ final class ChartSpec {
double outlineWidth = -1;
boolean marker = true;
String markerSymbol;
/** scatter/bubble: значения оси X (c:xVal). */
final List<Double> xValues = new ArrayList<>();
/** bubble: размеры пузырей (c:bubbleSize). */
final List<Double> bubbleSizes = new ArrayList<>();
Color fillAt(int i, List<Color> palette) {
Color c = pointFills.get(i);
@@ -143,6 +165,51 @@ final class ChartSpec {
Color chartFill = Color.WHITE;
Color chartBorder = new Color(0xBF, 0xBF, 0xBF);
double chartBorderWidth = 0.75;
// Параметры новых типов (ECMA-376 §21.2.3); дефолты — XSD dml-chart.
/** scatter/bubble: ось X (вторая c:valAx в plotArea). */
AxisSpec xAxis;
/** CT_ScatterStyle (xsd default "marker"): marker|line|lineMarker|smooth|smoothMarker|none. */
String scatterStyle = "marker";
/** CT_BubbleScale (xsd default 100%): масштаб пузырей, %. */
double bubbleScale = 100;
/** c:bubble3D — рисуется плоско (см. ScatterPainter). */
boolean bubble3d;
/** CT_SizeRepresents (xsd default "area"): area|w. */
String sizeRepresents = "area";
/** CT_ShowNegativeBubbles (xsd default true). */
boolean showNegBubbles = true;
/** CT_GapAmount gapDepth (xsd default 150) — зазор рядов в глубину, %. */
double gapDepth = 150;
/** CT_Shape (xsd default "box") — форма 3D-столбцов; рисуется всегда box. */
String shape3d = "box";
/** c:barDir="bar" у bar3DChart — горизонтальная ориентация. */
boolean bar3dHorizontal;
/** CT_RadarStyle (xsd default "standard"): standard|marker|filled. */
String radarStyle = "standard";
/** CT_OfPieType (xsd default "pie"): pie|bar — вид вторичной диаграммы. */
String ofPieType = "pie";
/** CT_SplitType (xsd default "auto"): auto|cust|percent|pos|val. */
String splitType = "auto";
/** c:splitPos (CT_Double); null = элемент опущен. */
Double splitPos;
/** c:custSplit/c:secondPiePt — индексы точек вторичной круговой. */
final List<Integer> secondPiePts = new ArrayList<>();
/** CT_SecondPieSize (xsd default 75%): диаметр вторичной, % от первичной. */
double secondPieSize = 75;
/** элемент c:serLines присутствует — связи между тортами. */
boolean serLines;
/** элемент c:hiLowLines присутствует. */
boolean hiLowLines;
/** элемент c:dropLines присутствует. */
boolean dropLines;
/** элемент c:upDownBars присутствует. */
boolean upDownBars;
/** c:upDownBars/c:gapWidth (xsd default 150). */
double upDownGapWidth = 150;
/** c:upBars/c:spPr solidFill (null = дефолт пейнтера). */
Color upFill;
/** c:downBars/c:spPr solidFill (null = дефолт пейнтера). */
Color downFill;
/** Цвета акцента темы — базовая палитра рядов (как в Word). */
static List<Color> palette(DrawMlColor colors) {
@@ -171,10 +238,12 @@ final class ChartSpec {
for (Object group : pa.getAreaChartOrArea3DChartOrLineChart()) {
readGroup(group, spec, colors, palette);
}
List<AxisSpec> valAxes = new ArrayList<>();
for (Object ax : pa.getValAxOrCatAxOrDateAx()) {
AxisSpec a = readAxis(ax, colors);
if (ax instanceof CTValAx) {
spec.valAxis = a;
valAxes.add(a);
} else if (ax instanceof CTCatAx) {
spec.catAxis = a;
} else if (ax instanceof CTSerAx) {
@@ -183,6 +252,14 @@ final class ChartSpec {
spec.catAxis = a;
}
}
// scatter/bubble: обе оси числовые — две c:valAx (ECMA порядок не
// нормирует; Word пишет ось X первой — регрессия
// ChartSpecTest#scatterFirstValAxisIsX).
if ((spec.type == Type.SCATTER || spec.type == Type.BUBBLE)
&& valAxes.size() >= 2) {
spec.xAxis = valAxes.get(0);
spec.valAxis = valAxes.get(1);
}
}
readLegend(chart, spec, colors);
readTitle(chart, spec, colors);
@@ -270,18 +347,7 @@ final class ChartSpec {
} else if (group instanceof CTLineChart g) {
spec.type = Type.LINE;
for (CTLineSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
readLineProps(s.getSpPr(), ser, colors);
CTMarker m = s.getMarker();
if (m != null) {
ser.marker = m.getSymbol() == null
|| m.getSymbol().getVal() != STMarkerStyle.NONE;
if (m.getSymbol() != null) {
ser.markerSymbol = m.getSymbol().getVal().value();
}
}
spec.series.add(ser);
spec.series.add(readLineSer(s, colors));
}
} else if (group instanceof CTBarChart g) {
boolean horizontal = g.getBarDir() != null
@@ -316,24 +382,197 @@ final class ChartSpec {
}
} else if (group instanceof CTSurface3DChart g) {
spec.type = Type.SURFACE3D;
spec.wireframe = isTrue(g.getWireframe());
for (CTSurfaceSer s : g.getSer()) {
readSurfaceGroup(isTrue(g.getWireframe()), g.getSer(), g.getBandFmts(),
spec, colors, palette);
} else if (group instanceof CTSurfaceChart g) {
spec.type = Type.SURFACE;
readSurfaceGroup(isTrue(g.getWireframe()), g.getSer(), g.getBandFmts(),
spec, colors, palette);
} else if (group instanceof CTArea3DChart g) {
spec.type = Type.AREA3D;
if (g.getGapDepth() != null) {
spec.gapDepth = g.getGapDepth().getVal();
}
for (org.docx4j.dml.chart.CTAreaSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), List.of(), ser, colors);
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
readLineProps(s.getSpPr(), ser, colors);
spec.series.add(ser);
}
} else if (group instanceof CTLine3DChart g) {
spec.type = Type.LINE3D;
if (g.getGapDepth() != null) {
spec.gapDepth = g.getGapDepth().getVal();
}
for (CTLineSer s : g.getSer()) {
spec.series.add(readLineSer(s, colors));
}
} else if (group instanceof CTBar3DChart g) {
spec.type = Type.BAR3D;
spec.bar3dHorizontal = g.getBarDir() != null
&& g.getBarDir().getVal() != null
&& "bar".equalsIgnoreCase(g.getBarDir().getVal().value());
if (g.getGapWidth() != null) {
spec.gapWidth = g.getGapWidth().getVal();
}
if (g.getGapDepth() != null) {
spec.gapDepth = g.getGapDepth().getVal();
}
if (g.getShape() != null && g.getShape().getVal() != null) {
spec.shape3d = g.getShape().getVal().value();
}
for (CTBarSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
spec.series.add(ser);
}
CTBandFmts bf = g.getBandFmts();
if (bf != null) {
for (CTBandFmt b : bf.getBandFmt()) {
Color c = b.getSpPr() != null && b.getSpPr().getSolidFill() != null
? colors.resolveFill(b.getSpPr().getSolidFill())
: null;
spec.bandColors.add(c != null ? c
: palette.get((int) (b.getIdx().getVal() % palette.size())));
} else if (group instanceof CTRadarChart g) {
spec.type = Type.RADAR;
if (g.getRadarStyle() != null && g.getRadarStyle().getVal() != null) {
spec.radarStyle = g.getRadarStyle().getVal().value();
}
for (CTRadarSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
readLineProps(s.getSpPr(), ser, colors);
readMarker(s.getMarker(), ser);
spec.series.add(ser);
}
} else if (group instanceof CTScatterChart g) {
spec.type = Type.SCATTER;
if (g.getScatterStyle() != null && g.getScatterStyle().getVal() != null) {
spec.scatterStyle = g.getScatterStyle().getVal().value();
}
for (CTScatterSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), null, s.getYVal(), s.getDPt(), ser, colors);
ser.xValues.addAll(axisNumValues(s.getXVal()));
readLineProps(s.getSpPr(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
readMarker(s.getMarker(), ser);
spec.series.add(ser);
}
} else if (group instanceof CTBubbleChart g) {
spec.type = Type.BUBBLE;
spec.bubble3d = isTrue(g.getBubble3D());
if (g.getBubbleScale() != null) {
spec.bubbleScale = g.getBubbleScale().getVal();
}
if (g.getShowNegBubbles() != null) {
spec.showNegBubbles = g.getShowNegBubbles().isVal();
}
if (g.getSizeRepresents() != null && g.getSizeRepresents().getVal() != null) {
spec.sizeRepresents = g.getSizeRepresents().getVal().value();
}
for (CTBubbleSer s : g.getSer()) {
Series ser = new Series();
readCommon(s.getTx(), null, s.getYVal(), s.getDPt(), ser, colors);
ser.xValues.addAll(axisNumValues(s.getXVal()));
ser.bubbleSizes.addAll(numValues(s.getBubbleSize()));
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
spec.series.add(ser);
}
} else if (group instanceof CTStockChart g) {
spec.type = Type.STOCK;
spec.hiLowLines = g.getHiLowLines() != null;
spec.dropLines = g.getDropLines() != null;
CTUpDownBars u = g.getUpDownBars();
if (u != null) {
spec.upDownBars = true;
if (u.getGapWidth() != null) {
spec.upDownGapWidth = u.getGapWidth().getVal();
}
spec.upFill = upDownBarFill(u.getUpBars(), colors);
spec.downFill = upDownBarFill(u.getDownBars(), colors);
}
for (CTLineSer s : g.getSer()) {
spec.series.add(readLineSer(s, colors));
}
} else if (group instanceof CTOfPieChart g) {
spec.type = Type.OF_PIE;
if (g.getOfPieType() != null && g.getOfPieType().getVal() != null) {
spec.ofPieType = g.getOfPieType().getVal().value();
}
if (g.getSplitType() != null && g.getSplitType().getVal() != null) {
spec.splitType = g.getSplitType().getVal().value();
}
if (g.getSplitPos() != null) {
spec.splitPos = g.getSplitPos().getVal();
}
if (g.getCustSplit() != null) {
for (CTUnsignedInt p : g.getCustSplit().getSecondPiePt()) {
spec.secondPiePts.add((int) p.getVal());
}
}
if (g.getSecondPieSize() != null) {
spec.secondPieSize = g.getSecondPieSize().getVal();
}
spec.serLines = !g.getSerLines().isEmpty();
for (CTPieSer s : g.getSer()) {
spec.series.add(readPieSer(s, colors));
}
}
}
/** CT_LineSer — общий разбор ряда lineChart/line3DChart/stockChart. */
private static Series readLineSer(CTLineSer s, DrawMlColor colors) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), s.getDPt(), ser, colors);
readLineProps(s.getSpPr(), ser, colors);
readMarker(s.getMarker(), ser);
return ser;
}
/** c:marker: symbol="none" → маркеров нет (семантика прежняя, для LINE). */
private static void readMarker(CTMarker m, Series ser) {
if (m == null) {
return;
}
ser.marker = m.getSymbol() == null
|| m.getSymbol().getVal() != STMarkerStyle.NONE;
if (m.getSymbol() != null) {
ser.markerSymbol = m.getSymbol().getVal().value();
}
}
/** c:upBars/c:downBars/c:spPr solidFill; null — элемента/заливки нет. */
private static Color upDownBarFill(CTUpDownBar bar, DrawMlColor colors) {
if (bar == null || bar.getSpPr() == null || bar.getSpPr().getSolidFill() == null) {
return null;
}
return colors.resolveFill(bar.getSpPr().getSolidFill());
}
/** surfaceChart/surface3DChart — общий разбор wireframe/сер/bandFmts. */
private static void readSurfaceGroup(boolean wireframe, List<CTSurfaceSer> sers,
CTBandFmts bf, ChartSpec spec,
DrawMlColor colors, List<Color> palette) {
spec.wireframe = wireframe;
for (CTSurfaceSer s : sers) {
Series ser = new Series();
readCommon(s.getTx(), s.getCat(), s.getVal(), List.of(), ser, colors);
if (s.getSpPr() != null && s.getSpPr().getSolidFill() != null) {
ser.fill = colors.resolveFill(s.getSpPr().getSolidFill());
}
spec.series.add(ser);
}
if (bf != null) {
for (CTBandFmt b : bf.getBandFmt()) {
Color c = b.getSpPr() != null && b.getSpPr().getSolidFill() != null
? colors.resolveFill(b.getSpPr().getSolidFill())
: null;
spec.bandColors.add(c != null ? c
: palette.get((int) (b.getIdx().getVal() % palette.size())));
}
}
}
@@ -364,27 +603,7 @@ final class ChartSpec {
List<CTDPt> dPts, Series ser, DrawMlColor colors) {
ser.name = seriesName(tx);
ser.categories.addAll(categoryNames(cat));
if (val != null) {
var num = val.getNumRef() != null ? val.getNumRef().getNumCache() : val.getNumLit();
if (num != null) {
long count = num.getPtCount() != null ? num.getPtCount().getVal() : -1;
if (count > MAX_POINTS) {
throw new IllegalArgumentException("c:pt idx/ptCount превышает лимит " + MAX_POINTS);
}
for (CTNumVal v : num.getPt()) {
checkPointIndex(v.getIdx());
while (ser.values.size() < (int) v.getIdx()) {
ser.values.add(null);
}
ser.values.add(parseDouble(v.getV()));
}
if (count > ser.values.size()) {
while (ser.values.size() < (int) count) {
ser.values.add(null);
}
}
}
}
ser.values.addAll(numValues(val));
for (CTDPt dp : dPts) {
if (dp.getSpPr() == null || dp.getSpPr().getSolidFill() == null
|| dp.getIdx() == null) {
@@ -397,6 +616,49 @@ final class ChartSpec {
}
}
/** c:numDataSource → список значений (numCache/numLit), DoS-гвард MAX_POINTS. */
private static List<Double> numValues(CTNumDataSource src) {
if (src == null) {
return new ArrayList<>();
}
return numValues(src.getNumRef() != null
? src.getNumRef().getNumCache() : src.getNumLit());
}
/** c:xVal (CT_AxDataSource, §21.2.2.171) — числовые значения оси X. */
private static List<Double> axisNumValues(CTAxDataSource x) {
if (x == null) {
return new ArrayList<>();
}
return numValues(x.getNumRef() != null
? x.getNumRef().getNumCache() : x.getNumLit());
}
/** numCache/numLit → значения; тот же DoS-гвард MAX_POINTS, что у c:val. */
private static List<Double> numValues(CTNumData num) {
List<Double> out = new ArrayList<>();
if (num == null) {
return out;
}
long count = num.getPtCount() != null ? num.getPtCount().getVal() : -1;
if (count > MAX_POINTS) {
throw new IllegalArgumentException("c:pt idx/ptCount превышает лимит " + MAX_POINTS);
}
for (CTNumVal v : num.getPt()) {
checkPointIndex(v.getIdx());
while (out.size() < (int) v.getIdx()) {
out.add(null);
}
out.add(parseDouble(v.getV()));
}
if (count > out.size()) {
while (out.size() < (int) count) {
out.add(null);
}
}
return out;
}
/** a:ln ряда (цвет и толщина линии графика). */
private static void readLineProps(CTShapeProperties sp, Series ser, DrawMlColor colors) {
if (sp == null) {
@@ -468,7 +730,7 @@ final class ChartSpec {
&& chart.getAutoTitleDeleted().isVal();
if ((text == null || text.isBlank()) && !deleted) {
boolean circular = spec.type == Type.PIE || spec.type == Type.PIE3D
|| spec.type == Type.DOUGHNUT;
|| spec.type == Type.DOUGHNUT || spec.type == Type.OF_PIE;
if (circular && !spec.series.isEmpty()) {
text = spec.series.get(0).name;
} else {
@@ -0,0 +1,247 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Комбинированная диаграмма (c:ofPieChart, ECMA-376 §21.2.2.108): главный
* пирог из первичных точек + вторичная круговая (c:ofPieType="pie") либо
* вертикальный стек ("bar") из вторичных. Разбиение по c:splitType
* (auto|cust|percent|pos|val, §21.2.2.155; семантика splitPos —
* MS-OI29500 §2.1.1554a/b): auto/pos — последние ceil(n/3) (или splitPos)
* точек, val/percent — точки ниже splitPos, cust — c:secondPiePt.
* Вторичных точек нет → обычная круговая через {@link PiePainter}.
* c:serLines — связи от обода главного пирога (эффективный угол точки в
* «хвостовом» секторе) до середины вторичного сектора/сегмента.
*
* Регрессия — OfPiePainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
final class OfPiePainter {
/** c:serLines — серый 0xA6A6A6 (дефолт Word, калибровка — OfPiePainterTest). */
static final Color SER_LINE_COLOR = new Color(0xA6, 0xA6, 0xA6);
/** Доля области построения под диаметр главного пирога (Word-эмпирика). */
private static final double MAIN_FIT = 0.72;
/** c:ofPieType="bar" — вторичная часть столбчатая (§21.2.2.134). */
private static final String SECONDARY_BAR = "bar";
private OfPiePainter() {
}
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
if (spec.series.isEmpty()) {
return;
}
ChartSpec.Series s = spec.series.get(0);
double total = 0;
for (Double v : s.values) {
if (v != null && v > 0) {
total += v;
}
}
if (total <= 0) {
return;
}
Set<Integer> secondary = splitIndices(spec, s, total);
if (secondary.isEmpty()) {
PiePainter.paint(g, spec, box, palette, null);
return;
}
double d1 = MAIN_FIT * Math.min(box.getWidth(), box.getHeight());
double d2 = d1 * spec.secondPieSize / 100.0;
double gap = 0.10 * d1;
if (d1 + gap + d2 > box.getWidth()) {
double k = box.getWidth() / (d1 + gap + d2);
d1 *= k;
d2 *= k;
gap *= k;
}
double cy = box.getY() + box.getHeight() / 2.0;
double cx1 = box.getX() + d1 / 2.0;
double cx2 = box.getX() + d1 + gap + d2 / 2.0;
double totalSecondary = 0;
for (int i : secondary) {
totalSecondary += s.values.get(i);
}
// Главный пирог: только первичные точки, углы от c:firstSliceAng.
double angle = spec.firstSliceAng;
double primarySweep = 0;
for (int i = 0; i < s.values.size(); i++) {
Double v = s.values.get(i);
if (v == null || v <= 0 || secondary.contains(i)) {
continue;
}
double sweep = 360.0 * v / total;
drawSector(g, s, i, palette, cx1, cy, d1 / 2.0, angle, sweep);
angle += sweep;
primarySweep += sweep;
}
double secondaryLeft = box.getX() + d1 + gap;
if (SECONDARY_BAR.equalsIgnoreCase(spec.ofPieType)) {
drawSecondaryBar(g, s, palette, secondary, totalSecondary,
secondaryLeft, cy, d1, d2);
} else {
drawSecondaryPie(g, spec, s, palette, secondary, totalSecondary,
cx2, cy, d2);
}
if (spec.serLines) {
drawSerLines(g, spec, s, secondary, total, totalSecondary,
primarySweep, cx1, cy, d1, cx2, cy, d2, secondaryLeft);
}
}
/** Индексы вторичных точек по c:splitType/c:splitPos/c:custSplit. */
static Set<Integer> splitIndices(ChartSpec spec, ChartSpec.Series s, double total) {
Set<Integer> out = new HashSet<>();
int nCat = s.values.size();
String type = spec.splitType == null ? "auto" : spec.splitType;
switch (type) {
case "cust" -> out.addAll(spec.secondPiePts);
case "pos" -> {
int n = spec.splitPos != null
? (int) Math.max(0d, spec.splitPos)
: (int) Math.ceil(nCat / 3.0);
for (int i = Math.max(0, nCat - n); i < nCat; i++) {
out.add(i);
}
}
case "val" -> {
if (spec.splitPos != null) {
for (int i = 0; i < nCat; i++) {
Double v = s.values.get(i);
if (v != null && v > 0 && v < spec.splitPos) {
out.add(i);
}
}
}
}
case "percent" -> {
if (spec.splitPos != null && total > 0) {
for (int i = 0; i < nCat; i++) {
Double v = s.values.get(i);
if (v != null && v > 0 && 100.0 * v / total < spec.splitPos) {
out.add(i);
}
}
}
}
default -> {
int n = (int) Math.ceil(nCat / 3.0);
for (int i = Math.max(0, nCat - n); i < nCat; i++) {
out.add(i);
}
}
}
// Точки без положительного значения — ни в один торт (как PiePainter).
out.removeIf(i -> i < 0 || i >= nCat || s.values.get(i) == null
|| s.values.get(i) <= 0);
return out;
}
private static void drawSecondaryPie(Graphics2D g, ChartSpec spec, ChartSpec.Series s,
List<Color> palette, Set<Integer> secondary,
double totalSecondary, double cx, double cy,
double d2) {
double angle = spec.firstSliceAng;
for (int i : orderedIndices(secondary)) {
double sweep = 360.0 * s.values.get(i) / totalSecondary;
drawSector(g, s, i, palette, cx, cy, d2 / 2.0, angle, sweep);
angle += sweep;
}
}
/** Вторичный «bar»: вертикальный стек сверху вниз в порядке индексов. */
private static void drawSecondaryBar(Graphics2D g, ChartSpec.Series s,
List<Color> palette, Set<Integer> secondary,
double totalSecondary, double left, double cy,
double d1, double d2) {
double w = d2 / 2.0;
double top = cy - d1 / 2.0;
for (int i : orderedIndices(secondary)) {
double h = d1 * s.values.get(i) / totalSecondary;
g.setColor(s.fillAt(i, palette));
g.fill(new Rectangle2D.Double(left, top, w, h));
top += h;
}
}
/**
* Связи c:serLines: от обода главного пирога на эффективном угле точки
* (первичные сектора + накопленная доля вторичных в «хвостовом» секторе)
* до внешней середины её вторичного сектора/сегмента.
*/
private static void drawSerLines(Graphics2D g, ChartSpec spec, ChartSpec.Series s,
Set<Integer> secondary, double total,
double totalSecondary, double primarySweep,
double cx1, double cy1, double d1,
double cx2, double cy2, double d2,
double secondaryLeft) {
g.setColor(SER_LINE_COLOR);
g.setStroke(new BasicStroke(0.75f));
boolean bar = "bar".equalsIgnoreCase(spec.ofPieType);
double wedgeWidth = 360.0 * totalSecondary / total;
double acc = 0;
double secAngle = spec.firstSliceAng;
double stackTop = cy2 - d1 / 2.0;
double w = d2 / 2.0;
for (int i : orderedIndices(secondary)) {
double share = s.values.get(i) / totalSecondary;
double mainAngle = spec.firstSliceAng + primarySweep
+ (acc + share / 2.0) * wedgeWidth;
double mrad = Math.toRadians(mainAngle);
double mx = cx1 + d1 / 2.0 * Math.sin(mrad);
double my = cy1 - d1 / 2.0 * Math.cos(mrad);
double tx;
double ty;
if (bar) {
double h = d1 * share;
tx = secondaryLeft + w;
ty = stackTop + h / 2.0;
stackTop += h;
} else {
double mid = Math.toRadians(secAngle + 360.0 * share / 2.0);
tx = cx2 + d2 / 2.0 * Math.sin(mid);
ty = cy2 - d2 / 2.0 * Math.cos(mid);
}
secAngle += 360.0 * share;
acc += share;
g.draw(new Line2D.Double(mx, my, tx, ty));
}
}
/** Один сектор: углы Word — от 12 часов по часовой, обводка как у PiePainter. */
private static void drawSector(Graphics2D g, ChartSpec.Series s, int i,
List<Color> palette, double cx, double cy,
double radius, double startDeg, double sweepDeg) {
Arc2D.Double arc = new Arc2D.Double(cx - radius, cy - radius, 2 * radius, 2 * radius,
90.0 - startDeg, -sweepDeg, Arc2D.PIE);
g.setColor(s.fillAt(i, palette));
g.fill(arc);
Color outline = s.outlineNoFill ? null
: s.outlineColor != null ? s.outlineColor : Color.WHITE;
if (outline != null) {
g.setColor(outline);
g.setStroke(new BasicStroke((float) (s.outlineWidth > 0 ? s.outlineWidth : 1.0)));
g.draw(arc);
}
}
private static List<Integer> orderedIndices(Set<Integer> set) {
return set.stream().sorted().toList();
}
}
@@ -0,0 +1,136 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
/**
* Лепестковая диаграмма (c:radarChart, ECMA-376 §21.2.2.143): категории —
* спицы от 12 часов по часовой, значения — радиус по оси значений.
* c:radarStyle (§21.2.2.119): standard — контур, marker — контур + маркеры,
* filled — полупрозрачная заливка без контура (вид как у AREA).
* Сетка — концентрические многоугольники по делениям оси значений (паутина
* прямыми звеньями, как в Word) и спицы.
*
* Регрессия — RadarPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
final class RadarPainter {
private RadarPainter() {
}
/** Контур ряда рисуется только из двух и более точек. */
private static final int MIN_POLYLINE_POINTS = 2;
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
int nCat = 0;
for (ChartSpec.Series s : spec.series) {
nCat = Math.max(nCat, s.values.size());
}
if (nCat < 2 || spec.series.isEmpty()) {
return;
}
List<String> cats = CartesianPainter.categoriesOf(spec, nCat);
ChartSpec.AxisSpec valAxis = spec.valAxis != null
? spec.valAxis : new ChartSpec.AxisSpec();
double[] range = ChartRenderer.valueRange(spec);
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1], true);
double lo = bounds[0];
double hi = bounds[1];
double unit = bounds[2];
DrawMlText.Style catStyle = spec.catAxis != null ? spec.catAxis.labelStyle : null;
double gutter = catStyle != null ? DrawMlText.textHeight(catStyle) + 6 : 12;
double side = Math.min(box.getWidth(), box.getHeight());
double cx = box.getCenterX();
double cy = box.getCenterY();
double r = Math.max(10, side / 2.0 - gutter);
// 1. Паутина: концентрические многоугольники по делениям + спицы.
g.setColor(valAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
for (double v = lo; v <= hi + unit / 2; v += unit) {
double t = (v - lo) / (hi - lo);
Path2D web = new Path2D.Double();
for (int i = 0; i < nCat; i++) {
double[] p = spoke(cx, cy, r * t, i, nCat);
if (i == 0) {
web.moveTo(p[0], p[1]);
} else {
web.lineTo(p[0], p[1]);
}
}
web.closePath();
g.draw(web);
}
for (int i = 0; i < nCat; i++) {
double[] tip = spoke(cx, cy, r, i, nCat);
g.draw(new java.awt.geom.Line2D.Double(cx, cy, tip[0], tip[1]));
}
// 2. Ряды.
boolean filled = "filled".equalsIgnoreCase(spec.radarStyle);
boolean markers = "marker".equalsIgnoreCase(spec.radarStyle);
for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
List<Double> xs = new ArrayList<>();
List<Double> ys = new ArrayList<>();
for (int i = 0; i < s.values.size(); i++) {
Double v = s.values.get(i);
if (v == null) {
continue;
}
double t = (v - lo) / (hi - lo);
double[] p = spoke(cx, cy, r * t, i, nCat);
xs.add(p[0]);
ys.add(p[1]);
}
if (xs.size() >= MIN_POLYLINE_POINTS) {
Path2D line = ChartRenderer.polyline(xs, ys, true);
if (filled) {
g.setColor(DrawMlColor.withAlpha(c, 0.55));
g.fill(line);
} else {
g.setColor(c);
g.setStroke(new BasicStroke((float) (s.lineWidth > 0 ? s.lineWidth : 2.25),
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.draw(line);
}
}
if (markers && s.marker) {
for (int i = 0; i < xs.size(); i++) {
CartesianPainter.drawMarker(g, xs.get(i), ys.get(i), false, c);
}
}
}
// 3. Подписи категорий у концов спиц.
if (catStyle != null) {
double h = DrawMlText.textHeight(catStyle) + 2;
for (int i = 0; i < nCat; i++) {
String label = cats.get(i);
if (label.isEmpty()) {
continue;
}
double[] p = spoke(cx, cy, r + 4, i, nCat);
double w = DrawMlText.textWidth(label, catStyle);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, catStyle, "ctr")),
new Rectangle2D.Double(p[0] - w / 2, p[1] - h / 2, w, h),
"ctr", "ctr", 1.0);
}
}
}
/** Точка на спине i (от 12 часов по часовой) на расстоянии dist от центра. */
private static double[] spoke(double cx, double cy, double dist, int i, int nCat) {
double rad = Math.toRadians(-90 + 360.0 * i / nCat);
return new double[]{cx + dist * Math.cos(rad), cy + dist * Math.sin(rad)};
}
}
@@ -0,0 +1,211 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
/**
* Точечная (c:scatterChart) и пузырьковая (c:bubbleChart) диаграммы: обе оси
* числовые — две c:valAx, ось X — первая из них (ChartSpec.parse, регрессия
* ChartSpecTest#scatterFirstValAxisIsX).
*
* scatter: маркеры по c:marker ряда, линия по c:scatterStyle (line/smooth —
* ECMA-376 §21.2.2.136, сглаживание — кривая Жозефа де Кастельно не
* имитируется, ломаная с JOIN_ROUND). bubble: круги без обводки, радиус
* sqrt(|size|/maxSize) при c:sizeRepresents="area" (§21.2.2.128) и линейно
* при "w", масштаб c:bubbleScale. Ограничения: c:bubble3D рисуется плоско.
*
* Регрессия — ScatterPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
final class ScatterPainter {
private ScatterPainter() {
}
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
ChartSpec.AxisSpec valAxis = spec.valAxis != null
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec xAxis = spec.xAxis != null ? spec.xAxis : valAxis;
double xMin = Double.MAX_VALUE;
double xMax = -Double.MAX_VALUE;
boolean any = false;
for (ChartSpec.Series s : spec.series) {
for (int i = 0; i < s.values.size(); i++) {
if (s.values.get(i) == null) {
continue;
}
any = true;
double x = xOf(s, i);
xMin = Math.min(xMin, x);
xMax = Math.max(xMax, x);
}
}
if (!any) {
return;
}
double[] range = ChartRenderer.valueRange(spec);
double[] yb = ChartRenderer.axisBounds(valAxis, range[0], range[1], true);
double lo = yb[0];
double hi = yb[1];
double unit = yb[2];
double[] xb = ChartRenderer.axisBounds(xAxis, xMin, xMax, true);
double xLo = xb[0];
double xHi = xb[1];
double xUnit = xb[2];
DrawMlText.Style valStyle = valAxis.labelStyle;
DrawMlText.Style xStyle = xAxis.labelStyle;
List<String> valLabels = new ArrayList<>();
for (double v = lo; v <= hi + unit / 2; v += unit) {
valLabels.add(ChartRenderer.formatValue(v, valAxis.numFmt));
}
List<String> xLabels = new ArrayList<>();
for (double v = xLo; v <= xHi + xUnit / 2; v += xUnit) {
xLabels.add(ChartRenderer.formatValue(v, xAxis.numFmt));
}
// Поля под подписи осей — как у CartesianPainter: ширина подписей
// значений слева, высота строки категорий снизу.
double valGutter = 8;
if (valStyle != null) {
for (String l : valLabels) {
valGutter = Math.max(valGutter, DrawMlText.textWidth(l, valStyle) + 8);
}
}
double xGutter = 6 + (xStyle != null ? DrawMlText.textHeight(xStyle) : 0);
Rectangle2D plot = new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
Math.max(10, box.getWidth() - valGutter),
Math.max(10, box.getHeight() - xGutter));
// Сетка: горизонтальные — по делениям оси значений, вертикальные —
// по делениям оси X (без линии осей: обе оси числовые).
if (valAxis.gridlines && !valAxis.deleted) {
g.setColor(valAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
for (double v = lo; v <= hi + unit / 2; v += unit) {
double y = plot.getY() + (1 - (v - lo) / (hi - lo)) * plot.getHeight();
g.draw(new Line2D.Double(plot.getX(), y,
plot.getX() + plot.getWidth(), y));
}
}
if (xAxis.gridlines && !xAxis.deleted) {
g.setColor(xAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
for (double v = xLo; v <= xHi + xUnit / 2; v += xUnit) {
double x = plot.getX() + (v - xLo) / (xHi - xLo) * plot.getWidth();
g.draw(new Line2D.Double(x, plot.getY(), x, plot.getY() + plot.getHeight()));
}
}
boolean bubble = spec.type == ChartSpec.Type.BUBBLE;
double maxSize = 0;
if (bubble) {
for (ChartSpec.Series s : spec.series) {
for (Double sz : s.bubbleSizes) {
if (sz != null) {
maxSize = Math.max(maxSize, Math.abs(sz));
}
}
}
}
double rMax = Math.min(plot.getWidth(), plot.getHeight())
* (spec.bubbleScale / 100.0) / 2.0;
for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
List<Double> xs = new ArrayList<>();
List<Double> ys = new ArrayList<>();
for (int i = 0; i < s.values.size(); i++) {
Double v = s.values.get(i);
if (v == null) {
continue;
}
double px = plot.getX() + (xOf(s, i) - xLo) / (xHi - xLo) * plot.getWidth();
double py = plot.getY() + (1 - (v - lo) / (hi - lo)) * plot.getHeight();
xs.add(px);
ys.add(py);
if (bubble) {
drawBubble(g, spec, s, i, px, py, maxSize, rMax, palette);
}
}
if (bubble) {
continue;
}
String style = spec.scatterStyle == null ? "marker" : spec.scatterStyle;
boolean smooth = style.startsWith("smooth");
if (xs.size() >= 2 && (style.startsWith("line") || smooth)) {
g.setColor(c);
g.setStroke(new BasicStroke(2.25f, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND));
g.draw(ChartRenderer.polyline(xs, ys, smooth));
}
if (s.marker) {
for (int i = 0; i < xs.size(); i++) {
CartesianPainter.drawMarker(g, xs.get(i), ys.get(i), false, c);
}
}
}
// Подписи делений обеих осей.
if (valStyle != null) {
double h = DrawMlText.textHeight(valStyle) + 2;
for (int i = 0; i < valLabels.size(); i++) {
double t = valLabels.size() == 1 ? 0 : i / (double) (valLabels.size() - 1);
String label = valLabels.get(i);
double w = DrawMlText.textWidth(label, valStyle);
double y = plot.getY() + plot.getHeight() * (1 - t);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, valStyle, "r")),
new Rectangle2D.Double(plot.getX() - w - 6, y - h / 2, w, h),
"r", "ctr", 1.0);
}
}
if (xStyle != null) {
double h = DrawMlText.textHeight(xStyle) + 2;
for (int i = 0; i < xLabels.size(); i++) {
double t = xLabels.size() == 1 ? 0 : i / (double) (xLabels.size() - 1);
String label = xLabels.get(i);
double w = DrawMlText.textWidth(label, xStyle);
double x = plot.getX() + plot.getWidth() * t;
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, xStyle, "ctr")),
new Rectangle2D.Double(x - w / 2, plot.getY() + plot.getHeight() + 3,
w, h), "ctr", "t", 1.0);
}
}
}
/** Один пузырь: круг без обводки; цвет — ряда, переопределение c:dPt. */
private static void drawBubble(Graphics2D g, ChartSpec spec, ChartSpec.Series s,
int i, double px, double py, double maxSize,
double rMax, List<Color> palette) {
Double size = i < s.bubbleSizes.size() ? s.bubbleSizes.get(i) : null;
if (size == null || (size < 0 && !spec.showNegBubbles) || maxSize <= 0) {
return;
}
double f = "w".equalsIgnoreCase(spec.sizeRepresents)
? Math.abs(size) / maxSize
: Math.sqrt(Math.abs(size) / maxSize);
double r = rMax * f;
if (r <= 0) {
return;
}
Color point = s.pointFills.get(i);
g.setColor(point != null ? point
: s.fill != null ? s.fill : palette.get(i % palette.size()));
g.fill(new Ellipse2D.Double(px - r, py - r, 2 * r, 2 * r));
}
/** Значение X точки: c:xVal, у ряда без него — позиция 1..n. */
private static double xOf(ChartSpec.Series s, int i) {
Double x = i < s.xValues.size() ? s.xValues.get(i) : null;
return x != null ? x : i + 1;
}
}
@@ -0,0 +1,218 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
/**
* Биржевая диаграмма (c:stockChart, ECMA-376 §21.2.2.153): ряды — линии
* (CT_LineSer, обычно open/high/low/close), плюс факультативные
* c:hiLowLines (вертикаль min..max по всем рядам категории),
* c:upDownBars (столбик между первым и последним рядом: вверх — зелёный,
* вниз — красный) и c:dropLines (вертикаль от точки до базовой линии).
*
* HI_LOW_COLOR/UP_FILL/DOWN_FILL/цвет dropLines — дефолты UI Word
* (эмпирика, эталона Word 300 dpi для этого типа в репо нет); менять
* только вместе с StockPainterTest.
*
* Регрессия — StockPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
final class StockPainter {
/** c:hiLowLines — серый 0xA6A6A6 (дефолт Word). */
static final Color HI_LOW_COLOR = new Color(0xA6, 0xA6, 0xA6);
/** c:upBars — зелёный 0x70AD47 (дефолт Word). */
static final Color UP_FILL = new Color(0x70, 0xAD, 0x47);
/** c:downBars — красный 0xC00000 (дефолт Word). */
static final Color DOWN_FILL = new Color(0xC0, 0x00, 0x00);
/** c:dropLines — светло-серый 0xD9D9D9 (дефолт Word). */
static final Color DROP_COLOR = new Color(0xD9, 0xD9, 0xD9);
/** Линия закрытия рисуется только из двух и более точек. */
private static final int MIN_POLYLINE_POINTS = 2;
private StockPainter() {
}
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
int nCat = 0;
for (ChartSpec.Series s : spec.series) {
nCat = Math.max(nCat, s.values.size());
}
if (spec.series.isEmpty() || nCat == 0) {
return;
}
List<String> cats = CartesianPainter.categoriesOf(spec, nCat);
ChartSpec.AxisSpec valAxis = spec.valAxis != null
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null
? spec.catAxis : new ChartSpec.AxisSpec();
double[] range = ChartRenderer.valueRange(spec);
double[] bounds = ChartRenderer.axisBounds(valAxis, range[0], range[1], true);
double lo = bounds[0];
double hi = bounds[1];
double unit = bounds[2];
DrawMlText.Style valStyle = valAxis.labelStyle;
DrawMlText.Style catStyle = catAxis.labelStyle;
// Поля под подписи осей — как у вертикального графика CartesianPainter.
double catGutter = (cats.isEmpty() ? 0
: catStyle != null ? DrawMlText.textHeight(catStyle) : 0) + 6;
List<String> valLabels = new ArrayList<>();
for (double v = lo; v <= hi + unit / 2; v += unit) {
valLabels.add(ChartRenderer.formatValue(v, valAxis.numFmt));
}
double valGutter = 8;
if (valStyle != null) {
for (String l : valLabels) {
valGutter = Math.max(valGutter, DrawMlText.textWidth(l, valStyle) + 8);
}
}
Rectangle2D plot = new Rectangle2D.Double(box.getX() + valGutter, box.getY(),
Math.max(10, box.getWidth() - valGutter),
Math.max(10, box.getHeight() - catGutter));
if (valAxis.gridlines && !valAxis.deleted) {
g.setColor(valAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
for (double v = lo; v <= hi + unit / 2; v += unit) {
double y = plot.getY() + (1 - (v - lo) / (hi - lo)) * plot.getHeight();
g.draw(new Line2D.Double(plot.getX(), y,
plot.getX() + plot.getWidth(), y));
}
}
// hiLowLines: под рядами, чтобы линии не затирались.
if (spec.hiLowLines) {
g.setColor(HI_LOW_COLOR);
g.setStroke(new BasicStroke(1.0f));
for (int i = 0; i < nCat; i++) {
double min = Double.MAX_VALUE;
double max = -Double.MAX_VALUE;
for (ChartSpec.Series s : spec.series) {
Double v = i < s.values.size() ? s.values.get(i) : null;
if (v != null) {
min = Math.min(min, v);
max = Math.max(max, v);
}
}
if (min > max || min == max) {
continue;
}
double x = catPos(i, nCat, plot);
g.draw(new Line2D.Double(x, valuePos(max, lo, hi, plot),
x, valuePos(min, lo, hi, plot)));
}
}
// upDownBars: между первым и последним рядом категории.
if (spec.upDownBars && spec.series.size() >= 2) {
ChartSpec.Series first = spec.series.get(0);
ChartSpec.Series last = spec.series.get(spec.series.size() - 1);
double w = plot.getWidth() / nCat * 100.0 / (100.0 + spec.upDownGapWidth);
for (int i = 0; i < nCat; i++) {
Double a = i < first.values.size() ? first.values.get(i) : null;
Double b = i < last.values.size() ? last.values.get(i) : null;
if (a == null || b == null || a.equals(b)) {
continue;
}
double x = catPos(i, nCat, plot);
double yA = valuePos(a, lo, hi, plot);
double yB = valuePos(b, lo, hi, plot);
g.setColor(b > a
? (spec.upFill != null ? spec.upFill : UP_FILL)
: spec.downFill != null ? spec.downFill : DOWN_FILL);
g.fill(new Rectangle2D.Double(x - w / 2, Math.min(yA, yB),
w, Math.abs(yB - yA)));
}
}
// Ряды-линии (маркеры — по c:marker ряда, как у LINE).
for (int si = 0; si < spec.series.size(); si++) {
ChartSpec.Series s = spec.series.get(si);
Color c = s.lineColor != null ? s.lineColor : s.fillAt(si, palette);
List<Double> xs = new ArrayList<>();
List<Double> ys = new ArrayList<>();
for (int i = 0; i < s.values.size(); i++) {
Double v = s.values.get(i);
if (v == null) {
continue;
}
xs.add(catPos(i, nCat, plot));
ys.add(valuePos(v, lo, hi, plot));
}
if (spec.dropLines) {
g.setColor(DROP_COLOR);
g.setStroke(new BasicStroke(0.75f));
double base = plot.getY() + plot.getHeight();
for (int i = 0; i < xs.size(); i++) {
g.draw(new Line2D.Double(xs.get(i), ys.get(i), xs.get(i), base));
}
}
if (xs.size() >= MIN_POLYLINE_POINTS) {
g.setColor(c);
g.setStroke(new BasicStroke((float) (s.lineWidth > 0 ? s.lineWidth : 2.25),
BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.draw(ChartRenderer.polyline(xs, ys, false));
}
if (s.marker) {
for (int i = 0; i < xs.size(); i++) {
CartesianPainter.drawMarker(g, xs.get(i), ys.get(i), false, c);
}
}
}
// Линия категории и подписи.
if (catAxis.axisLineColor != null && !catAxis.deleted) {
g.setColor(catAxis.axisLineColor);
g.setStroke(new BasicStroke((float) Math.max(0.5, catAxis.axisLineWidth)));
double y = plot.getY() + plot.getHeight();
g.draw(new Line2D.Double(plot.getX(), y, plot.getX() + plot.getWidth(), y));
}
if (catStyle != null) {
double h = DrawMlText.textHeight(catStyle) + 2;
double slot = plot.getWidth() / nCat;
for (int i = 0; i < nCat; i++) {
String label = cats.get(i);
if (label.isEmpty()) {
continue;
}
double w = DrawMlText.textWidth(label, catStyle);
if (w > slot * 1.15) {
continue;
}
double cx = plot.getX() + plot.getWidth() * (i + 0.5) / nCat;
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, catStyle, "ctr")),
new Rectangle2D.Double(cx - w / 2, plot.getY() + plot.getHeight() + 3,
w, h), "ctr", "t", 1.0);
}
}
if (valStyle != null) {
double h = DrawMlText.textHeight(valStyle) + 2;
for (int i = 0; i < valLabels.size(); i++) {
double t = valLabels.size() == 1 ? 0 : i / (double) (valLabels.size() - 1);
String label = valLabels.get(i);
double w = DrawMlText.textWidth(label, valStyle);
double y = plot.getY() + plot.getHeight() * (1 - t);
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, valStyle, "r")),
new Rectangle2D.Double(plot.getX() - w - 6, y - h / 2, w, h),
"r", "ctr", 1.0);
}
}
}
private static double valuePos(double v, double lo, double hi, Rectangle2D plot) {
return plot.getY() + (1 - (v - lo) / (hi - lo)) * plot.getHeight();
}
private static double catPos(int i, int n, Rectangle2D plot) {
return plot.getX() + plot.getWidth() * (i + 0.5) / n;
}
}
@@ -0,0 +1,261 @@
package ru.pjandro.wordpdf.internal.chart;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
/**
* Поверхностная диаграмма без объёма (c:surfaceChart, ECMA-376 §21.2.2.204):
* «отображает взаимосвязь между категориями и осью значений» — то есть
* рисуется в системе координат «категория × значение»: ось значений слева,
* категории снизу. Каждый ряд — ломаная через категории; лист поверхности
* идёт от переднего ряда к задним, и на экране виден торцом: полосы между
* соседними ломаными красятся контурными полосами высот (c:bandFmts,
* §21.2.2.13 — индексация от низкого к высокого; без bandFmts — палитра),
* передняя стенка от пола до ряда 0 — полосой значения переднего края.
* c:wireframe (§21.2.2.205) — вместо заливок сетка из ломаных рядов и
* линий по категориям.
*
* Регрессия — Surface2dPainterTest, фикстура samples/chart-types.docx
* (WordPdfConverterTest#chartTypes_allTypesRenderAsImages).
*/
final class Surface2dPainter {
private Surface2dPainter() {
}
/** Отрезок полосы короче этого не рисуется (эпсилон float-сравнения). */
private static final double MIN_SEGMENT = 1e-9;
static void paint(Graphics2D g, ChartSpec spec, Rectangle2D box, List<Color> palette) {
int nSer = spec.series.size();
int nCat = 0;
for (ChartSpec.Series s : spec.series) {
nCat = Math.max(nCat, s.values.size());
}
if (nSer < 2 || nCat < 2) {
return;
}
double[][] z = new double[nSer][nCat];
double min = Double.MAX_VALUE;
double max = -Double.MAX_VALUE;
for (int r = 0; r < nSer; r++) {
List<Double> vals = spec.series.get(r).values;
for (int c = 0; c < nCat; c++) {
double v = c < vals.size() && vals.get(c) != null ? vals.get(c) : 0;
z[r][c] = v;
min = Math.min(min, v);
max = Math.max(max, v);
}
}
ChartSpec.AxisSpec valAxis = spec.valAxis != null
? spec.valAxis : new ChartSpec.AxisSpec();
ChartSpec.AxisSpec catAxis = spec.catAxis != null
? spec.catAxis : new ChartSpec.AxisSpec();
double[] bounds = ChartRenderer.axisBounds(valAxis, min, max);
double lo = bounds[0];
double hi = bounds[1];
double unit = bounds[2];
int bandCount = Math.max(1, (int) Math.ceil((hi - lo) / unit - 1e-9));
List<Color> bands = spec.bandColors.isEmpty() ? palette : spec.bandColors;
// Поля под подписи осей — та же auto-layout-эвристика, что у
// CartesianPainter (подписи значений слева, категорий снизу).
List<String> cats = CartesianPainter.categoriesOf(spec, nCat);
DrawMlText.Style valStyle = valAxis.labelStyle;
DrawMlText.Style catStyle = catAxis.labelStyle;
List<String> valLabels = new ArrayList<>();
for (double v = lo; v <= hi + unit / 2; v += unit) {
valLabels.add(ChartRenderer.formatValue(v, valAxis.numFmt));
}
double catGutter = catStyle != null ? DrawMlText.textHeight(catStyle) + 6 : 6;
double valGutter = 8;
if (valStyle != null) {
for (String l : valLabels) {
valGutter = Math.max(valGutter, DrawMlText.textWidth(l, valStyle) + 8);
}
}
Rectangle2D plot = new Rectangle2D.Double(
box.getX() + valGutter, box.getY(),
Math.max(10, box.getWidth() - valGutter),
Math.max(10, box.getHeight() - catGutter));
// Сетка по делениям оси значений — под поверхностью.
if (valAxis.gridlines && !valAxis.deleted) {
g.setColor(valAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
for (double v = lo; v <= hi + unit / 2; v += unit) {
double y = yOf(v, lo, hi, plot);
g.draw(new Line2D.Double(plot.getX(), y,
plot.getX() + plot.getWidth(), y));
}
}
if (spec.wireframe) {
drawWireframe(g, z, nSer, nCat, lo, hi, plot, valAxis);
} else {
drawContour(g, z, nSer, nCat, lo, hi, unit, bandCount, bands, plot);
}
// Оси поверх: линия категории и подписи.
if (catAxis.axisLineColor != null && !catAxis.deleted) {
g.setColor(catAxis.axisLineColor);
g.setStroke(new BasicStroke((float) Math.max(0.5, catAxis.axisLineWidth)));
double y = plot.getY() + plot.getHeight();
g.draw(new Line2D.Double(plot.getX(), y,
plot.getX() + plot.getWidth(), y));
}
drawCategoryLabels(g, cats, plot, catStyle);
drawValueLabels(g, valLabels, plot, valStyle, lo, hi);
}
/**
* Контурная заливка: по вертикальным срезам листа. На срезе x лист
* занимает вертикальные промежутки между соседними ломаными (ряд r и
* r+1) плюс переднюю стенку [пол, ряд 0]; промежуток режется по
* границам полос высот, каждая часть красится своей полосой.
*/
private static void drawContour(Graphics2D g, double[][] z, int nSer, int nCat,
double lo, double hi, double unit, int bandCount,
List<Color> bands, Rectangle2D plot) {
double step = Math.max(0.4, plot.getWidth() / 400.0);
// Без сглаживания: соседние колонки-заливки иначе дают полупрозрачные
// стыки-«полоски» (границы полос меняются от колонки к колонке).
Object oldAA = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
for (double x = plot.getX(); x < plot.getX() + plot.getWidth(); x += step) {
double w = Math.min(step + 0.6, plot.getX() + plot.getWidth() - x + 0.6);
double[] h = new double[nSer];
for (int r = 0; r < nSer; r++) {
h[r] = interp(z[r], x, plot, nCat);
}
// Задние полосы — первыми, передняя стенка перекрывает всё снизу.
for (int r = nSer - 2; r >= 0; r--) {
double v0 = Math.min(h[r], h[r + 1]);
double v1 = Math.max(h[r], h[r + 1]);
int k0 = Math.max(0, Math.min(bandCount - 1, (int) Math.floor((v0 - lo) / unit)));
int k1 = Math.max(0, Math.min(bandCount - 1, (int) Math.floor((v1 - lo) / unit)));
for (int k = k0; k <= k1; k++) {
double segLo = Math.max(v0, lo + k * unit);
double segHi = Math.min(v1, lo + (k + 1) * unit);
if (segHi - segLo <= MIN_SEGMENT) {
continue;
}
g.setColor(bands.get(k % bands.size()));
double yTop = yOf(segHi, lo, hi, plot);
g.fill(new Rectangle2D.Double(x, yTop, w,
yOf(segLo, lo, hi, plot) - yTop));
}
}
double front = h[0];
if (front > lo) {
int k = Math.max(0, Math.min(bandCount - 1,
(int) Math.floor((front - lo) / unit)));
g.setColor(bands.get(k % bands.size()));
double yTop = yOf(front, lo, hi, plot);
g.fill(new Rectangle2D.Double(x, yTop, w,
plot.getY() + plot.getHeight() - yTop));
}
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldAA);
}
/** c:wireframe: сетка листа — ломаные рядов + линии по категориям. */
private static void drawWireframe(Graphics2D g, double[][] z, int nSer, int nCat,
double lo, double hi, Rectangle2D plot,
ChartSpec.AxisSpec valAxis) {
g.setColor(valAxis.gridColor);
g.setStroke(new BasicStroke(0.6f));
for (int r = 0; r < nSer; r++) {
Path2D p = new Path2D.Double();
for (int c = 0; c < nCat; c++) {
double x = xOf(c, plot, nCat);
double y = yOf(z[r][c], lo, hi, plot);
if (c == 0) {
p.moveTo(x, y);
} else {
p.lineTo(x, y);
}
}
g.draw(p);
}
for (int c = 0; c < nCat; c++) {
double x = xOf(c, plot, nCat);
double yTop = yOf(z[nSer - 1][c], lo, hi, plot);
double yBot = yOf(z[0][c], lo, hi, plot);
g.draw(new Line2D.Double(x, Math.min(yTop, yBot), x, Math.max(yTop, yBot)));
}
}
/** Высота листа на срезе x: линейная интерполяция ломаной ряда. */
private static double interp(double[] row, double x, Rectangle2D plot, int nCat) {
double t = (x - plot.getX()) / plot.getWidth() * (nCat - 1);
int c = (int) Math.floor(t);
if (c < 0) {
return row[0];
}
if (c >= nCat - 1) {
return row[nCat - 1];
}
double f = t - c;
return row[c] + (row[c + 1] - row[c]) * f;
}
private static double xOf(int c, Rectangle2D plot, int nCat) {
return plot.getX() + plot.getWidth() * c / (nCat - 1);
}
private static double yOf(double v, double lo, double hi, Rectangle2D plot) {
return plot.getY() + (1 - (v - lo) / (hi - lo)) * plot.getHeight();
}
private static void drawCategoryLabels(Graphics2D g, List<String> cats,
Rectangle2D plot, DrawMlText.Style style) {
if (style == null || cats.isEmpty()) {
return;
}
int n = cats.size();
double h = DrawMlText.textHeight(style) + 2;
double slot = plot.getWidth() / n;
for (int i = 0; i < n; i++) {
String label = cats.get(i);
if (label.isEmpty()) {
continue;
}
double cx = plot.getX() + plot.getWidth() * (i + 0.5) / n;
double w = DrawMlText.textWidth(label, style);
if (w > slot * 1.15) {
continue;
}
DrawMlText.paint(g, List.of(new DrawMlText.Paragraph(label, style, "ctr")),
new Rectangle2D.Double(cx - w / 2, plot.getY() + plot.getHeight() + 3,
w, h),
"ctr", "t", 1.0);
}
}
private static void drawValueLabels(Graphics2D g, List<String> labels,
Rectangle2D plot, DrawMlText.Style style,
double lo, double hi) {
if (style == null) {
return;
}
double h = DrawMlText.textHeight(style) + 2;
for (int i = 0; i < labels.size(); i++) {
double v = lo + (hi - lo) * i / Math.max(1, labels.size() - 1);
double y = yOf(v, lo, hi, plot);
DrawMlText.paint(g,
List.of(new DrawMlText.Paragraph(labels.get(i), style, "r")),
new Rectangle2D.Double(plot.getX() - 6, y - h / 2,
Math.max(10, DrawMlText.textWidth(labels.get(i), style)), h),
"r", "ctr", 1.0);
}
}
}