js-draw 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.eslintrc.js +1 -0
  2. package/CHANGELOG.md +3 -0
  3. package/dist/bundle.js +2 -2
  4. package/dist/bundledStyles.js +1 -1
  5. package/dist/cjs/src/Color4.js +3 -3
  6. package/dist/cjs/src/Editor.js +5 -5
  7. package/dist/cjs/src/SVGLoader.js +69 -7
  8. package/dist/cjs/src/Viewport.d.ts +2 -0
  9. package/dist/cjs/src/Viewport.js +6 -2
  10. package/dist/cjs/src/components/{ImageBackground.d.ts → BackgroundComponent.d.ts} +23 -3
  11. package/dist/cjs/src/components/BackgroundComponent.js +309 -0
  12. package/dist/cjs/src/components/Stroke.js +1 -1
  13. package/dist/cjs/src/components/TextComponent.d.ts +1 -13
  14. package/dist/cjs/src/components/TextComponent.js +1 -1
  15. package/dist/cjs/src/components/lib.d.ts +2 -2
  16. package/dist/cjs/src/components/lib.js +2 -2
  17. package/dist/cjs/src/components/util/StrokeSmoother.js +25 -15
  18. package/dist/cjs/src/localizations/de.js +1 -1
  19. package/dist/cjs/src/localizations/es.js +1 -1
  20. package/dist/cjs/src/math/Path.js +1 -1
  21. package/dist/cjs/src/math/polynomial/QuadraticBezier.d.ts +28 -0
  22. package/dist/cjs/src/math/polynomial/QuadraticBezier.js +115 -0
  23. package/dist/cjs/src/math/polynomial/solveQuadratic.d.ts +6 -0
  24. package/dist/cjs/src/math/polynomial/solveQuadratic.js +36 -0
  25. package/dist/cjs/src/rendering/renderers/CanvasRenderer.js +5 -3
  26. package/dist/cjs/src/rendering/renderers/SVGRenderer.js +15 -6
  27. package/dist/cjs/src/toolbar/localization.d.ts +2 -1
  28. package/dist/cjs/src/toolbar/localization.js +2 -1
  29. package/dist/cjs/src/toolbar/widgets/DocumentPropertiesWidget.d.ts +5 -0
  30. package/dist/cjs/src/toolbar/widgets/DocumentPropertiesWidget.js +77 -2
  31. package/dist/cjs/src/toolbar/widgets/PenToolWidget.js +1 -1
  32. package/dist/cjs/src/tools/FindTool.js +1 -1
  33. package/dist/cjs/src/tools/SoundUITool.js +1 -1
  34. package/dist/mjs/src/Color4.mjs +3 -3
  35. package/dist/mjs/src/Editor.mjs +4 -4
  36. package/dist/mjs/src/SVGLoader.mjs +68 -6
  37. package/dist/mjs/src/Viewport.d.ts +2 -0
  38. package/dist/mjs/src/Viewport.mjs +6 -2
  39. package/dist/mjs/src/components/{ImageBackground.d.ts → BackgroundComponent.d.ts} +23 -3
  40. package/dist/mjs/src/components/BackgroundComponent.mjs +279 -0
  41. package/dist/mjs/src/components/Stroke.mjs +1 -1
  42. package/dist/mjs/src/components/TextComponent.d.ts +1 -13
  43. package/dist/mjs/src/components/TextComponent.mjs +1 -1
  44. package/dist/mjs/src/components/lib.d.ts +2 -2
  45. package/dist/mjs/src/components/lib.mjs +2 -2
  46. package/dist/mjs/src/components/util/StrokeSmoother.mjs +25 -15
  47. package/dist/mjs/src/localizations/de.mjs +1 -1
  48. package/dist/mjs/src/localizations/es.mjs +1 -1
  49. package/dist/mjs/src/math/Path.mjs +1 -1
  50. package/dist/mjs/src/math/polynomial/QuadraticBezier.d.ts +28 -0
  51. package/dist/mjs/src/math/polynomial/QuadraticBezier.mjs +109 -0
  52. package/dist/mjs/src/math/polynomial/solveQuadratic.d.ts +6 -0
  53. package/dist/mjs/src/math/polynomial/solveQuadratic.mjs +34 -0
  54. package/dist/mjs/src/rendering/renderers/CanvasRenderer.mjs +5 -3
  55. package/dist/mjs/src/rendering/renderers/SVGRenderer.mjs +15 -6
  56. package/dist/mjs/src/toolbar/localization.d.ts +2 -1
  57. package/dist/mjs/src/toolbar/localization.mjs +2 -1
  58. package/dist/mjs/src/toolbar/widgets/DocumentPropertiesWidget.d.ts +5 -0
  59. package/dist/mjs/src/toolbar/widgets/DocumentPropertiesWidget.mjs +54 -2
  60. package/dist/mjs/src/toolbar/widgets/PenToolWidget.mjs +1 -1
  61. package/dist/mjs/src/tools/FindTool.mjs +1 -1
  62. package/dist/mjs/src/tools/SoundUITool.mjs +1 -1
  63. package/jest.config.js +1 -1
  64. package/package.json +14 -14
  65. package/dist/cjs/src/components/ImageBackground.js +0 -146
  66. package/dist/mjs/src/components/ImageBackground.mjs +0 -139
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.backgroundTypeToClassNameMap = exports.imageBackgroundNonAutomaticSecondaryColorCSSClassName = exports.imageBackgroundGridSizeCSSPrefix = exports.imageBackgroundCSSClassName = exports.BackgroundType = void 0;
30
+ const Color4_1 = __importDefault(require("../Color4"));
31
+ const EditorImage_1 = require("../EditorImage");
32
+ const Rect2_1 = __importDefault(require("../math/Rect2"));
33
+ const AbstractComponent_1 = __importDefault(require("./AbstractComponent"));
34
+ const RestylableComponent_1 = require("./RestylableComponent");
35
+ const Path_1 = __importStar(require("../math/Path"));
36
+ const Vec2_1 = require("../math/Vec2");
37
+ const Viewport_1 = __importDefault(require("../Viewport"));
38
+ const rounding_1 = require("../math/rounding");
39
+ var BackgroundType;
40
+ (function (BackgroundType) {
41
+ BackgroundType[BackgroundType["SolidColor"] = 0] = "SolidColor";
42
+ BackgroundType[BackgroundType["Grid"] = 1] = "Grid";
43
+ BackgroundType[BackgroundType["None"] = 2] = "None";
44
+ })(BackgroundType = exports.BackgroundType || (exports.BackgroundType = {}));
45
+ exports.imageBackgroundCSSClassName = 'js-draw-image-background';
46
+ // Class name prefix indicating the size of the background's grid cells (if present).
47
+ exports.imageBackgroundGridSizeCSSPrefix = 'js-draw-image-background-grid-';
48
+ // Flag included in rendered SVGs (etc) that indicates that the secondary color of the
49
+ // background has been manually set.
50
+ exports.imageBackgroundNonAutomaticSecondaryColorCSSClassName = 'js-draw-image-background-non-automatic-secondary-color';
51
+ exports.backgroundTypeToClassNameMap = {
52
+ [BackgroundType.Grid]: 'js-draw-image-background-grid',
53
+ [BackgroundType.SolidColor]: exports.imageBackgroundCSSClassName,
54
+ [BackgroundType.None]: '',
55
+ };
56
+ // Represents the background of the editor's canvas.
57
+ class BackgroundComponent extends AbstractComponent_1.default {
58
+ constructor(backgroundType, mainColor) {
59
+ super('image-background', 0);
60
+ this.backgroundType = backgroundType;
61
+ this.mainColor = mainColor;
62
+ this.viewportSizeChangeListener = null;
63
+ this.gridSize = Viewport_1.default.getGridSize(2);
64
+ this.gridStrokeWidth = 0.7;
65
+ this.secondaryColor = null;
66
+ // eslint-disable-next-line @typescript-eslint/prefer-as-const
67
+ this.isRestylableComponent = true;
68
+ this.contentBBox = Rect2_1.default.empty;
69
+ }
70
+ static ofGrid(backgroundColor, gridSize, gridColor, gridStrokeWidth) {
71
+ const background = new BackgroundComponent(BackgroundType.Grid, backgroundColor);
72
+ if (gridSize !== undefined) {
73
+ background.gridSize = gridSize;
74
+ }
75
+ if (gridColor !== undefined) {
76
+ background.secondaryColor = gridColor;
77
+ }
78
+ if (gridStrokeWidth !== undefined) {
79
+ background.gridStrokeWidth = gridStrokeWidth;
80
+ }
81
+ return background;
82
+ }
83
+ getBackgroundType() {
84
+ return this.backgroundType;
85
+ }
86
+ // @internal
87
+ getMainColor() {
88
+ return this.mainColor;
89
+ }
90
+ // @internal
91
+ getSecondaryColor() {
92
+ return this.secondaryColor;
93
+ }
94
+ // @internal
95
+ getGridSize() {
96
+ return this.gridSize;
97
+ }
98
+ getStyle() {
99
+ let color = this.mainColor;
100
+ if (this.backgroundType === BackgroundType.None) {
101
+ color = undefined;
102
+ }
103
+ return {
104
+ color,
105
+ };
106
+ }
107
+ updateStyle(style) {
108
+ return (0, RestylableComponent_1.createRestyleComponentCommand)(this.getStyle(), style, this);
109
+ }
110
+ // @internal
111
+ forceStyle(style, editor) {
112
+ const fill = style.color;
113
+ if (!fill) {
114
+ return;
115
+ }
116
+ this.mainColor = fill;
117
+ // A solid background and transparent fill is equivalent to no background.
118
+ if (fill.eq(Color4_1.default.transparent) && this.backgroundType === BackgroundType.SolidColor) {
119
+ this.backgroundType = BackgroundType.None;
120
+ }
121
+ else if (this.backgroundType === BackgroundType.None) {
122
+ this.backgroundType = BackgroundType.SolidColor;
123
+ }
124
+ if (editor) {
125
+ editor.image.queueRerenderOf(this);
126
+ editor.queueRerender();
127
+ }
128
+ }
129
+ onAddToImage(image) {
130
+ if (this.viewportSizeChangeListener) {
131
+ console.warn('onAddToImage called when background is already in an image');
132
+ this.onRemoveFromImage();
133
+ }
134
+ this.viewportSizeChangeListener = image.notifier.on(EditorImage_1.EditorImageEventType.ExportViewportChanged, () => {
135
+ this.recomputeBBox(image);
136
+ });
137
+ this.recomputeBBox(image);
138
+ }
139
+ onRemoveFromImage() {
140
+ var _a;
141
+ (_a = this.viewportSizeChangeListener) === null || _a === void 0 ? void 0 : _a.remove();
142
+ this.viewportSizeChangeListener = null;
143
+ }
144
+ recomputeBBox(image) {
145
+ const importExportRect = image.getImportExportViewport().visibleRect;
146
+ if (!this.contentBBox.eq(importExportRect)) {
147
+ this.contentBBox = importExportRect;
148
+ // Re-render this if already added to the EditorImage.
149
+ image.queueRerenderOf(this);
150
+ }
151
+ }
152
+ generateGridPath(visibleRect) {
153
+ var _a, _b;
154
+ const targetRect = (_b = (_a = visibleRect === null || visibleRect === void 0 ? void 0 : visibleRect.grownBy(this.gridStrokeWidth)) === null || _a === void 0 ? void 0 : _a.intersection(this.contentBBox)) !== null && _b !== void 0 ? _b : this.contentBBox;
155
+ const roundDownToGrid = (coord) => Math.floor(coord / this.gridSize) * this.gridSize;
156
+ const roundUpToGrid = (coord) => Math.ceil(coord / this.gridSize) * this.gridSize;
157
+ const startY = roundUpToGrid(targetRect.y);
158
+ const endY = roundDownToGrid(targetRect.y + targetRect.h);
159
+ const startX = roundUpToGrid(targetRect.x);
160
+ const endX = roundDownToGrid(targetRect.x + targetRect.w);
161
+ const result = [];
162
+ // Don't generate grids with a huge number of rows/columns -- such grids
163
+ // take a long time to render and are likely invisible due to the number of
164
+ // cells.
165
+ const rowCount = (endY - startY) / this.gridSize;
166
+ const colCount = (endX - startX) / this.gridSize;
167
+ const maxGridCols = 1000;
168
+ const maxGridRows = 1000;
169
+ if (rowCount > maxGridRows || colCount > maxGridCols) {
170
+ return Path_1.default.empty;
171
+ }
172
+ const startPoint = Vec2_1.Vec2.of(targetRect.x, startY);
173
+ for (let y = startY; y <= endY; y += this.gridSize) {
174
+ result.push({
175
+ kind: Path_1.PathCommandType.MoveTo,
176
+ point: Vec2_1.Vec2.of(targetRect.x, y),
177
+ });
178
+ result.push({
179
+ kind: Path_1.PathCommandType.LineTo,
180
+ point: Vec2_1.Vec2.of(targetRect.x + targetRect.w, y),
181
+ });
182
+ }
183
+ for (let x = startX; x <= endX; x += this.gridSize) {
184
+ result.push({
185
+ kind: Path_1.PathCommandType.MoveTo,
186
+ point: Vec2_1.Vec2.of(x, targetRect.y),
187
+ });
188
+ result.push({
189
+ kind: Path_1.PathCommandType.LineTo,
190
+ point: Vec2_1.Vec2.of(x, targetRect.y + targetRect.h)
191
+ });
192
+ }
193
+ return new Path_1.default(startPoint, result);
194
+ }
195
+ render(canvas, visibleRect) {
196
+ if (this.backgroundType === BackgroundType.None) {
197
+ return;
198
+ }
199
+ const clip = true;
200
+ canvas.startObject(this.contentBBox, clip);
201
+ if (this.backgroundType === BackgroundType.SolidColor || this.backgroundType === BackgroundType.Grid) {
202
+ // If the rectangle for this region contains the visible rect,
203
+ // we can fill the entire visible rectangle (which may be more efficient than
204
+ // filling the entire region for this.)
205
+ if (visibleRect) {
206
+ const intersection = visibleRect.intersection(this.contentBBox);
207
+ if (intersection) {
208
+ canvas.fillRect(intersection, this.mainColor);
209
+ }
210
+ }
211
+ else {
212
+ canvas.fillRect(this.contentBBox, this.mainColor);
213
+ }
214
+ }
215
+ if (this.backgroundType === BackgroundType.Grid) {
216
+ let gridColor = this.secondaryColor;
217
+ gridColor !== null && gridColor !== void 0 ? gridColor : (gridColor = Color4_1.default.ofRGBA(1 - this.mainColor.r, 1 - this.mainColor.g, 1 - this.mainColor.b, 0.2));
218
+ // If the background fill is completely transparent, ensure visibility on otherwise light
219
+ // and dark backgrounds.
220
+ if (this.mainColor.a === 0) {
221
+ gridColor = Color4_1.default.ofRGBA(0.5, 0.5, 0.5, 0.2);
222
+ }
223
+ const style = {
224
+ fill: Color4_1.default.transparent,
225
+ stroke: { width: this.gridStrokeWidth, color: gridColor }
226
+ };
227
+ canvas.drawPath(this.generateGridPath(visibleRect).toRenderable(style));
228
+ }
229
+ const backgroundTypeCSSClass = exports.backgroundTypeToClassNameMap[this.backgroundType];
230
+ const classNames = [exports.imageBackgroundCSSClassName];
231
+ if (backgroundTypeCSSClass !== exports.imageBackgroundCSSClassName) {
232
+ classNames.push(backgroundTypeCSSClass);
233
+ const gridSizeStr = (0, rounding_1.toRoundedString)(this.gridSize).replace(/[.]/g, 'p');
234
+ classNames.push(exports.imageBackgroundGridSizeCSSPrefix + gridSizeStr);
235
+ }
236
+ if (this.secondaryColor !== null) {
237
+ classNames.push(exports.imageBackgroundNonAutomaticSecondaryColorCSSClassName);
238
+ }
239
+ canvas.endObject(this.getLoadSaveData(), classNames);
240
+ }
241
+ intersects(lineSegment) {
242
+ return this.contentBBox.getEdges().some(edge => edge.intersects(lineSegment));
243
+ }
244
+ isSelectable() {
245
+ return false;
246
+ }
247
+ isBackground() {
248
+ return true;
249
+ }
250
+ serializeToJSON() {
251
+ var _a;
252
+ return {
253
+ mainColor: this.mainColor.toHexString(),
254
+ secondaryColor: (_a = this.secondaryColor) === null || _a === void 0 ? void 0 : _a.toHexString(),
255
+ backgroundType: this.backgroundType,
256
+ gridSize: this.gridSize,
257
+ gridStrokeWidth: this.gridStrokeWidth,
258
+ };
259
+ }
260
+ applyTransformation(_affineTransfm) {
261
+ // Do nothing — it doesn't make sense to transform the background.
262
+ }
263
+ description(localizationTable) {
264
+ if (this.backgroundType === BackgroundType.SolidColor) {
265
+ return localizationTable.filledBackgroundWithColor(this.mainColor.toString());
266
+ }
267
+ else {
268
+ return localizationTable.emptyBackground;
269
+ }
270
+ }
271
+ createClone() {
272
+ return new BackgroundComponent(this.backgroundType, this.mainColor);
273
+ }
274
+ // @internal
275
+ static deserializeFromJSON(json) {
276
+ var _a, _b;
277
+ if (typeof json === 'string') {
278
+ json = JSON.parse(json);
279
+ }
280
+ if (typeof json.mainColor !== 'string') {
281
+ throw new Error('Error deserializing — mainColor must be of type string.');
282
+ }
283
+ let backgroundType;
284
+ const jsonBackgroundType = json.backgroundType;
285
+ if (jsonBackgroundType === BackgroundType.None || jsonBackgroundType === BackgroundType.Grid
286
+ || jsonBackgroundType === BackgroundType.SolidColor) {
287
+ backgroundType = jsonBackgroundType;
288
+ }
289
+ else {
290
+ const exhaustivenessCheck = jsonBackgroundType;
291
+ return exhaustivenessCheck;
292
+ }
293
+ const mainColor = Color4_1.default.fromHex(json.mainColor);
294
+ const secondaryColor = json.secondaryColor ? Color4_1.default.fromHex(json.secondaryColor) : null;
295
+ const gridSize = (_a = json.gridSize) !== null && _a !== void 0 ? _a : undefined;
296
+ const gridStrokeWidth = (_b = json.gridStrokeWidth) !== null && _b !== void 0 ? _b : undefined;
297
+ const result = new BackgroundComponent(backgroundType, mainColor);
298
+ result.secondaryColor = secondaryColor;
299
+ if (gridSize) {
300
+ result.gridSize = gridSize;
301
+ }
302
+ if (gridStrokeWidth) {
303
+ result.gridStrokeWidth = gridStrokeWidth;
304
+ }
305
+ return result;
306
+ }
307
+ }
308
+ exports.default = BackgroundComponent;
309
+ AbstractComponent_1.default.registerComponent('image-background', BackgroundComponent.deserializeFromJSON);
@@ -130,7 +130,7 @@ class Stroke extends AbstractComponent_1.default {
130
130
  if (!bbox.intersects(visibleRect)) {
131
131
  continue;
132
132
  }
133
- const muchBiggerThanVisible = bbox.size.x > visibleRect.size.x * 2 || bbox.size.y > visibleRect.size.y * 2;
133
+ const muchBiggerThanVisible = bbox.size.x > visibleRect.size.x * 3 || bbox.size.y > visibleRect.size.y * 3;
134
134
  if (muchBiggerThanVisible && !part.path.roughlyIntersects(visibleRect, (_b = (_a = part.style.stroke) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 0)) {
135
135
  continue;
136
136
  }
@@ -36,19 +36,7 @@ export default class TextComponent extends AbstractComponent implements Restylea
36
36
  getStyle(): ComponentStyle;
37
37
  updateStyle(style: ComponentStyle): SerializableCommand;
38
38
  forceStyle(style: ComponentStyle, editor: Editor | null): void;
39
- getTextStyle(): {
40
- renderingStyle: {
41
- fill: import("../Color4").default;
42
- stroke: {
43
- color: import("../Color4").default;
44
- width: number;
45
- } | undefined;
46
- };
47
- size: number;
48
- fontFamily: string;
49
- fontWeight?: string | undefined;
50
- fontVariant?: string | undefined;
51
- };
39
+ getTextStyle(): TextRenderingStyle;
52
40
  getBaselinePos(): import("../lib").Vec3;
53
41
  getTransform(): Mat33;
54
42
  protected applyTransformation(affineTransfm: Mat33): void;
@@ -163,7 +163,7 @@ class TextComponent extends AbstractComponent_1.default {
163
163
  editor.queueRerender();
164
164
  }
165
165
  }
166
- // See this.getStyle
166
+ // See {@link getStyle}
167
167
  getTextStyle() {
168
168
  return (0, TextRenderingStyle_1.cloneTextStyle)(this.style);
169
169
  }
@@ -9,5 +9,5 @@ import TextComponent from './TextComponent';
9
9
  import ImageComponent from './ImageComponent';
10
10
  import RestyleableComponent from './RestylableComponent';
11
11
  import { createRestyleComponentCommand, isRestylableComponent, ComponentStyle as RestyleableComponentStyle } from './RestylableComponent';
12
- import ImageBackground from './ImageBackground';
13
- export { Stroke, TextComponent as Text, RestyleableComponent, createRestyleComponentCommand, isRestylableComponent, RestyleableComponentStyle, TextComponent, Stroke as StrokeComponent, ImageBackground as BackgroundComponent, ImageComponent, };
12
+ import BackgroundComponent from './BackgroundComponent';
13
+ export { Stroke, TextComponent as Text, RestyleableComponent, createRestyleComponentCommand, isRestylableComponent, RestyleableComponentStyle, TextComponent, Stroke as StrokeComponent, BackgroundComponent, ImageComponent, };
@@ -39,5 +39,5 @@ exports.ImageComponent = ImageComponent_1.default;
39
39
  const RestylableComponent_1 = require("./RestylableComponent");
40
40
  Object.defineProperty(exports, "createRestyleComponentCommand", { enumerable: true, get: function () { return RestylableComponent_1.createRestyleComponentCommand; } });
41
41
  Object.defineProperty(exports, "isRestylableComponent", { enumerable: true, get: function () { return RestylableComponent_1.isRestylableComponent; } });
42
- const ImageBackground_1 = __importDefault(require("./ImageBackground"));
43
- exports.BackgroundComponent = ImageBackground_1.default;
42
+ const BackgroundComponent_1 = __importDefault(require("./BackgroundComponent"));
43
+ exports.BackgroundComponent = BackgroundComponent_1.default;
@@ -4,10 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.StrokeSmoother = void 0;
7
- const bezier_js_1 = require("bezier-js");
8
7
  const Vec2_1 = require("../../math/Vec2");
9
8
  const Rect2_1 = __importDefault(require("../../math/Rect2"));
10
9
  const LineSegment2_1 = __importDefault(require("../../math/LineSegment2"));
10
+ const QuadraticBezier_1 = __importDefault(require("../../math/polynomial/QuadraticBezier"));
11
11
  // Handles stroke smoothing
12
12
  class StrokeSmoother {
13
13
  constructor(startPoint,
@@ -44,9 +44,9 @@ class StrokeSmoother {
44
44
  if (!this.currentCurve) {
45
45
  return 0;
46
46
  }
47
- const startPt = Vec2_1.Vec2.ofXY(this.currentCurve.points[0]);
48
- const controlPt = Vec2_1.Vec2.ofXY(this.currentCurve.points[1]);
49
- const endPt = Vec2_1.Vec2.ofXY(this.currentCurve.points[2]);
47
+ const startPt = this.currentCurve.p0;
48
+ const controlPt = this.currentCurve.p1;
49
+ const endPt = this.currentCurve.p2;
50
50
  const toControlDist = startPt.minus(controlPt).length();
51
51
  const toEndDist = endPt.minus(controlPt).length();
52
52
  return toControlDist + toEndDist;
@@ -58,7 +58,7 @@ class StrokeSmoother {
58
58
  }
59
59
  this.onCurveAdded(this.currentSegmentToPath());
60
60
  const lastPoint = this.buffer[this.buffer.length - 1];
61
- this.lastExitingVec = Vec2_1.Vec2.ofXY(this.currentCurve.points[2]).minus(Vec2_1.Vec2.ofXY(this.currentCurve.points[1]));
61
+ this.lastExitingVec = this.currentCurve.p2.minus(this.currentCurve.p1);
62
62
  console.assert(this.lastExitingVec.magnitude() !== 0, 'lastExitingVec has zero length!');
63
63
  // Use the last two points to start a new curve (the last point isn't used
64
64
  // in the current curve and we want connected curves to share end points)
@@ -73,13 +73,13 @@ class StrokeSmoother {
73
73
  if (this.currentCurve == null) {
74
74
  throw new Error('Invalid State: currentCurve is null!');
75
75
  }
76
- const startVec = Vec2_1.Vec2.ofXY(this.currentCurve.normal(0)).normalized();
76
+ const startVec = this.currentCurve.normal(0).normalized();
77
77
  if (!isFinite(startVec.magnitude())) {
78
78
  throw new Error(`startVec(${startVec}) is NaN or ∞`);
79
79
  }
80
- const startPt = Vec2_1.Vec2.ofXY(this.currentCurve.get(0));
81
- const endPt = Vec2_1.Vec2.ofXY(this.currentCurve.get(1));
82
- const controlPoint = Vec2_1.Vec2.ofXY(this.currentCurve.points[1]);
80
+ const startPt = this.currentCurve.at(0);
81
+ const endPt = this.currentCurve.at(1);
82
+ const controlPoint = this.currentCurve.p1;
83
83
  return {
84
84
  startPoint: startPt,
85
85
  controlPoint,
@@ -131,7 +131,7 @@ class StrokeSmoother {
131
131
  const p2 = lastPoint.pos.plus((_b = this.lastExitingVec) !== null && _b !== void 0 ? _b : Vec2_1.Vec2.unitX);
132
132
  const p3 = newPoint.pos;
133
133
  // Quadratic Bézier curve
134
- this.currentCurve = new bezier_js_1.Bezier(p1.xy, p2.xy, p3.xy);
134
+ this.currentCurve = new QuadraticBezier_1.default(p1, p2, p3);
135
135
  console.assert(!isNaN(p1.magnitude()) && !isNaN(p2.magnitude()) && !isNaN(p3.magnitude()), 'Expected !NaN');
136
136
  if (this.isFirstSegment) {
137
137
  // The start of a curve often lacks accurate pressure information. Update it.
@@ -182,19 +182,29 @@ class StrokeSmoother {
182
182
  console.assert(!segmentStart.eq(controlPoint, 1e-11), 'Start and control points are equal!');
183
183
  console.assert(!controlPoint.eq(segmentEnd, 1e-11), 'Control and end points are equal!');
184
184
  const prevCurve = this.currentCurve;
185
- this.currentCurve = new bezier_js_1.Bezier(segmentStart.xy, controlPoint.xy, segmentEnd.xy);
186
- if (isNaN(Vec2_1.Vec2.ofXY(this.currentCurve.normal(0)).magnitude())) {
185
+ this.currentCurve = new QuadraticBezier_1.default(segmentStart, controlPoint, segmentEnd);
186
+ if (isNaN(this.currentCurve.normal(0).magnitude())) {
187
187
  console.error('NaN normal at 0. Curve:', this.currentCurve);
188
188
  this.currentCurve = prevCurve;
189
189
  }
190
190
  // Should we start making a new curve? Check whether all buffer points are within
191
191
  // ±strokeWidth of the curve.
192
192
  const curveMatchesPoints = (curve) => {
193
+ let nonMatching = 0;
194
+ const maxNonMatching = 2;
195
+ const minFit = Math.max(Math.min(this.curveStartWidth, this.curveEndWidth) / 3, this.minFitAllowed);
193
196
  for (const point of this.buffer) {
194
- const proj = Vec2_1.Vec2.ofXY(curve.project(point.xy));
195
- const dist = proj.minus(point).magnitude();
196
- const minFit = Math.max(Math.min(this.curveStartWidth, this.curveEndWidth) / 3, this.minFitAllowed);
197
+ let dist = curve.approximateDistance(point);
197
198
  if (dist > minFit || dist > this.maxFitAllowed) {
199
+ // Avoid using the slower .distance
200
+ if (nonMatching >= maxNonMatching - 1) {
201
+ dist = curve.distance(point);
202
+ }
203
+ if (dist > minFit || dist > this.maxFitAllowed) {
204
+ nonMatching++;
205
+ }
206
+ }
207
+ if (nonMatching >= maxNonMatching) {
198
208
  return false;
199
209
  }
200
210
  }
@@ -2,5 +2,5 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const localization_1 = require("../localization");
4
4
  // German localization
5
- const localization = Object.assign(Object.assign({}, localization_1.defaultEditorLocalization), { pen: 'Stift', eraser: 'Radierer', select: 'Auswahl', handTool: 'Verschieben', zoom: 'Vergrößerung', resetView: 'Ansicht zurücksetzen', thicknessLabel: 'Dicke: ', colorLabel: 'Farbe: ', fontLabel: 'Schriftart: ', resizeImageToSelection: 'Bildgröße an Auswahl anpassen', deleteSelection: 'Auswahl löschen', duplicateSelection: 'Auswahl duplizieren', undo: 'Rückgängig', redo: 'Wiederholen', pickColorFromScreen: 'Farbe von Bildschirm auswählen', clickToPickColorAnnouncement: 'Klicke auf den Bildschirm, um eine Farbe auszuwählen', selectionToolKeyboardShortcuts: 'Auswahl-Werkzeug: Verwende die Pfeiltasten, um ausgewählte Elemente zu verschieben und ‚i‘ und ‚o‘, um ihre Größe zu ändern.', touchPanning: 'Ansicht mit Touchscreen verschieben', anyDevicePanning: 'Ansicht mit jedem Eingabegerät verschieben', selectObjectType: 'Objekt-Typ: ', freehandPen: 'Freihand', arrowPen: 'Pfeil', linePen: 'Linie', outlinedRectanglePen: 'Umrissenes Rechteck', filledRectanglePen: 'Ausgefülltes Rechteck', dropdownShown: t => `Dropdown-Menü für ${t} angezeigt`, dropdownHidden: t => `Dropdown-Menü für ${t} versteckt`, zoomLevel: t => `Vergößerung: ${t}%`, colorChangedAnnouncement: t => `Farbe zu ${t} geändert`, penTool: t => `Stift ${t}`, selectionTool: 'Auswahl', eraserTool: 'Radiergummi', touchPanTool: 'Ansicht mit Touchscreen verschieben', twoFingerPanZoomTool: 'Ansicht verschieben und vergrößern', undoRedoTool: 'Rückgängig/Wiederholen', rightClickDragPanTool: 'Rechtsklick-Ziehen', pipetteTool: 'Farbe von Bildschirm auswählen', keyboardPanZoom: 'Tastaturkürzel zum Verschieben/Vergrößern der Ansicht', textTool: 'Text', enterTextToInsert: 'Einzufügender Text', toolEnabledAnnouncement: t => `${t} aktiviert`, toolDisabledAnnouncement: t => `${t} deaktiviert`, updatedViewport: 'Transformierte Ansicht', transformedElements: t => `${t} Element${1 === t ? '' : 'e'} transformiert`, resizeOutputCommand: t => `Bildgröße auf ${t.w}x${t.h} geändert`, addElementAction: t => `${t} hinzugefügt`, eraseAction: (t, e) => `${e} ${t} gelöscht`, duplicateAction: (t, e) => `${e} ${t} dupliziert`, inverseOf: t => `Umkehrung von ${t}`, elements: 'Elemente', erasedNoElements: 'Nichts entfernt', duplicatedNoElements: 'Nichts dupliziert', rotatedBy: t => `${Math.abs(t)} Grad ${t < 0 ? 'im Uhrzeigersinn' : 'gegen den Uhrzeigersinn'} gedreht`, movedLeft: 'Nacht links bewegt', movedUp: 'Nacht oben bewegt', movedDown: 'Nacht unten bewegt', movedRight: 'Nacht rechts bewegt', zoomedOut: 'Ansicht verkleinert', zoomedIn: 'Ansicht vergrößert', selectedElements: t => `${t} Element${1 === t ? '' : 'e'} ausgewählt`, stroke: 'Strich', svgObject: 'SVG-Objekt', text: t => `Text-Objekt: ${t}`, pathNodeCount: t => `Es gibt ${t} sichtbare Pfad-Objekte.`, textNodeCount: t => `Es gibt ${t} sichtbare Text-Knotenpunkte.`, textNode: t => `Text: ${t}`, rerenderAsText: 'Als Text darstellen', accessibilityInputInstructions: 'Drücke ‚t‘, um den Inhalt des Ansichtsfensters als Text zu lesen. Verwende die Pfeiltasten, um die Ansicht zu verschieben, und klicke und ziehe, um Striche zu zeichnen. Drücke ‚w‘ zum Vergrößern und ‚s‘ zum Verkleinern der Ansicht.', loading: t => `Laden ${t}%...`, doneLoading: 'Laden fertig', imageEditor: 'Bild-Editor', undoAnnouncement: t => `Rückgangig gemacht ${t}`, redoAnnouncement: t => `Wiederholt ${t}` });
5
+ const localization = Object.assign(Object.assign({}, localization_1.defaultEditorLocalization), { pen: 'Stift', eraser: 'Radierer', select: 'Auswahl', handTool: 'Verschieben', zoom: 'Vergrößerung', resetView: 'Ansicht zurücksetzen', thicknessLabel: 'Dicke: ', colorLabel: 'Farbe: ', fontLabel: 'Schriftart: ', resizeImageToSelection: 'Bildgröße an Auswahl anpassen', deleteSelection: 'Auswahl löschen', duplicateSelection: 'Auswahl duplizieren', undo: 'Rückgängig', redo: 'Wiederholen', pickColorFromScreen: 'Farbe von Bildschirm auswählen', clickToPickColorAnnouncement: 'Klicke auf den Bildschirm, um eine Farbe auszuwählen', selectionToolKeyboardShortcuts: 'Auswahl-Werkzeug: Verwende die Pfeiltasten, um ausgewählte Elemente zu verschieben und ‚i‘ und ‚o‘, um ihre Größe zu ändern.', touchPanning: 'Ansicht mit Touchscreen verschieben', anyDevicePanning: 'Ansicht mit jedem Eingabegerät verschieben', selectPenType: 'Objekt-Typ: ', freehandPen: 'Freihand', arrowPen: 'Pfeil', linePen: 'Linie', outlinedRectanglePen: 'Umrissenes Rechteck', filledRectanglePen: 'Ausgefülltes Rechteck', dropdownShown: t => `Dropdown-Menü für ${t} angezeigt`, dropdownHidden: t => `Dropdown-Menü für ${t} versteckt`, zoomLevel: t => `Vergößerung: ${t}%`, colorChangedAnnouncement: t => `Farbe zu ${t} geändert`, penTool: t => `Stift ${t}`, selectionTool: 'Auswahl', eraserTool: 'Radiergummi', touchPanTool: 'Ansicht mit Touchscreen verschieben', twoFingerPanZoomTool: 'Ansicht verschieben und vergrößern', undoRedoTool: 'Rückgängig/Wiederholen', rightClickDragPanTool: 'Rechtsklick-Ziehen', pipetteTool: 'Farbe von Bildschirm auswählen', keyboardPanZoom: 'Tastaturkürzel zum Verschieben/Vergrößern der Ansicht', textTool: 'Text', enterTextToInsert: 'Einzufügender Text', toolEnabledAnnouncement: t => `${t} aktiviert`, toolDisabledAnnouncement: t => `${t} deaktiviert`, updatedViewport: 'Transformierte Ansicht', transformedElements: t => `${t} Element${1 === t ? '' : 'e'} transformiert`, resizeOutputCommand: t => `Bildgröße auf ${t.w}x${t.h} geändert`, addElementAction: t => `${t} hinzugefügt`, eraseAction: (t, e) => `${e} ${t} gelöscht`, duplicateAction: (t, e) => `${e} ${t} dupliziert`, inverseOf: t => `Umkehrung von ${t}`, elements: 'Elemente', erasedNoElements: 'Nichts entfernt', duplicatedNoElements: 'Nichts dupliziert', rotatedBy: t => `${Math.abs(t)} Grad ${t < 0 ? 'im Uhrzeigersinn' : 'gegen den Uhrzeigersinn'} gedreht`, movedLeft: 'Nacht links bewegt', movedUp: 'Nacht oben bewegt', movedDown: 'Nacht unten bewegt', movedRight: 'Nacht rechts bewegt', zoomedOut: 'Ansicht verkleinert', zoomedIn: 'Ansicht vergrößert', selectedElements: t => `${t} Element${1 === t ? '' : 'e'} ausgewählt`, stroke: 'Strich', svgObject: 'SVG-Objekt', text: t => `Text-Objekt: ${t}`, pathNodeCount: t => `Es gibt ${t} sichtbare Pfad-Objekte.`, textNodeCount: t => `Es gibt ${t} sichtbare Text-Knotenpunkte.`, textNode: t => `Text: ${t}`, rerenderAsText: 'Als Text darstellen', accessibilityInputInstructions: 'Drücke ‚t‘, um den Inhalt des Ansichtsfensters als Text zu lesen. Verwende die Pfeiltasten, um die Ansicht zu verschieben, und klicke und ziehe, um Striche zu zeichnen. Drücke ‚w‘ zum Vergrößern und ‚s‘ zum Verkleinern der Ansicht.', loading: t => `Laden ${t}%...`, doneLoading: 'Laden fertig', imageEditor: 'Bild-Editor', undoAnnouncement: t => `Rückgangig gemacht ${t}`, redoAnnouncement: t => `Wiederholt ${t}` });
6
6
  exports.default = localization;
@@ -8,7 +8,7 @@ const localization = Object.assign(Object.assign({}, localization_1.defaultEdito
8
8
  loading: (percentage) => `Cargando: ${percentage}%...`, imageEditor: 'Editor de dibujos', undoAnnouncement: (commandDescription) => `${commandDescription} fue deshecho`, redoAnnouncement: (commandDescription) => `${commandDescription} fue rehecho`, undo: 'Deshace', redo: 'Rehace',
9
9
  // Strings for the toolbar
10
10
  // (see src/toolbar/localization.ts)
11
- pen: 'Lapiz', eraser: 'Borrador', select: 'Selecciona', thicknessLabel: 'Tamaño: ', colorLabel: 'Color: ', doneLoading: 'El cargado terminó', fontLabel: 'Fuente: ', anyDevicePanning: 'Mover la pantalla con todo dispotivo', touchPanning: 'Mover la pantalla con un dedo', touchPanTool: 'Instrumento de mover la pantalla con un dedo', outlinedRectanglePen: 'Rectángulo con nada más que un borde', filledRectanglePen: 'Rectángulo sin borde', linePen: 'Línea', arrowPen: 'Flecha', freehandPen: 'Dibuja sin restricción de forma', selectObjectType: 'Forma de dibuja:', handTool: 'Mover', zoom: 'Zoom', resetView: 'Reiniciar vista', resizeImageToSelection: 'Redimensionar la imagen a lo que está seleccionado', deleteSelection: 'Borra la selección', duplicateSelection: 'Duplica la selección', pickColorFromScreen: 'Selecciona un color de la pantalla', clickToPickColorAnnouncement: 'Haga un clic en la pantalla para seleccionar un color', dropdownShown(toolName) {
11
+ pen: 'Lapiz', eraser: 'Borrador', select: 'Selecciona', thicknessLabel: 'Tamaño: ', colorLabel: 'Color: ', doneLoading: 'El cargado terminó', fontLabel: 'Fuente: ', anyDevicePanning: 'Mover la pantalla con todo dispotivo', touchPanning: 'Mover la pantalla con un dedo', touchPanTool: 'Instrumento de mover la pantalla con un dedo', outlinedRectanglePen: 'Rectángulo con nada más que un borde', filledRectanglePen: 'Rectángulo sin borde', linePen: 'Línea', arrowPen: 'Flecha', freehandPen: 'Dibuja sin restricción de forma', selectPenType: 'Forma de dibuja:', handTool: 'Mover', zoom: 'Zoom', resetView: 'Reiniciar vista', resizeImageToSelection: 'Redimensionar la imagen a lo que está seleccionado', deleteSelection: 'Borra la selección', duplicateSelection: 'Duplica la selección', pickColorFromScreen: 'Selecciona un color de la pantalla', clickToPickColorAnnouncement: 'Haga un clic en la pantalla para seleccionar un color', dropdownShown(toolName) {
12
12
  return `Menú por ${toolName} es visible`;
13
13
  }, dropdownHidden: function (toolName) {
14
14
  return `Menú por ${toolName} fue ocultado`;
@@ -347,7 +347,7 @@ class Path {
347
347
  const onlyStroked = strokeWidth > 0 && renderablePath.style.fill.a === 0;
348
348
  // Scale the expanded rect --- the visual equivalent is only close for huge strokes.
349
349
  const expandedRect = visibleRect.grownBy(strokeWidth)
350
- .transformedBoundingBox(Mat33_1.default.scaling2D(2, visibleRect.center));
350
+ .transformedBoundingBox(Mat33_1.default.scaling2D(4, visibleRect.center));
351
351
  // TODO: Handle simplifying very small paths.
352
352
  if (expandedRect.containsRect(path.bbox.grownBy(strokeWidth))) {
353
353
  return renderablePath;
@@ -0,0 +1,28 @@
1
+ import { Point2, Vec2 } from '../Vec2';
2
+ export default class QuadraticBezier {
3
+ readonly p0: Point2;
4
+ readonly p1: Point2;
5
+ readonly p2: Point2;
6
+ private bezierJs;
7
+ constructor(p0: Point2, p1: Point2, p2: Point2);
8
+ /**
9
+ * Returns a component of a quadratic Bézier curve at t, where p0,p1,p2 are either all x or
10
+ * all y components of the target curve.
11
+ */
12
+ private static componentAt;
13
+ private static derivativeComponentAt;
14
+ /**
15
+ * @returns the curve evaluated at `t`.
16
+ */
17
+ at(t: number): Point2;
18
+ derivativeAt(t: number): Point2;
19
+ /**
20
+ * @returns the approximate distance from `point` to this curve.
21
+ */
22
+ approximateDistance(point: Point2): number;
23
+ /**
24
+ * @returns the exact distance from `point` to this.
25
+ */
26
+ distance(point: Point2): number;
27
+ normal(t: number): Vec2;
28
+ }
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const bezier_js_1 = require("bezier-js");
7
+ const Vec2_1 = require("../Vec2");
8
+ const solveQuadratic_1 = __importDefault(require("./solveQuadratic"));
9
+ class QuadraticBezier {
10
+ constructor(p0, p1, p2) {
11
+ this.p0 = p0;
12
+ this.p1 = p1;
13
+ this.p2 = p2;
14
+ this.bezierJs = null;
15
+ }
16
+ /**
17
+ * Returns a component of a quadratic Bézier curve at t, where p0,p1,p2 are either all x or
18
+ * all y components of the target curve.
19
+ */
20
+ static componentAt(t, p0, p1, p2) {
21
+ return p0 + t * (-2 * p0 + 2 * p1) + t * t * (p0 - 2 * p1 + p2);
22
+ }
23
+ static derivativeComponentAt(t, p0, p1, p2) {
24
+ return -2 * p0 + 2 * p1 + 2 * t * (p0 - 2 * p1 + p2);
25
+ }
26
+ /**
27
+ * @returns the curve evaluated at `t`.
28
+ */
29
+ at(t) {
30
+ const p0 = this.p0;
31
+ const p1 = this.p1;
32
+ const p2 = this.p2;
33
+ return Vec2_1.Vec2.of(QuadraticBezier.componentAt(t, p0.x, p1.x, p2.x), QuadraticBezier.componentAt(t, p0.y, p1.y, p2.y));
34
+ }
35
+ derivativeAt(t) {
36
+ const p0 = this.p0;
37
+ const p1 = this.p1;
38
+ const p2 = this.p2;
39
+ return Vec2_1.Vec2.of(QuadraticBezier.derivativeComponentAt(t, p0.x, p1.x, p2.x), QuadraticBezier.derivativeComponentAt(t, p0.y, p1.y, p2.y));
40
+ }
41
+ /**
42
+ * @returns the approximate distance from `point` to this curve.
43
+ */
44
+ approximateDistance(point) {
45
+ // We want to minimize f(t) = |B(t) - p|².
46
+ // Expanding,
47
+ // f(t) = (Bₓ(t) - pₓ)² + (Bᵧ(t) - pᵧ)²
48
+ // ⇒ f'(t) = Dₜ(Bₓ(t) - pₓ)² + Dₜ(Bᵧ(t) - pᵧ)²
49
+ //
50
+ // Considering just one component,
51
+ // Dₜ(Bₓ(t) - pₓ)² = 2(Bₓ(t) - pₓ)(DₜBₓ(t))
52
+ // = 2(Bₓ(t)DₜBₓ(t) - pₓBₓ(t))
53
+ // = 2(p0ₓ + (t)(-2p0ₓ + 2p1ₓ) + (t²)(p0ₓ - 2p1ₓ + p2ₓ) - pₓ)((-2p0ₓ + 2p1ₓ) + 2(t)(p0ₓ - 2p1ₓ + p2ₓ))
54
+ // - (pₓ)((-2p0ₓ + 2p1ₓ) + (t)(p0ₓ - 2p1ₓ + p2ₓ))
55
+ const A = this.p0.x - point.x;
56
+ const B = -2 * this.p0.x + 2 * this.p1.x;
57
+ const C = this.p0.x - 2 * this.p1.x + this.p2.x;
58
+ // Let A = p0ₓ - pₓ, B = -2p0ₓ + 2p1ₓ, C = p0ₓ - 2p1ₓ + p2ₓ. We then have,
59
+ // Dₜ(Bₓ(t) - pₓ)²
60
+ // = 2(A + tB + t²C)(B + 2tC) - (pₓ)(B + 2tC)
61
+ // = 2(AB + tB² + t²BC + 2tCA + 2tCtB + 2tCt²C) - pₓB - pₓ2tC
62
+ // = 2(AB + tB² + 2tCA + t²BC + 2t²CB + 2C²t³) - pₓB - pₓ2tC
63
+ // = 2AB + 2t(B² + 2CA) + 2t²(BC + 2CB) + 4C²t³ - pₓB - pₓ2tC
64
+ // = 2AB + 2t(B² + 2CA - pₓC) + 2t²(BC + 2CB) + 4C²t³ - pₓB
65
+ //
66
+ const D = this.p0.y - point.y;
67
+ const E = -2 * this.p0.y + 2 * this.p1.y;
68
+ const F = this.p0.y - 2 * this.p1.y + this.p2.y;
69
+ // Using D = p0ᵧ - pᵧ, E = -2p0ᵧ + 2p1ᵧ, F = p0ᵧ - 2p1ᵧ + p2ᵧ, we thus have,
70
+ // f'(t) = 2AB + 2t(B² + 2CA - pₓC) + 2t²(BC + 2CB) + 4C²t³ - pₓB
71
+ // + 2DE + 2t(E² + 2FD - pᵧF) + 2t²(EF + 2FE) + 4F²t³ - pᵧE
72
+ const a = 2 * A * B + 2 * D * E - point.x * B - point.y * E;
73
+ const b = 2 * B * B + 2 * E * E + 2 * C * A + 2 * F * D - point.x * C - point.y * F;
74
+ const c = 2 * E * F + 2 * B * C + 2 * C * B + 2 * F * E;
75
+ //const d = 4 * C * C + 4 * F * F;
76
+ // Thus,
77
+ // f'(t) = a + bt + ct² + dt³
78
+ const fDerivAtZero = a;
79
+ const f2ndDerivAtZero = b;
80
+ const f3rdDerivAtZero = 2 * c;
81
+ // Using the first few terms of a Maclaurin series to approximate f'(t),
82
+ // f'(t) ≈ f'(0) + t f''(0) + t² f'''(0) / 2
83
+ let [min1, min2] = (0, solveQuadratic_1.default)(f3rdDerivAtZero / 2, f2ndDerivAtZero, fDerivAtZero);
84
+ // If the quadratic has no solutions, approximate.
85
+ if (isNaN(min1)) {
86
+ min1 = 0.25;
87
+ }
88
+ if (isNaN(min2)) {
89
+ min2 = 0.75;
90
+ }
91
+ const at1 = this.at(min1);
92
+ const at2 = this.at(min2);
93
+ const sqrDist1 = at1.minus(point).magnitudeSquared();
94
+ const sqrDist2 = at2.minus(point).magnitudeSquared();
95
+ const sqrDist3 = this.at(0).minus(point).magnitudeSquared();
96
+ const sqrDist4 = this.at(1).minus(point).magnitudeSquared();
97
+ return Math.sqrt(Math.min(sqrDist1, sqrDist2, sqrDist3, sqrDist4));
98
+ }
99
+ /**
100
+ * @returns the exact distance from `point` to this.
101
+ */
102
+ distance(point) {
103
+ if (!this.bezierJs) {
104
+ this.bezierJs = new bezier_js_1.Bezier([this.p0.xy, this.p1.xy, this.p2.xy]);
105
+ }
106
+ const proj = Vec2_1.Vec2.ofXY(this.bezierJs.project(point.xy));
107
+ const dist = proj.minus(point).magnitude();
108
+ return dist;
109
+ }
110
+ normal(t) {
111
+ const tangent = this.derivativeAt(t);
112
+ return tangent.orthog().normalized();
113
+ }
114
+ }
115
+ exports.default = QuadraticBezier;