brep-io-kernel 1.0.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 (403) hide show
  1. package/LICENSE.md +32 -0
  2. package/README.md +144 -0
  3. package/dist-kernel/brep-kernel.js +74699 -0
  4. package/dist-kernel/help/CONTRIBUTING.html +248 -0
  5. package/dist-kernel/help/LICENSE.html +248 -0
  6. package/dist-kernel/help/MODELING.png +0 -0
  7. package/dist-kernel/help/PMI.png +0 -0
  8. package/dist-kernel/help/SKETCH.png +0 -0
  9. package/dist-kernel/help/assembly-constraints__Coincident_Constraint_dialog.png +0 -0
  10. package/dist-kernel/help/assembly-constraints___Angle_Constraint_dialog.png +0 -0
  11. package/dist-kernel/help/assembly-constraints___Distance_Constraint_dialog.png +0 -0
  12. package/dist-kernel/help/assembly-constraints___Fixed_Constraint_dialog.png +0 -0
  13. package/dist-kernel/help/assembly-constraints___Parallel_Constraint_dialog.png +0 -0
  14. package/dist-kernel/help/assembly-constraints___Touch_Align_Constraint_dialog.png +0 -0
  15. package/dist-kernel/help/assembly-constraints__angle-constraint.html +248 -0
  16. package/dist-kernel/help/assembly-constraints__coincident-constraint.html +248 -0
  17. package/dist-kernel/help/assembly-constraints__distance-constraint.html +248 -0
  18. package/dist-kernel/help/assembly-constraints__fixed-constraint.html +248 -0
  19. package/dist-kernel/help/assembly-constraints__parallel-constraint.html +248 -0
  20. package/dist-kernel/help/assembly-constraints__solver.html +248 -0
  21. package/dist-kernel/help/assembly-constraints__touch-align-constraint.html +248 -0
  22. package/dist-kernel/help/brep-api.html +263 -0
  23. package/dist-kernel/help/brep-kernel.html +258 -0
  24. package/dist-kernel/help/brep-model.html +248 -0
  25. package/dist-kernel/help/cylindrical-face-radius-embedding.html +290 -0
  26. package/dist-kernel/help/dialog-screenshots.html +248 -0
  27. package/dist-kernel/help/extruded-sketch-radius-embedding.html +336 -0
  28. package/dist-kernel/help/features__Assembly_Component_dialog.png +0 -0
  29. package/dist-kernel/help/features__Boolean_dialog.png +0 -0
  30. package/dist-kernel/help/features__Chamfer_dialog.png +0 -0
  31. package/dist-kernel/help/features__Datium_dialog.png +0 -0
  32. package/dist-kernel/help/features__Extrude_dialog.png +0 -0
  33. package/dist-kernel/help/features__Fillet_dialog.png +0 -0
  34. package/dist-kernel/help/features__Helix_dialog.png +0 -0
  35. package/dist-kernel/help/features__Hole_dialog.png +0 -0
  36. package/dist-kernel/help/features__Image_Heightmap_Solid_dialog.png +0 -0
  37. package/dist-kernel/help/features__Image_to_Face_dialog.png +0 -0
  38. package/dist-kernel/help/features__Import_3D_Model_dialog.png +0 -0
  39. package/dist-kernel/help/features__Loft_dialog.png +0 -0
  40. package/dist-kernel/help/features__Mirror_dialog.png +0 -0
  41. package/dist-kernel/help/features__Offset_Shell_dialog.png +0 -0
  42. package/dist-kernel/help/features__Overlap_Cleanup_dialog.png +0 -0
  43. package/dist-kernel/help/features__Pattern_Linear_dialog.png +0 -0
  44. package/dist-kernel/help/features__Pattern_Radial_dialog.png +0 -0
  45. package/dist-kernel/help/features__Pattern_dialog.png +0 -0
  46. package/dist-kernel/help/features__Plane_dialog.png +0 -0
  47. package/dist-kernel/help/features__Primitive_Cone_dialog.png +0 -0
  48. package/dist-kernel/help/features__Primitive_Cube_dialog.png +0 -0
  49. package/dist-kernel/help/features__Primitive_Cylinder_dialog.png +0 -0
  50. package/dist-kernel/help/features__Primitive_Pyramid_dialog.png +0 -0
  51. package/dist-kernel/help/features__Primitive_Sphere_dialog.png +0 -0
  52. package/dist-kernel/help/features__Primitive_Torus_dialog.png +0 -0
  53. package/dist-kernel/help/features__Remesh_dialog.png +0 -0
  54. package/dist-kernel/help/features__Revolve_dialog.png +0 -0
  55. package/dist-kernel/help/features__Sheet_Metal_Contour_Flange_dialog.png +0 -0
  56. package/dist-kernel/help/features__Sheet_Metal_Cutout_dialog.png +0 -0
  57. package/dist-kernel/help/features__Sheet_Metal_Flange_dialog.png +0 -0
  58. package/dist-kernel/help/features__Sheet_Metal_Tab_dialog.png +0 -0
  59. package/dist-kernel/help/features__Sketch_dialog.png +0 -0
  60. package/dist-kernel/help/features__Spline_dialog.png +0 -0
  61. package/dist-kernel/help/features__Sweep_dialog.png +0 -0
  62. package/dist-kernel/help/features__Transform_dialog.png +0 -0
  63. package/dist-kernel/help/features__Tube_dialog.png +0 -0
  64. package/dist-kernel/help/features__assembly-component.html +248 -0
  65. package/dist-kernel/help/features__boolean.html +248 -0
  66. package/dist-kernel/help/features__chamfer.html +248 -0
  67. package/dist-kernel/help/features__datium.html +248 -0
  68. package/dist-kernel/help/features__datum.html +248 -0
  69. package/dist-kernel/help/features__extrude.html +248 -0
  70. package/dist-kernel/help/features__fillet.html +248 -0
  71. package/dist-kernel/help/features__helix.html +248 -0
  72. package/dist-kernel/help/features__hole.html +248 -0
  73. package/dist-kernel/help/features__image-heightmap-solid.html +248 -0
  74. package/dist-kernel/help/features__image-to-face-2D_dialog.png +0 -0
  75. package/dist-kernel/help/features__image-to-face-3D_dialog.png +0 -0
  76. package/dist-kernel/help/features__image-to-face.html +248 -0
  77. package/dist-kernel/help/features__import-3d-model.html +248 -0
  78. package/dist-kernel/help/features__index.html +248 -0
  79. package/dist-kernel/help/features__loft.html +248 -0
  80. package/dist-kernel/help/features__mirror.html +248 -0
  81. package/dist-kernel/help/features__offset-shell.html +248 -0
  82. package/dist-kernel/help/features__pattern-linear.html +248 -0
  83. package/dist-kernel/help/features__pattern-radial.html +248 -0
  84. package/dist-kernel/help/features__pattern.html +248 -0
  85. package/dist-kernel/help/features__plane.html +248 -0
  86. package/dist-kernel/help/features__primitive-cone.html +248 -0
  87. package/dist-kernel/help/features__primitive-cube.html +248 -0
  88. package/dist-kernel/help/features__primitive-cylinder.html +248 -0
  89. package/dist-kernel/help/features__primitive-pyramid.html +248 -0
  90. package/dist-kernel/help/features__primitive-sphere.html +248 -0
  91. package/dist-kernel/help/features__primitive-torus.html +248 -0
  92. package/dist-kernel/help/features__remesh.html +248 -0
  93. package/dist-kernel/help/features__revolve.html +248 -0
  94. package/dist-kernel/help/features__sheet-metal-contour-flange.html +248 -0
  95. package/dist-kernel/help/features__sheet-metal-flange.html +248 -0
  96. package/dist-kernel/help/features__sheet-metal-tab.html +248 -0
  97. package/dist-kernel/help/features__sketch.html +248 -0
  98. package/dist-kernel/help/features__spline.html +248 -0
  99. package/dist-kernel/help/features__sweep.html +248 -0
  100. package/dist-kernel/help/features__transform.html +248 -0
  101. package/dist-kernel/help/features__tube.html +248 -0
  102. package/dist-kernel/help/file-formats.html +248 -0
  103. package/dist-kernel/help/getting-started.html +248 -0
  104. package/dist-kernel/help/highlights.html +248 -0
  105. package/dist-kernel/help/history-systems.html +248 -0
  106. package/dist-kernel/help/how-it-works.html +248 -0
  107. package/dist-kernel/help/index.html +862 -0
  108. package/dist-kernel/help/input-params-schema.html +363 -0
  109. package/dist-kernel/help/inspector-improvements.html +248 -0
  110. package/dist-kernel/help/inspector.html +248 -0
  111. package/dist-kernel/help/modes__modeling.html +248 -0
  112. package/dist-kernel/help/modes__pmi.html +248 -0
  113. package/dist-kernel/help/modes__sketch.html +248 -0
  114. package/dist-kernel/help/plugins.html +248 -0
  115. package/dist-kernel/help/pmi-annotations__Angle_Dimension_dialog.png +0 -0
  116. package/dist-kernel/help/pmi-annotations__Explode_Body_dialog.png +0 -0
  117. package/dist-kernel/help/pmi-annotations__Hole_Callout_dialog.png +0 -0
  118. package/dist-kernel/help/pmi-annotations__Leader_dialog.png +0 -0
  119. package/dist-kernel/help/pmi-annotations__Linear_Dimension_dialog.png +0 -0
  120. package/dist-kernel/help/pmi-annotations__Note_dialog.png +0 -0
  121. package/dist-kernel/help/pmi-annotations__Radial_Dimension_dialog.png +0 -0
  122. package/dist-kernel/help/pmi-annotations__angle-dimension.html +248 -0
  123. package/dist-kernel/help/pmi-annotations__explode-body.html +248 -0
  124. package/dist-kernel/help/pmi-annotations__hole-callout.html +248 -0
  125. package/dist-kernel/help/pmi-annotations__index.html +248 -0
  126. package/dist-kernel/help/pmi-annotations__leader.html +248 -0
  127. package/dist-kernel/help/pmi-annotations__linear-dimension.html +248 -0
  128. package/dist-kernel/help/pmi-annotations__note.html +248 -0
  129. package/dist-kernel/help/pmi-annotations__radial-dimension.html +248 -0
  130. package/dist-kernel/help/search-index.json +464 -0
  131. package/dist-kernel/help/simplified-radial-dimensions.html +298 -0
  132. package/dist-kernel/help/solid-methods.html +359 -0
  133. package/dist-kernel/help/table-of-contents.html +330 -0
  134. package/dist-kernel/help/ui-overview.html +248 -0
  135. package/dist-kernel/help/whats-new.html +248 -0
  136. package/package.json +54 -0
  137. package/src/BREP/AssemblyComponent.js +42 -0
  138. package/src/BREP/BREP.js +43 -0
  139. package/src/BREP/BetterSolid.js +805 -0
  140. package/src/BREP/Edge.js +103 -0
  141. package/src/BREP/Extrude.js +403 -0
  142. package/src/BREP/Face.js +187 -0
  143. package/src/BREP/MeshRepairer.js +634 -0
  144. package/src/BREP/OffsetShellSolid.js +614 -0
  145. package/src/BREP/PointCloudWrap.js +302 -0
  146. package/src/BREP/Revolve.js +345 -0
  147. package/src/BREP/SolidMethods/authoring.js +112 -0
  148. package/src/BREP/SolidMethods/booleanOps.js +230 -0
  149. package/src/BREP/SolidMethods/chamfer.js +122 -0
  150. package/src/BREP/SolidMethods/edgeResolution.js +25 -0
  151. package/src/BREP/SolidMethods/fillet.js +792 -0
  152. package/src/BREP/SolidMethods/index.js +72 -0
  153. package/src/BREP/SolidMethods/io.js +105 -0
  154. package/src/BREP/SolidMethods/lifecycle.js +103 -0
  155. package/src/BREP/SolidMethods/manifoldOps.js +375 -0
  156. package/src/BREP/SolidMethods/meshCleanup.js +2512 -0
  157. package/src/BREP/SolidMethods/meshQueries.js +264 -0
  158. package/src/BREP/SolidMethods/metadata.js +106 -0
  159. package/src/BREP/SolidMethods/metrics.js +51 -0
  160. package/src/BREP/SolidMethods/transforms.js +361 -0
  161. package/src/BREP/SolidMethods/visualize.js +508 -0
  162. package/src/BREP/SolidShared.js +26 -0
  163. package/src/BREP/Sweep.js +1596 -0
  164. package/src/BREP/Tube.js +857 -0
  165. package/src/BREP/Vertex.js +43 -0
  166. package/src/BREP/applyBooleanOperation.js +704 -0
  167. package/src/BREP/boundsUtils.js +48 -0
  168. package/src/BREP/chamfer.js +551 -0
  169. package/src/BREP/edgePolylineUtils.js +85 -0
  170. package/src/BREP/fillets/common.js +388 -0
  171. package/src/BREP/fillets/fillet.js +1422 -0
  172. package/src/BREP/fillets/filletGeometry.js +15 -0
  173. package/src/BREP/fillets/inset.js +389 -0
  174. package/src/BREP/fillets/offsetHelper.js +143 -0
  175. package/src/BREP/fillets/outset.js +88 -0
  176. package/src/BREP/helix.js +193 -0
  177. package/src/BREP/meshToBrep.js +234 -0
  178. package/src/BREP/primitives.js +279 -0
  179. package/src/BREP/setupManifold.js +71 -0
  180. package/src/BREP/threadGeometry.js +1120 -0
  181. package/src/BREP/triangleUtils.js +8 -0
  182. package/src/BREP/triangulate.js +608 -0
  183. package/src/FeatureRegistry.js +183 -0
  184. package/src/PartHistory.js +1132 -0
  185. package/src/UI/AccordionWidget.js +292 -0
  186. package/src/UI/CADmaterials.js +850 -0
  187. package/src/UI/EnvMonacoEditor.js +522 -0
  188. package/src/UI/FloatingWindow.js +396 -0
  189. package/src/UI/HistoryWidget.js +457 -0
  190. package/src/UI/MainToolbar.js +131 -0
  191. package/src/UI/ModelLibraryView.js +194 -0
  192. package/src/UI/OrthoCameraIdle.js +206 -0
  193. package/src/UI/PluginsWidget.js +280 -0
  194. package/src/UI/SceneListing.js +606 -0
  195. package/src/UI/SelectionFilter.js +629 -0
  196. package/src/UI/ViewCube.js +389 -0
  197. package/src/UI/assembly/AssemblyConstraintCollectionWidget.js +329 -0
  198. package/src/UI/assembly/AssemblyConstraintControlsWidget.js +282 -0
  199. package/src/UI/assembly/AssemblyConstraintsWidget.css +292 -0
  200. package/src/UI/assembly/AssemblyConstraintsWidget.js +1373 -0
  201. package/src/UI/assembly/constraintFaceUtils.js +115 -0
  202. package/src/UI/assembly/constraintHighlightUtils.js +70 -0
  203. package/src/UI/assembly/constraintLabelUtils.js +31 -0
  204. package/src/UI/assembly/constraintPointUtils.js +64 -0
  205. package/src/UI/assembly/constraintSelectionUtils.js +185 -0
  206. package/src/UI/assembly/constraintStatusUtils.js +142 -0
  207. package/src/UI/componentSelectorModal.js +240 -0
  208. package/src/UI/controls/CombinedTransformControls.js +386 -0
  209. package/src/UI/dialogs.js +351 -0
  210. package/src/UI/expressionsManager.js +100 -0
  211. package/src/UI/featureDialogWidgets/booleanField.js +25 -0
  212. package/src/UI/featureDialogWidgets/booleanOperationField.js +97 -0
  213. package/src/UI/featureDialogWidgets/buttonField.js +45 -0
  214. package/src/UI/featureDialogWidgets/componentSelectorField.js +102 -0
  215. package/src/UI/featureDialogWidgets/defaultField.js +23 -0
  216. package/src/UI/featureDialogWidgets/fileField.js +66 -0
  217. package/src/UI/featureDialogWidgets/index.js +34 -0
  218. package/src/UI/featureDialogWidgets/numberField.js +165 -0
  219. package/src/UI/featureDialogWidgets/optionsField.js +33 -0
  220. package/src/UI/featureDialogWidgets/referenceSelectionField.js +208 -0
  221. package/src/UI/featureDialogWidgets/stringField.js +24 -0
  222. package/src/UI/featureDialogWidgets/textareaField.js +28 -0
  223. package/src/UI/featureDialogWidgets/threadDesignationField.js +160 -0
  224. package/src/UI/featureDialogWidgets/transformField.js +252 -0
  225. package/src/UI/featureDialogWidgets/utils.js +43 -0
  226. package/src/UI/featureDialogWidgets/vec3Field.js +133 -0
  227. package/src/UI/featureDialogs.js +1414 -0
  228. package/src/UI/fileManagerWidget.js +615 -0
  229. package/src/UI/history/HistoryCollectionWidget.js +1294 -0
  230. package/src/UI/history/historyCollectionWidget.css.js +257 -0
  231. package/src/UI/history/historyDisplayInfo.js +133 -0
  232. package/src/UI/mobile.js +28 -0
  233. package/src/UI/objectDump.js +442 -0
  234. package/src/UI/pmi/AnnotationCollectionWidget.js +120 -0
  235. package/src/UI/pmi/AnnotationHistory.js +353 -0
  236. package/src/UI/pmi/AnnotationRegistry.js +90 -0
  237. package/src/UI/pmi/BaseAnnotation.js +269 -0
  238. package/src/UI/pmi/LabelOverlay.css +102 -0
  239. package/src/UI/pmi/LabelOverlay.js +191 -0
  240. package/src/UI/pmi/PMIMode.js +1550 -0
  241. package/src/UI/pmi/PMIViewsWidget.js +1098 -0
  242. package/src/UI/pmi/annUtils.js +729 -0
  243. package/src/UI/pmi/dimensions/AngleDimensionAnnotation.js +647 -0
  244. package/src/UI/pmi/dimensions/ExplodeBodyAnnotation.js +507 -0
  245. package/src/UI/pmi/dimensions/HoleCalloutAnnotation.js +462 -0
  246. package/src/UI/pmi/dimensions/LeaderAnnotation.js +403 -0
  247. package/src/UI/pmi/dimensions/LinearDimensionAnnotation.js +532 -0
  248. package/src/UI/pmi/dimensions/NoteAnnotation.js +110 -0
  249. package/src/UI/pmi/dimensions/RadialDimensionAnnotation.js +659 -0
  250. package/src/UI/pmi/pmiStyle.js +44 -0
  251. package/src/UI/sketcher/SketchMode3D.js +4095 -0
  252. package/src/UI/sketcher/dimensions.js +674 -0
  253. package/src/UI/sketcher/glyphs.js +236 -0
  254. package/src/UI/sketcher/highlights.js +60 -0
  255. package/src/UI/toolbarButtons/aboutButton.js +5 -0
  256. package/src/UI/toolbarButtons/exportButton.js +609 -0
  257. package/src/UI/toolbarButtons/flatPatternButton.js +307 -0
  258. package/src/UI/toolbarButtons/importButton.js +160 -0
  259. package/src/UI/toolbarButtons/inspectorToggleButton.js +12 -0
  260. package/src/UI/toolbarButtons/metadataButton.js +1063 -0
  261. package/src/UI/toolbarButtons/orientToFaceButton.js +114 -0
  262. package/src/UI/toolbarButtons/registerDefaultButtons.js +46 -0
  263. package/src/UI/toolbarButtons/saveButton.js +99 -0
  264. package/src/UI/toolbarButtons/scriptRunnerButton.js +302 -0
  265. package/src/UI/toolbarButtons/testsButton.js +26 -0
  266. package/src/UI/toolbarButtons/undoRedoButtons.js +25 -0
  267. package/src/UI/toolbarButtons/wireframeToggleButton.js +5 -0
  268. package/src/UI/toolbarButtons/zoomToFitButton.js +5 -0
  269. package/src/UI/triangleDebuggerWindow.js +945 -0
  270. package/src/UI/viewer.js +4228 -0
  271. package/src/assemblyConstraints/AssemblyConstraintHistory.js +1576 -0
  272. package/src/assemblyConstraints/AssemblyConstraintRegistry.js +120 -0
  273. package/src/assemblyConstraints/BaseAssemblyConstraint.js +66 -0
  274. package/src/assemblyConstraints/constraintExpressionUtils.js +35 -0
  275. package/src/assemblyConstraints/constraintUtils/parallelAlignment.js +676 -0
  276. package/src/assemblyConstraints/constraints/AngleConstraint.js +485 -0
  277. package/src/assemblyConstraints/constraints/CoincidentConstraint.js +194 -0
  278. package/src/assemblyConstraints/constraints/DistanceConstraint.js +616 -0
  279. package/src/assemblyConstraints/constraints/FixedConstraint.js +78 -0
  280. package/src/assemblyConstraints/constraints/ParallelConstraint.js +252 -0
  281. package/src/assemblyConstraints/constraints/TouchAlignConstraint.js +961 -0
  282. package/src/core/entities/HistoryCollectionBase.js +72 -0
  283. package/src/core/entities/ListEntityBase.js +109 -0
  284. package/src/core/entities/schemaProcesser.js +121 -0
  285. package/src/exporters/sheetMetalFlatPattern.js +659 -0
  286. package/src/exporters/sheetMetalUnfold.js +862 -0
  287. package/src/exporters/step.js +1135 -0
  288. package/src/exporters/threeMF.js +575 -0
  289. package/src/features/assemblyComponent/AssemblyComponentFeature.js +780 -0
  290. package/src/features/boolean/BooleanFeature.js +94 -0
  291. package/src/features/chamfer/ChamferFeature.js +116 -0
  292. package/src/features/datium/DatiumFeature.js +80 -0
  293. package/src/features/edgeFeatureUtils.js +41 -0
  294. package/src/features/extrude/ExtrudeFeature.js +143 -0
  295. package/src/features/fillet/FilletFeature.js +197 -0
  296. package/src/features/helix/HelixFeature.js +405 -0
  297. package/src/features/hole/HoleFeature.js +1050 -0
  298. package/src/features/hole/screwClearance.js +86 -0
  299. package/src/features/hole/threadDesignationCatalog.js +149 -0
  300. package/src/features/imageHeightSolid/ImageHeightmapSolidFeature.js +463 -0
  301. package/src/features/imageToFace/ImageToFaceFeature.js +727 -0
  302. package/src/features/imageToFace/imageEditor.js +1270 -0
  303. package/src/features/imageToFace/traceUtils.js +971 -0
  304. package/src/features/import3dModel/Import3dModelFeature.js +151 -0
  305. package/src/features/loft/LoftFeature.js +605 -0
  306. package/src/features/mirror/MirrorFeature.js +151 -0
  307. package/src/features/offsetFace/OffsetFaceFeature.js +370 -0
  308. package/src/features/offsetShell/OffsetShellFeature.js +89 -0
  309. package/src/features/overlapCleanup/OverlapCleanupFeature.js +85 -0
  310. package/src/features/pattern/PatternFeature.js +275 -0
  311. package/src/features/patternLinear/PatternLinearFeature.js +120 -0
  312. package/src/features/patternRadial/PatternRadialFeature.js +186 -0
  313. package/src/features/plane/PlaneFeature.js +154 -0
  314. package/src/features/primitiveCone/primitiveConeFeature.js +99 -0
  315. package/src/features/primitiveCube/primitiveCubeFeature.js +70 -0
  316. package/src/features/primitiveCylinder/primitiveCylinderFeature.js +91 -0
  317. package/src/features/primitivePyramid/primitivePyramidFeature.js +72 -0
  318. package/src/features/primitiveSphere/primitiveSphereFeature.js +62 -0
  319. package/src/features/primitiveTorus/primitiveTorusFeature.js +109 -0
  320. package/src/features/remesh/RemeshFeature.js +97 -0
  321. package/src/features/revolve/RevolveFeature.js +111 -0
  322. package/src/features/selectionUtils.js +118 -0
  323. package/src/features/sheetMetal/SheetMetalContourFlangeFeature.js +1656 -0
  324. package/src/features/sheetMetal/SheetMetalCutoutFeature.js +1056 -0
  325. package/src/features/sheetMetal/SheetMetalFlangeFeature.js +1568 -0
  326. package/src/features/sheetMetal/SheetMetalHemFeature.js +43 -0
  327. package/src/features/sheetMetal/SheetMetalObject.js +141 -0
  328. package/src/features/sheetMetal/SheetMetalTabFeature.js +176 -0
  329. package/src/features/sheetMetal/UNFOLD_NEUTRAL_REQUIREMENTS.md +153 -0
  330. package/src/features/sheetMetal/contour-flange-rebuild-spec.md +261 -0
  331. package/src/features/sheetMetal/profileUtils.js +25 -0
  332. package/src/features/sheetMetal/sheetMetalCleanup.js +9 -0
  333. package/src/features/sheetMetal/sheetMetalFaceTypes.js +146 -0
  334. package/src/features/sheetMetal/sheetMetalMetadata.js +165 -0
  335. package/src/features/sheetMetal/sheetMetalPipeline.js +169 -0
  336. package/src/features/sheetMetal/sheetMetalProfileUtils.js +216 -0
  337. package/src/features/sheetMetal/sheetMetalTabUtils.js +29 -0
  338. package/src/features/sheetMetal/sheetMetalTree.js +210 -0
  339. package/src/features/sketch/SketchFeature.js +955 -0
  340. package/src/features/sketch/sketchSolver2D/ConstraintEngine.js +800 -0
  341. package/src/features/sketch/sketchSolver2D/constraintDefinitions.js +704 -0
  342. package/src/features/sketch/sketchSolver2D/mathHelpersMod.js +307 -0
  343. package/src/features/spline/SplineEditorSession.js +988 -0
  344. package/src/features/spline/SplineFeature.js +1388 -0
  345. package/src/features/spline/splineUtils.js +218 -0
  346. package/src/features/sweep/SweepFeature.js +110 -0
  347. package/src/features/transform/TransformFeature.js +152 -0
  348. package/src/features/tube/TubeFeature.js +635 -0
  349. package/src/fs.proxy.js +625 -0
  350. package/src/idbStorage.js +254 -0
  351. package/src/index.js +12 -0
  352. package/src/main.js +15 -0
  353. package/src/metadataManager.js +64 -0
  354. package/src/path.proxy.js +277 -0
  355. package/src/plugins/ghLoader.worker.js +151 -0
  356. package/src/plugins/pluginManager.js +286 -0
  357. package/src/pmi/PMIViewsManager.js +134 -0
  358. package/src/services/componentLibrary.js +198 -0
  359. package/src/tests/ConsoleCapture.js +189 -0
  360. package/src/tests/S7-diagnostics-2025-12-23T18-37-23-570Z.json +630 -0
  361. package/src/tests/browserTests.js +597 -0
  362. package/src/tests/debugBoolean.js +225 -0
  363. package/src/tests/partFiles/badBoolean.json +957 -0
  364. package/src/tests/partFiles/extrudeTest.json +88 -0
  365. package/src/tests/partFiles/filletFail.json +58 -0
  366. package/src/tests/partFiles/import_TEst.part.part.json +646 -0
  367. package/src/tests/partFiles/sheetMetalHem.BREP.json +734 -0
  368. package/src/tests/test_boolean_subtract.js +27 -0
  369. package/src/tests/test_chamfer.js +17 -0
  370. package/src/tests/test_extrudeFace.js +24 -0
  371. package/src/tests/test_fillet.js +17 -0
  372. package/src/tests/test_fillet_nonClosed.js +45 -0
  373. package/src/tests/test_filletsMoreDifficult.js +46 -0
  374. package/src/tests/test_history_features_basic.js +149 -0
  375. package/src/tests/test_hole.js +282 -0
  376. package/src/tests/test_mirror.js +16 -0
  377. package/src/tests/test_offsetShellGrouping.js +85 -0
  378. package/src/tests/test_plane.js +4 -0
  379. package/src/tests/test_primitiveCone.js +11 -0
  380. package/src/tests/test_primitiveCube.js +7 -0
  381. package/src/tests/test_primitiveCylinder.js +8 -0
  382. package/src/tests/test_primitivePyramid.js +9 -0
  383. package/src/tests/test_primitiveSphere.js +17 -0
  384. package/src/tests/test_primitiveTorus.js +21 -0
  385. package/src/tests/test_pushFace.js +126 -0
  386. package/src/tests/test_sheetMetalContourFlange.js +125 -0
  387. package/src/tests/test_sheetMetal_features.js +80 -0
  388. package/src/tests/test_sketch_openLoop.js +45 -0
  389. package/src/tests/test_solidMetrics.js +58 -0
  390. package/src/tests/test_stlLoader.js +1889 -0
  391. package/src/tests/test_sweepFace.js +55 -0
  392. package/src/tests/test_tube.js +45 -0
  393. package/src/tests/test_tube_closedLoop.js +67 -0
  394. package/src/tests/tests.js +493 -0
  395. package/src/tools/assemblyConstraintDialogCapturePage.js +56 -0
  396. package/src/tools/dialogCapturePageFactory.js +227 -0
  397. package/src/tools/featureDialogCapturePage.js +47 -0
  398. package/src/tools/pmiAnnotationDialogCapturePage.js +60 -0
  399. package/src/utils/axisHelpers.js +99 -0
  400. package/src/utils/deepClone.js +69 -0
  401. package/src/utils/geometryTolerance.js +37 -0
  402. package/src/utils/normalizeTypeString.js +8 -0
  403. package/src/utils/xformMath.js +51 -0
@@ -0,0 +1,1270 @@
1
+ // Image editor that displays as a full screen paint-like editor
2
+ import { SchemaForm } from '../../UI/featureDialogs.js';
3
+ import { traceImageDataToPolylines, applyCurveFit, assignBreaksToLoops, splitLoopIntoEdges, sanitizeLoopsForExtrude, dropIntersectingLoops } from './traceUtils.js';
4
+
5
+ export class ImageEditorUI {
6
+ // onSaveCallback can be a function (dataUrl)=>void, or an object { onSave, onCancel }
7
+ // options: { featureSchema, featureParams, onParamsChange, partHistory, viewer }
8
+ constructor(imageBase64, onSaveCallback, options = {}) {
9
+ this.imageBase64 = imageBase64 || '';
10
+ this.onSaveCallback = typeof onSaveCallback === 'function' ? onSaveCallback : (onSaveCallback && onSaveCallback.onSave) || null;
11
+ this.onCancelCallback = (onSaveCallback && onSaveCallback.onCancel) || null;
12
+ this.featureSchema = options && options.featureSchema ? options.featureSchema : null;
13
+ this.featureParams = options && options.featureParams ? options.featureParams : null;
14
+ this.onParamsChange = options && typeof options.onParamsChange === 'function' ? options.onParamsChange : null;
15
+ this.featureViewer = options && options.viewer ? options.viewer : null;
16
+ this.featurePartHistory = options && options.partHistory ? options.partHistory : null;
17
+
18
+ // Drawing state
19
+ this.tool = 'brush'; // 'brush' | 'eraser' | 'pan' | 'bucket' | 'break'
20
+ this.brushColor = '#000000';
21
+ this.brushSize = 8;
22
+ this.brushShape = 'round'; // 'round' | 'square' | 'diamond'
23
+ this.bucketTolerance = 0; // 0-255, max per-channel diff
24
+ this.isDrawing = false;
25
+ this.isPanning = false;
26
+ this.isHovering = false;
27
+ this.lastX = 0;
28
+ this.lastY = 0;
29
+ this.hoverX = 0;
30
+ this.hoverY = 0;
31
+ this.scale = 1;
32
+ this.offsetX = 0;
33
+ this.offsetY = 0;
34
+ this.minScale = 0.1;
35
+ this.maxScale = 10;
36
+
37
+ // Working canvas logical size (in image pixels)
38
+ this.workWidth = 0;
39
+ this.workHeight = 0;
40
+
41
+ // Resize-handle interaction
42
+ this.isResizingCanvas = false;
43
+ this.resizeHandleSize = 12; // screen px for hit area and drawing
44
+
45
+ // Initial view state flag
46
+ this._didInitialView = false;
47
+
48
+ // Canvas state (image-space backing buffer for edits)
49
+ this.bgImage = null; // HTMLImageElement
50
+ this.drawCanvas = null; // offscreen edits at image resolution
51
+ this.drawCtx = null;
52
+
53
+ // Undo stack for the draw layer (image-space)
54
+ this.undoStack = [];
55
+ this.redoStack = [];
56
+ this.maxHistory = 30;
57
+
58
+ // DOM elements
59
+ this.overlay = null;
60
+ this.toolbar = null;
61
+ this.canvas = null; // display canvas
62
+ this.ctx = null;
63
+ this.svgOverlay = null;
64
+ this.svgPathsGroup = null;
65
+ this.svgBreakpointsGroup = null;
66
+ this.svgManualBreaksGroup = null;
67
+ this.svgSuppressedBreaksGroup = null;
68
+ this.sidebar = null;
69
+ this.formHost = null;
70
+ this.finishBtn = null;
71
+ this.cancelBtn = null;
72
+ this.colorInput = null;
73
+ this.sizeInput = null;
74
+ this.brushBtn = null;
75
+ this.eraserBtn = null;
76
+ this.breakBtn = null;
77
+ this.undoBtn = null;
78
+ this.redoBtn = null;
79
+ this.schemaForm = null;
80
+
81
+ this._bound = {};
82
+
83
+ // Vector overlay state
84
+ this._vectorDirty = true;
85
+ this._vectorUpdateHandle = null;
86
+ this._traceCanvas = null;
87
+ this._traceCtx = null;
88
+ this._baseImageOnDrawCanvas = false;
89
+ this._vectorLoops = [];
90
+ this._autoBreakPoints = [];
91
+ this._autoBreaksEnabled = false;
92
+ this._breakAutoPx = 2.2;
93
+ this._breakManualPx = 3;
94
+ this._breakSnapPx = 6;
95
+ this._breakDedupePx = 4;
96
+ this._breakRemovePx = 6;
97
+
98
+ this._initDOM();
99
+ this._loadImage(this.imageBase64).then(() => {/* one-to-one set in _loadImage */ });
100
+ }
101
+
102
+ // ----------------------------- Public API -----------------------------
103
+ open() {
104
+ if (!this.overlay) return;
105
+ if (!document.body.contains(this.overlay)) document.body.appendChild(this.overlay);
106
+ this._attachEvents();
107
+ try { if (this.featureViewer) this.featureViewer._imageEditorActive = true; } catch { }
108
+ // Ensure initial 1:1 view once canvas has real size
109
+ this._maybeResetInitialView(true);
110
+ this._render();
111
+ }
112
+
113
+ close() {
114
+ this._detachEvents();
115
+ if (this.overlay && this.overlay.parentNode) this.overlay.parentNode.removeChild(this.overlay);
116
+ try { if (this.featureViewer) this.featureViewer._imageEditorActive = false; } catch { }
117
+ }
118
+
119
+ // ---------------------------- Initialization ---------------------------
120
+ _initDOM() {
121
+ // Overlay
122
+ const overlay = document.createElement('div');
123
+ overlay.className = 'img-editor-overlay';
124
+ overlay.innerHTML = `
125
+ <style>
126
+ .img-editor-overlay{position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:100;color:var(--ie-fg);font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;}
127
+ .img-editor-toolbar{position:absolute;left:0;right:0;top:0;height:48px;background:var(--ie-bg-2);border-bottom:1px solid var(--ie-border);display:flex;align-items:center;gap:12px;padding:0 12px;}
128
+ .img-editor-spacer{flex:1 1 auto;}
129
+ .img-editor-btn{border:1px solid var(--ie-border);background:var(--ie-bg-3);color:var(--ie-fg);border-radius:6px;padding:6px 10px;cursor:pointer;line-height:1;}
130
+ .img-editor-btn.active{background:var(--ie-accent-bg);border-color:var(--ie-accent);color:var(--ie-accent-fg)}
131
+ .img-editor-btn:disabled{opacity:.5;cursor:not-allowed;}
132
+ .img-editor-right{margin-left:auto;display:flex;gap:8px;}
133
+ .img-editor-main{position:absolute;left:0;right:0;top:48px;bottom:0;display:flex;flex-direction:row-reverse;min-height:0;}
134
+ .img-editor-canvas-wrap{position:relative;flex:1;overflow:hidden;background-color:var(--ie-bg-1);background-image:linear-gradient(45deg,var(--ie-bg-2) 25%,transparent 25%,transparent 75%,var(--ie-bg-2) 75%,var(--ie-bg-2)),linear-gradient(45deg,var(--ie-bg-2) 25%,transparent 25%,transparent 75%,var(--ie-bg-2) 75%,var(--ie-bg-2));background-size:16px 16px;background-position:0 0,8px 8px;}
135
+ .img-editor-canvas{position:absolute;left:0;top:0;display:block;}
136
+ .img-editor-overlay-svg{position:absolute;left:0;top:0;display:block;pointer-events:none;shape-rendering:geometricPrecision;}
137
+ .img-editor-sidebar{width:320px;max-width:360px;min-width:240px;background:var(--ie-bg-2);border-right:1px solid var(--ie-border);overflow:auto;padding:12px;box-sizing:border-box;}
138
+ .img-editor-sidebar h3{margin:0 0 8px;font-size:14px;font-weight:600;color:var(--ie-fg);}
139
+ .img-editor-form{background:var(--ie-bg-3);border:1px solid var(--ie-border);border-radius:8px;padding:8px;box-sizing:border-box;}
140
+ .img-editor-group{display:flex;align-items:center;gap:6px;border-right:1px dashed var(--ie-border);padding-right:10px;margin-right:8px;}
141
+ .img-editor-label{font-size:12px;color:var(--ie-muted);}
142
+ .img-editor-color{width:32px;height:28px;border:1px solid var(--ie-border);border-radius:4px;padding:0;background:var(--ie-bg-3)}
143
+ .img-editor-range{width:120px}
144
+ .img-editor-select{height:28px;border:1px solid var(--ie-border);border-radius:4px;background:var(--ie-bg-3);color:var(--ie-fg);}
145
+ /* Light defaults */
146
+ .img-editor-overlay{--ie-bg-1:#111;--ie-bg-2:#1a1a1a;--ie-bg-3:#2a2a2a;--ie-fg:#f3f3f3;--ie-muted:#c0c0c0;--ie-border:#3a3a3a;--ie-accent:#69f;--ie-accent-bg:#143a66;--ie-accent-fg:#e8f2ff}
147
+ @media (prefers-color-scheme: light){
148
+ .img-editor-overlay{--ie-bg-1:#f7f7f7;--ie-bg-2:#f4f4f4;--ie-bg-3:#ffffff;--ie-fg:#111;--ie-muted:#555;--ie-border:#ddd;--ie-accent:#69f;--ie-accent-bg:#e6f2ff;--ie-accent-fg:#113355}
149
+ }
150
+ </style>
151
+ <div class="img-editor-toolbar">
152
+ <div class="img-editor-group">
153
+ <input type="color" class="img-editor-color js-color" value="#000000"/>
154
+ <button class="img-editor-btn js-brush" title="Brush (B)">Brush</button>
155
+ <select class="img-editor-select js-shape">
156
+ <option value="round" selected>Round</option>
157
+ <option value="square">Square</option>
158
+ <option value="diamond">Diamond</option>
159
+ </select>
160
+ <label class="img-editor-label">Size</label>
161
+ <input type="range" min="1" max="64" value="8" class="img-editor-range js-size"/>
162
+ <button class="img-editor-btn js-eraser" title="Eraser (E)">Eraser</button>
163
+ <button class="img-editor-btn js-pan" title="Pan (Hold Space)">Pan</button>
164
+ <button class="img-editor-btn js-break" title="Insert edge break">Break</button>
165
+ </div>
166
+ <div class="img-editor-group">
167
+ <button class="img-editor-btn js-bucket" title="Paint Bucket (G)">Bucket</button>
168
+ <label class="img-editor-label">Tolerance</label>
169
+ <input type="range" min="0" max="255" value="0" class="img-editor-range js-bucket-tol"/>
170
+ </div>
171
+ <div class="img-editor-group">
172
+ <button class="img-editor-btn js-undo" title="Undo (Ctrl+Z)">↶</button>
173
+ <button class="img-editor-btn js-redo" title="Redo (Ctrl+Y)">↷</button>
174
+ <button class="img-editor-btn js-fit" title="Fit (F)">Fit</button>
175
+ </div>
176
+ <div class="img-editor-spacer"></div>
177
+ <div class="img-editor-right">
178
+ <button class="img-editor-btn js-finish" title="Finish (Enter)">Finish</button>
179
+ <button class="img-editor-btn js-cancel" title="Cancel (Esc)">Cancel</button>
180
+ </div>
181
+ </div>
182
+ <div class="img-editor-main">
183
+ <div class="img-editor-canvas-wrap">
184
+ <canvas class="img-editor-canvas"></canvas>
185
+ <svg class="img-editor-overlay-svg" preserveAspectRatio="none" aria-hidden="true">
186
+ <g class="js-vector-group" fill="none" stroke="lime" stroke-width="1" vector-effect="non-scaling-stroke" stroke-linejoin="round" stroke-linecap="round" shape-rendering="geometricPrecision"></g>
187
+ <g class="js-breakpoints-group" fill="#ffd400" stroke="#111" stroke-width="0.5" vector-effect="non-scaling-stroke" shape-rendering="geometricPrecision"></g>
188
+ <g class="js-breakpoints-manual" fill="#ff4bd8" stroke="#111" stroke-width="0.5" vector-effect="non-scaling-stroke" shape-rendering="geometricPrecision"></g>
189
+ <g class="js-breakpoints-suppressed" fill="none" stroke="#888" stroke-width="0.5" vector-effect="non-scaling-stroke" shape-rendering="geometricPrecision"></g>
190
+ </svg>
191
+ </div>
192
+ <div class="img-editor-sidebar">
193
+ <h3>Image to Face</h3>
194
+ <div class="img-editor-form js-feature-form"></div>
195
+ </div>
196
+ </div>
197
+ `;
198
+
199
+ const canvas = overlay.querySelector('canvas');
200
+ const toolbar = overlay.querySelector('.img-editor-toolbar');
201
+ this.overlay = overlay;
202
+ this.toolbar = toolbar;
203
+ this.canvas = canvas;
204
+ this.ctx = this.canvas.getContext('2d');
205
+ this.svgOverlay = overlay.querySelector('.img-editor-overlay-svg');
206
+ this.svgPathsGroup = overlay.querySelector('.js-vector-group');
207
+ this.svgBreakpointsGroup = overlay.querySelector('.js-breakpoints-group');
208
+ this.svgManualBreaksGroup = overlay.querySelector('.js-breakpoints-manual');
209
+ this.svgSuppressedBreaksGroup = overlay.querySelector('.js-breakpoints-suppressed');
210
+ this.sidebar = overlay.querySelector('.img-editor-sidebar');
211
+ this.formHost = overlay.querySelector('.js-feature-form');
212
+ this.colorInput = overlay.querySelector('.js-color');
213
+ this.sizeInput = overlay.querySelector('.js-size');
214
+ this.brushBtn = overlay.querySelector('.js-brush');
215
+ this.eraserBtn = overlay.querySelector('.js-eraser');
216
+ this.panBtn = overlay.querySelector('.js-pan');
217
+ this.breakBtn = overlay.querySelector('.js-break');
218
+ this.bucketBtn = overlay.querySelector('.js-bucket');
219
+ this.undoBtn = overlay.querySelector('.js-undo');
220
+ this.redoBtn = overlay.querySelector('.js-redo');
221
+ this.fitBtn = overlay.querySelector('.js-fit');
222
+ this.finishBtn = overlay.querySelector('.js-finish');
223
+ this.cancelBtn = overlay.querySelector('.js-cancel');
224
+ this.shapeSelect = overlay.querySelector('.js-shape');
225
+ this.bucketTolInput = overlay.querySelector('.js-bucket-tol');
226
+
227
+ // Offscreen draw layer (created after image loads to match resolution)
228
+ this.drawCanvas = document.createElement('canvas');
229
+ this.drawCtx = this.drawCanvas.getContext('2d');
230
+
231
+ this._renderFeatureForm();
232
+ }
233
+
234
+ _renderFeatureForm() {
235
+ if (!this.formHost || !this.featureSchema || !this.featureParams) return;
236
+ try { this.formHost.innerHTML = ''; } catch (_) { }
237
+ try {
238
+ this.schemaForm = new SchemaForm(this.featureSchema, this.featureParams, {
239
+ useShadowDOM: false,
240
+ viewer: this.featureViewer || null,
241
+ scene: (this.featureViewer && this.featureViewer.scene) ? this.featureViewer.scene : null,
242
+ partHistory: this.featurePartHistory || null,
243
+ onChange: () => {
244
+ this._vectorDirty = true;
245
+ this._scheduleVectorOverlayUpdate();
246
+ if (typeof this.onParamsChange === 'function') {
247
+ try { this.onParamsChange(); } catch (_) { }
248
+ }
249
+ }
250
+ });
251
+ this.formHost.appendChild(this.schemaForm.uiElement);
252
+ } catch (e) {
253
+ console.warn('[ImageEditor] Failed to render feature form', e);
254
+ }
255
+ }
256
+
257
+ async _loadImage(src) {
258
+ if (!src) return;
259
+ this.bgImage = await new Promise((resolve, reject) => {
260
+ const img = new Image();
261
+ img.onload = () => resolve(img);
262
+ img.onerror = (e) => reject(e);
263
+ img.src = src;
264
+ });
265
+ // match working area and draw canvas to image resolution
266
+ this.workWidth = this.bgImage.width;
267
+ this.workHeight = this.bgImage.height;
268
+ this._resizeDrawCanvas(this.workWidth, this.workHeight, /*preserve*/ false);
269
+ this.drawCtx.clearRect(0, 0, this.drawCanvas.width, this.drawCanvas.height);
270
+ // Treat the loaded image as the editable bitmap so eraser makes pixels transparent.
271
+ this.drawCtx.drawImage(this.bgImage, 0, 0, this.workWidth, this.workHeight);
272
+ this._baseImageOnDrawCanvas = true;
273
+ this._pushHistory(); // base state
274
+ // Default view: 1:1 pixel mapping centered (if overlay sized)
275
+ this._maybeResetInitialView(false);
276
+ this._vectorDirty = true;
277
+ this._scheduleVectorOverlayUpdate();
278
+ this._render();
279
+ }
280
+
281
+ _attachEvents() {
282
+ const bound = this._bound;
283
+ bound.onResize = () => this._resizeCanvasToViewport();
284
+ bound.onMouseDown = (e) => this._pointerDown(e);
285
+ bound.onMouseMove = (e) => this._pointerMove(e);
286
+ bound.onMouseUp = (e) => this._pointerUp(e);
287
+ bound.onWheel = (e) => this._wheel(e);
288
+ bound.onKey = (e) => this._key(e);
289
+ bound.onColor = (e) => { this.brushColor = e.target.value || '#000000'; this._updateButtons(); };
290
+ bound.onSize = (e) => { this.brushSize = Math.max(1, Math.min(64, Number(e.target.value) || 8)); };
291
+ bound.onBrush = () => { this.tool = 'brush'; this._updateButtons(); };
292
+ bound.onEraser = () => { this.tool = 'eraser'; this._updateButtons(); };
293
+ bound.onPan = () => { this.tool = 'pan'; this._updateButtons(); };
294
+ bound.onBreak = () => { this.tool = 'break'; this._updateButtons(); };
295
+ bound.onBucket = () => { this.tool = 'bucket'; this._updateButtons(); };
296
+ bound.onUndo = () => this._undo();
297
+ bound.onRedo = () => this._redo();
298
+ bound.onFit = () => { this._resetViewToFit(); this._render(); };
299
+ bound.onFinish = () => this._finish();
300
+ bound.onCancel = () => this._cancel();
301
+ bound.onShape = (e) => { const v = String(e.target.value || 'round'); this.brushShape = (v === 'square' || v === 'diamond') ? v : 'round'; this._render(); };
302
+ bound.onBucketTol = (e) => { this.bucketTolerance = Math.max(0, Math.min(255, Number(e.target.value) || 0)); };
303
+ bound.onEnter = () => { this.isHovering = true; };
304
+ bound.onLeave = () => { this.isHovering = false; this._render(); };
305
+ bound.onContextMenu = (e) => { e.preventDefault(); };
306
+
307
+ window.addEventListener('resize', bound.onResize);
308
+ this.canvas.addEventListener('mousedown', bound.onMouseDown);
309
+ window.addEventListener('mousemove', bound.onMouseMove);
310
+ window.addEventListener('mouseup', bound.onMouseUp);
311
+ this.canvas.addEventListener('wheel', bound.onWheel, { passive: false });
312
+ this.canvas.addEventListener('contextmenu', bound.onContextMenu);
313
+ window.addEventListener('keydown', bound.onKey);
314
+ window.addEventListener('keyup', bound.onKey);
315
+ this.canvas.addEventListener('mouseenter', bound.onEnter);
316
+ this.canvas.addEventListener('mouseleave', bound.onLeave);
317
+
318
+ this.colorInput.addEventListener('input', bound.onColor);
319
+ this.sizeInput.addEventListener('input', bound.onSize);
320
+ this.brushBtn.addEventListener('click', bound.onBrush);
321
+ this.eraserBtn.addEventListener('click', bound.onEraser);
322
+ this.panBtn.addEventListener('click', bound.onPan);
323
+ this.breakBtn.addEventListener('click', bound.onBreak);
324
+ this.bucketBtn.addEventListener('click', bound.onBucket);
325
+ this.undoBtn.addEventListener('click', bound.onUndo);
326
+ this.redoBtn.addEventListener('click', bound.onRedo);
327
+ this.fitBtn.addEventListener('click', bound.onFit);
328
+ this.finishBtn.addEventListener('click', bound.onFinish);
329
+ this.cancelBtn.addEventListener('click', bound.onCancel);
330
+ this.shapeSelect.addEventListener('change', bound.onShape);
331
+ this.bucketTolInput.addEventListener('input', bound.onBucketTol);
332
+
333
+ this._resizeCanvasToViewport();
334
+ this._updateButtons();
335
+ }
336
+
337
+ _detachEvents() {
338
+ const b = this._bound;
339
+ window.removeEventListener('resize', b.onResize);
340
+ if (this.canvas) {
341
+ this.canvas.removeEventListener('mousedown', b.onMouseDown);
342
+ this.canvas.removeEventListener('wheel', b.onWheel);
343
+ this.canvas.removeEventListener('mouseenter', b.onEnter);
344
+ this.canvas.removeEventListener('mouseleave', b.onLeave);
345
+ this.canvas.removeEventListener('contextmenu', b.onContextMenu);
346
+ }
347
+ window.removeEventListener('mousemove', b.onMouseMove);
348
+ window.removeEventListener('mouseup', b.onMouseUp);
349
+ window.removeEventListener('keydown', b.onKey);
350
+ window.removeEventListener('keyup', b.onKey);
351
+ if (this.colorInput) this.colorInput.removeEventListener('input', b.onColor);
352
+ if (this.sizeInput) this.sizeInput.removeEventListener('input', b.onSize);
353
+ if (this.brushBtn) this.brushBtn.removeEventListener('click', b.onBrush);
354
+ if (this.eraserBtn) this.eraserBtn.removeEventListener('click', b.onEraser);
355
+ if (this.panBtn) this.panBtn.removeEventListener('click', b.onPan);
356
+ if (this.breakBtn) this.breakBtn.removeEventListener('click', b.onBreak);
357
+ if (this.bucketBtn) this.bucketBtn.removeEventListener('click', b.onBucket);
358
+ if (this.undoBtn) this.undoBtn.removeEventListener('click', b.onUndo);
359
+ if (this.redoBtn) this.redoBtn.removeEventListener('click', b.onRedo);
360
+ if (this.fitBtn) this.fitBtn.removeEventListener('click', b.onFit);
361
+ if (this.finishBtn) this.finishBtn.removeEventListener('click', b.onFinish);
362
+ if (this.cancelBtn) this.cancelBtn.removeEventListener('click', b.onCancel);
363
+ if (this.shapeSelect) this.shapeSelect.removeEventListener('change', b.onShape);
364
+ if (this.bucketTolInput) this.bucketTolInput.removeEventListener('input', b.onBucketTol);
365
+ }
366
+
367
+ _resizeCanvasToViewport() {
368
+ if (!this.canvas) return;
369
+ const wrap = this.overlay.querySelector('.img-editor-canvas-wrap');
370
+ const w = wrap.clientWidth | 0;
371
+ const h = wrap.clientHeight | 0;
372
+ if (!w || !h) return;
373
+ const dpr = Math.max(1, Math.floor(window.devicePixelRatio || 1));
374
+ this.canvas.width = Math.max(1, w * dpr);
375
+ this.canvas.height = Math.max(1, h * dpr);
376
+ this.canvas.style.width = w + 'px';
377
+ this.canvas.style.height = h + 'px';
378
+ if (this.ctx) {
379
+ this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
380
+ }
381
+ // If first time sizing and image is ready, set initial view now
382
+ this._maybeResetInitialView(false);
383
+ this._render();
384
+ }
385
+
386
+ _resetViewToFit() {
387
+ if (!this.bgImage || !this.canvas) return;
388
+ const wrap = this.overlay.querySelector('.img-editor-canvas-wrap');
389
+ const vw = wrap.clientWidth || 1;
390
+ const vh = wrap.clientHeight || 1;
391
+ const iw = this.workWidth || (this.bgImage?.width || 1);
392
+ const ih = this.workHeight || (this.bgImage?.height || 1);
393
+ const s = Math.min(vw / iw, vh / ih);
394
+ this.scale = Math.max(this.minScale, Math.min(this.maxScale, s));
395
+ this.offsetX = (vw - iw * this.scale) * 0.5;
396
+ this.offsetY = (vh - ih * this.scale) * 0.5;
397
+ }
398
+
399
+ _resetViewToOneToOne() {
400
+ if (!this.canvas) return;
401
+ const wrap = this.overlay.querySelector('.img-editor-canvas-wrap');
402
+ const vw = wrap.clientWidth || 1;
403
+ const vh = wrap.clientHeight || 1;
404
+ const iw = this.workWidth || (this.bgImage?.width || 1);
405
+ const ih = this.workHeight || (this.bgImage?.height || 1);
406
+ this.scale = 1; // 1 image px == 1 CSS px
407
+ this.offsetX = (vw - iw * this.scale) * 0.5;
408
+ this.offsetY = (vh - ih * this.scale) * 0.5;
409
+ }
410
+
411
+ _maybeResetInitialView(force = false) {
412
+ if (!this.bgImage || !this.canvas || !this.overlay) return;
413
+ const wrap = this.overlay.querySelector('.img-editor-canvas-wrap');
414
+ const vw = wrap && wrap.clientWidth ? wrap.clientWidth : 0;
415
+ const vh = wrap && wrap.clientHeight ? wrap.clientHeight : 0;
416
+ if (!vw || !vh) return; // wait until visible/sized
417
+ if (force || !this._didInitialView) {
418
+ this._resetViewToOneToOne();
419
+ this._didInitialView = true;
420
+ }
421
+ }
422
+
423
+ // ------------------------------ Rendering ------------------------------
424
+ _render() {
425
+ const ctx = this.ctx;
426
+ if (!ctx) return;
427
+ ctx.save();
428
+ ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
429
+
430
+ // image smoothing: disable at 1:1 for crisp pixels
431
+ const isOneToOne = Math.abs(this.scale - 1) < 1e-6;
432
+ ctx.imageSmoothingEnabled = !isOneToOne;
433
+ ctx.imageSmoothingQuality = isOneToOne ? 'low' : 'high';
434
+
435
+ // draw background image in view space (anchored at 0,0 of work area)
436
+ if (this.bgImage && !this._baseImageOnDrawCanvas) {
437
+ ctx.drawImage(this.bgImage, this.offsetX, this.offsetY, this.bgImage.width * this.scale, this.bgImage.height * this.scale);
438
+ }
439
+
440
+ // draw edits layer in view space
441
+ if (this.drawCanvas && this.drawCanvas.width > 0) {
442
+ ctx.drawImage(this.drawCanvas, this.offsetX, this.offsetY, this.drawCanvas.width * this.scale, this.drawCanvas.height * this.scale);
443
+ }
444
+
445
+ // draw work-area border and resize handle
446
+ if (this.workWidth > 0 && this.workHeight > 0) {
447
+ const x = this.offsetX;
448
+ const y = this.offsetY;
449
+ const w = this.workWidth * this.scale;
450
+ const h = this.workHeight * this.scale;
451
+ ctx.save();
452
+ ctx.strokeStyle = 'rgba(255,255,255,0.6)';
453
+ ctx.lineWidth = 1;
454
+ ctx.setLineDash([4, 3]);
455
+ ctx.strokeRect(x + 0.5, y + 0.5, w, h);
456
+ ctx.setLineDash([]);
457
+ // handle square at bottom-right
458
+ const hs = this.resizeHandleSize;
459
+ ctx.fillStyle = 'rgba(255,255,255,0.9)';
460
+ ctx.strokeStyle = 'rgba(0,0,0,0.6)';
461
+ ctx.lineWidth = 1;
462
+ ctx.fillRect(x + w - hs, y + h - hs, hs, hs);
463
+ ctx.strokeRect(x + w - hs + 0.5, y + h - hs + 0.5, hs, hs);
464
+ ctx.restore();
465
+ }
466
+ // draw brush cursor on top
467
+ this._drawBrushPreview(ctx);
468
+ this._updateOverlayTransform();
469
+ if (this._vectorDirty) this._scheduleVectorOverlayUpdate();
470
+ ctx.restore();
471
+ }
472
+
473
+ // Draw brush cursor preview (view space)
474
+ _drawBrushPreview(ctx) {
475
+ if (!this.isHovering || !this.canvas) return;
476
+ if (this.tool !== 'brush' && this.tool !== 'eraser') return;
477
+ const cx = this.offsetX + this.hoverX * (this.scale || 1);
478
+ const cy = this.offsetY + this.hoverY * (this.scale || 1);
479
+ const r = Math.max(0.5, (this.brushSize * (this.scale || 1)) / 2);
480
+ ctx.save();
481
+ ctx.beginPath();
482
+ if (this.brushShape === 'square') {
483
+ ctx.rect(cx - r, cy - r, 2 * r, 2 * r);
484
+ } else if (this.brushShape === 'diamond') {
485
+ ctx.moveTo(cx, cy - r);
486
+ ctx.lineTo(cx + r, cy);
487
+ ctx.lineTo(cx, cy + r);
488
+ ctx.lineTo(cx - r, cy);
489
+ ctx.closePath();
490
+ } else {
491
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
492
+ }
493
+ ctx.strokeStyle = 'rgba(255,255,255,0.9)';
494
+ ctx.lineWidth = 1;
495
+ ctx.setLineDash([3, 2]);
496
+ ctx.stroke();
497
+ ctx.setLineDash([]);
498
+ ctx.restore();
499
+ }
500
+
501
+ _updateOverlayTransform() {
502
+ if (!this.svgOverlay) return;
503
+ const wrap = this.overlay?.querySelector('.img-editor-canvas-wrap');
504
+ const vw = wrap?.clientWidth || 0;
505
+ const vh = wrap?.clientHeight || 0;
506
+ const s = this.scale || 1;
507
+ if (vw && vh) {
508
+ this.svgOverlay.setAttribute('width', String(vw));
509
+ this.svgOverlay.setAttribute('height', String(vh));
510
+ this.svgOverlay.style.width = vw + 'px';
511
+ this.svgOverlay.style.height = vh + 'px';
512
+ }
513
+ const minX = -((this.offsetX || 0) / s);
514
+ const minY = -((this.offsetY || 0) / s);
515
+ const vbW = (vw || 1) / s;
516
+ const vbH = (vh || 1) / s;
517
+ this.svgOverlay.setAttribute('viewBox', `${minX} ${minY} ${vbW} ${vbH}`);
518
+ this.svgOverlay.style.transform = '';
519
+ this.svgOverlay.style.transformOrigin = '';
520
+ this._updateBreakPointSizes();
521
+ }
522
+
523
+ _composeImageForVector() {
524
+ const w = this.workWidth | 0;
525
+ const h = this.workHeight | 0;
526
+ if (!w || !h) return null;
527
+ if (!this._traceCanvas) {
528
+ this._traceCanvas = document.createElement('canvas');
529
+ this._traceCtx = this._traceCanvas.getContext('2d', { willReadFrequently: true });
530
+ }
531
+ this._traceCanvas.width = w;
532
+ this._traceCanvas.height = h;
533
+ const ctx = this._traceCtx;
534
+ if (!ctx) return null;
535
+ ctx.clearRect(0, 0, w, h);
536
+ if (this.bgImage && !this._baseImageOnDrawCanvas) ctx.drawImage(this.bgImage, 0, 0, w, h);
537
+ if (this.drawCanvas) ctx.drawImage(this.drawCanvas, 0, 0, w, h);
538
+ try {
539
+ return ctx.getImageData(0, 0, w, h);
540
+ } catch (_) {
541
+ return null;
542
+ }
543
+ }
544
+
545
+ _scheduleVectorOverlayUpdate() {
546
+ if (this._vectorUpdateHandle && typeof cancelAnimationFrame === 'function') {
547
+ cancelAnimationFrame(this._vectorUpdateHandle);
548
+ }
549
+ if (typeof requestAnimationFrame === 'function') {
550
+ this._vectorUpdateHandle = requestAnimationFrame(() => {
551
+ this._vectorUpdateHandle = null;
552
+ this._updateVectorOverlay();
553
+ });
554
+ } else {
555
+ this._vectorUpdateHandle = setTimeout(() => {
556
+ this._vectorUpdateHandle = null;
557
+ this._updateVectorOverlay();
558
+ }, 16);
559
+ }
560
+ }
561
+
562
+ _updateVectorOverlay() {
563
+ this._vectorDirty = false;
564
+ const group = this.svgPathsGroup;
565
+ if (!group || !this.svgOverlay) return;
566
+ const id = this._composeImageForVector();
567
+ if (!id) {
568
+ group.innerHTML = '';
569
+ if (this.svgBreakpointsGroup) this.svgBreakpointsGroup.innerHTML = '';
570
+ if (this.svgManualBreaksGroup) this.svgManualBreaksGroup.innerHTML = '';
571
+ if (this.svgSuppressedBreaksGroup) this.svgSuppressedBreaksGroup.innerHTML = '';
572
+ this._vectorLoops = [];
573
+ this._autoBreakPoints = [];
574
+ return;
575
+ }
576
+ const params = this.featureParams || {};
577
+ const threshold = Number.isFinite(Number(params.threshold)) ? Number(params.threshold) : 128;
578
+ const invert = !!params.invert;
579
+ const smooth = params.smoothCurves !== false;
580
+ const curveTol = Number.isFinite(Number(params.curveTolerance)) ? Number(params.curveTolerance) : 0.75;
581
+ const speckleArea = Number.isFinite(Number(params.speckleArea)) ? Math.max(0, Number(params.speckleArea)) : 0;
582
+ const simplifyCollinear = !!params.simplifyCollinear;
583
+ const rdpTol = Number.isFinite(Number(params.rdpTolerance)) ? Number(params.rdpTolerance) : 0;
584
+ const edgeSplitAngle = Number.isFinite(Number(params.edgeSplitAngle))
585
+ ? Math.max(1, Math.min(179, Number(params.edgeSplitAngle)))
586
+ : 70;
587
+ const edgeMinSpacing = Number.isFinite(Number(params.edgeMinSpacing))
588
+ ? Math.max(0, Number(params.edgeMinSpacing))
589
+ : 0;
590
+ const pixelScale = Number.isFinite(Number(params.pixelScale)) ? Number(params.pixelScale) : 1;
591
+ const scaleAbs = Math.max(Math.abs(pixelScale) || 1, 1e-9);
592
+ const traceSimplify = (rdpTol && Number(rdpTol) > 0) ? (Number(rdpTol) / scaleAbs) : 0;
593
+ const curveTolImage = Math.max(0.01, curveTol) / scaleAbs;
594
+ const simplifyCollinearLoop = (loop) => {
595
+ let pts = Array.isArray(loop) ? loop.slice() : [];
596
+ if (!pts.length) return pts;
597
+ if (pts[0][0] !== pts[pts.length - 1][0] || pts[0][1] !== pts[pts.length - 1][1]) {
598
+ pts.push([pts[0][0], pts[0][1]]);
599
+ }
600
+ if (pts.length < 4) return pts;
601
+ const out = [];
602
+ const n = pts.length - 1;
603
+ for (let i = 0; i < n; i++) {
604
+ const a = pts[(i + n - 2) % n];
605
+ const b = pts[(i + n - 1) % n];
606
+ const c = pts[i];
607
+ const abx = b[0] - a[0];
608
+ const aby = b[1] - a[1];
609
+ const bcx = c[0] - b[0];
610
+ const bcy = c[1] - b[1];
611
+ const cross = abx * bcy - aby * bcx;
612
+ if (Math.abs(cross) > 1e-12) out.push(b);
613
+ }
614
+ if (out.length) {
615
+ out.push([out[0][0], out[0][1]]);
616
+ return out;
617
+ }
618
+ return pts;
619
+ };
620
+
621
+ const loops = traceImageDataToPolylines(id, {
622
+ threshold,
623
+ mode: "luma+alpha",
624
+ invert,
625
+ mergeCollinear: simplifyCollinear,
626
+ simplify: traceSimplify,
627
+ minArea: speckleArea,
628
+ });
629
+ let polyLoops = loops.map((l) => l.map((p) => [p.x, p.y]));
630
+ const fallbackLoops = polyLoops.map((l) => simplifyCollinearLoop(l));
631
+ if (smooth) {
632
+ polyLoops = applyCurveFit(polyLoops, {
633
+ tolerance: curveTolImage,
634
+ cornerThresholdDeg: 70,
635
+ iterations: 3,
636
+ });
637
+ } else {
638
+ polyLoops = polyLoops.map((l) => simplifyCollinearLoop(l));
639
+ }
640
+ const sanitizeEps = Math.max(1e-6, 1e-6 * scaleAbs);
641
+ polyLoops = sanitizeLoopsForExtrude(polyLoops, fallbackLoops, { eps: sanitizeEps });
642
+ polyLoops = dropIntersectingLoops(polyLoops, { eps: sanitizeEps })
643
+ .filter((l) => Array.isArray(l) && l.length >= 3);
644
+ this._vectorLoops = polyLoops.slice();
645
+ const pathStrings = [];
646
+ for (const loop of polyLoops) {
647
+ if (!loop || loop.length < 2) continue;
648
+ let d = `M${loop[0][0]} ${loop[0][1]}`;
649
+ for (let i = 1; i < loop.length; i++) d += ` L${loop[i][0]} ${loop[i][1]}`;
650
+ d += ' Z';
651
+ pathStrings.push(`<path d="${d}" />`);
652
+ }
653
+ group.innerHTML = pathStrings.join('');
654
+
655
+ const breaksByLoop = assignBreaksToLoops(polyLoops, this._getManualBreaks());
656
+ const autoBreaksEnabled = this._autoBreaksEnabled === true;
657
+ const suppressedByLoop = autoBreaksEnabled ? assignBreaksToLoops(polyLoops, this._getSuppressedBreaks()) : polyLoops.map(() => []);
658
+ const autoPoints = [];
659
+ const manualPoints = [];
660
+ const autoKeys = new Set();
661
+ const manualKeys = new Set();
662
+ const minSegLen = Math.max(0.5, 1e-6 / scaleAbs);
663
+ const cornerSpacing = edgeMinSpacing / scaleAbs;
664
+ for (let li = 0; li < polyLoops.length; li++) {
665
+ const loop = polyLoops[li];
666
+ if (!loop || loop.length < 2) continue;
667
+ const info = splitLoopIntoEdges(loop, {
668
+ angleDeg: edgeSplitAngle,
669
+ minSegLen,
670
+ cornerSpacing,
671
+ manualBreaks: breaksByLoop[li] || [],
672
+ suppressedBreaks: suppressedByLoop[li] || [],
673
+ autoBreaks: autoBreaksEnabled,
674
+ returnDebug: true,
675
+ });
676
+ const ring = Array.isArray(info?.ring) ? info.ring : [];
677
+ if (!ring.length) continue;
678
+ const pushPoint = (arr, set, pt) => {
679
+ const key = `${Math.round(pt[0] * 1000)},${Math.round(pt[1] * 1000)}`;
680
+ if (set.has(key)) return;
681
+ set.add(key);
682
+ arr.push(pt);
683
+ };
684
+ const autoIdx = Array.isArray(info?.corners) ? info.corners : [];
685
+ for (const idx of autoIdx) {
686
+ const pt = ring[idx];
687
+ if (pt) pushPoint(autoPoints, autoKeys, pt);
688
+ }
689
+ const manualIdx = Array.isArray(info?.manualCorners) ? info.manualCorners : [];
690
+ for (const idx of manualIdx) {
691
+ const pt = ring[idx];
692
+ if (pt) pushPoint(manualPoints, manualKeys, pt);
693
+ }
694
+ }
695
+
696
+ const autoR = 1;
697
+ const manualR = 1;
698
+ if (this.svgBreakpointsGroup) {
699
+ this.svgBreakpointsGroup.innerHTML = autoBreaksEnabled
700
+ ? autoPoints.map((p) => `<circle cx="${p[0]}" cy="${p[1]}" r="${autoR}" />`).join('')
701
+ : '';
702
+ }
703
+ if (this.svgManualBreaksGroup) {
704
+ this.svgManualBreaksGroup.innerHTML = manualPoints.map((p) => `<circle cx="${p[0]}" cy="${p[1]}" r="${manualR}" />`).join('');
705
+ }
706
+ if (this.svgSuppressedBreaksGroup) {
707
+ const suppressedPoints = autoBreaksEnabled ? this._getSuppressedBreaks() : [];
708
+ this.svgSuppressedBreaksGroup.innerHTML = suppressedPoints.map((p) => `<circle cx="${p[0]}" cy="${p[1]}" r="${autoR}" />`).join('');
709
+ }
710
+ this._autoBreakPoints = autoBreaksEnabled ? autoPoints.slice() : [];
711
+ this._updateBreakPointSizes();
712
+ }
713
+
714
+ // ------------------------------ Interaction ----------------------------
715
+ _canvasToImage(x, y) {
716
+ // Convert screen coords within canvas → image coords
717
+ const ix = (x - this.offsetX) / (this.scale || 1);
718
+ const iy = (y - this.offsetY) / (this.scale || 1);
719
+ return [ix, iy];
720
+ }
721
+
722
+ _updateBreakPointSizes() {
723
+ const viewScale = Math.max(1e-6, this.scale || 1);
724
+ const autoR = Math.max(1e-6, this._breakAutoPx / viewScale);
725
+ const manualR = Math.max(1e-6, this._breakManualPx / viewScale);
726
+ if (this.svgBreakpointsGroup) {
727
+ const circles = this.svgBreakpointsGroup.querySelectorAll('circle');
728
+ circles.forEach((c) => c.setAttribute('r', autoR));
729
+ }
730
+ if (this.svgManualBreaksGroup) {
731
+ const circles = this.svgManualBreaksGroup.querySelectorAll('circle');
732
+ circles.forEach((c) => c.setAttribute('r', manualR));
733
+ }
734
+ if (this.svgSuppressedBreaksGroup) {
735
+ const circles = this.svgSuppressedBreaksGroup.querySelectorAll('circle');
736
+ circles.forEach((c) => c.setAttribute('r', autoR));
737
+ }
738
+ }
739
+
740
+ _getManualBreaks() {
741
+ const raw = this.featureParams?.edgeBreakPoints;
742
+ if (!Array.isArray(raw)) return [];
743
+ const out = [];
744
+ for (const bp of raw) {
745
+ let x;
746
+ let y;
747
+ if (Array.isArray(bp)) {
748
+ x = Number(bp[0]);
749
+ y = Number(bp[1]);
750
+ } else if (bp && typeof bp === 'object') {
751
+ x = Number(bp.x ?? bp[0]);
752
+ y = Number(bp.y ?? bp[1]);
753
+ }
754
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
755
+ out.push([x, y]);
756
+ }
757
+ return out;
758
+ }
759
+
760
+ _getSuppressedBreaks() {
761
+ const raw = this.featureParams?.edgeSuppressedBreaks;
762
+ if (!Array.isArray(raw)) return [];
763
+ const out = [];
764
+ for (const bp of raw) {
765
+ let x;
766
+ let y;
767
+ if (Array.isArray(bp)) {
768
+ x = Number(bp[0]);
769
+ y = Number(bp[1]);
770
+ } else if (bp && typeof bp === 'object') {
771
+ x = Number(bp.x ?? bp[0]);
772
+ y = Number(bp.y ?? bp[1]);
773
+ }
774
+ if (!Number.isFinite(x) || !Number.isFinite(y)) continue;
775
+ out.push([x, y]);
776
+ }
777
+ return out;
778
+ }
779
+
780
+ _setManualBreaks(breaks) {
781
+ if (!this.featureParams) return;
782
+ this.featureParams.edgeBreakPoints = Array.isArray(breaks) ? breaks.map((p) => [p[0], p[1]]) : [];
783
+ this._vectorDirty = true;
784
+ this._scheduleVectorOverlayUpdate();
785
+ if (typeof this.onParamsChange === 'function') {
786
+ try { this.onParamsChange(); } catch (_) { }
787
+ }
788
+ }
789
+
790
+ _setSuppressedBreaks(breaks) {
791
+ if (!this.featureParams) return;
792
+ this.featureParams.edgeSuppressedBreaks = Array.isArray(breaks) ? breaks.map((p) => [p[0], p[1]]) : [];
793
+ this._vectorDirty = true;
794
+ this._scheduleVectorOverlayUpdate();
795
+ if (typeof this.onParamsChange === 'function') {
796
+ try { this.onParamsChange(); } catch (_) { }
797
+ }
798
+ }
799
+
800
+ _findNearestPointOnLoops(px, py, loops) {
801
+ const out = { dist2: Infinity, point: null };
802
+ if (!Array.isArray(loops) || !loops.length) return out;
803
+ for (const loop of loops) {
804
+ if (!Array.isArray(loop) || loop.length < 2) continue;
805
+ const ring = (loop.length > 1 && loop[0][0] === loop[loop.length - 1][0] && loop[0][1] === loop[loop.length - 1][1])
806
+ ? loop.slice(0, -1)
807
+ : loop;
808
+ const n = ring.length;
809
+ if (n < 2) continue;
810
+ for (let i = 0; i < n; i++) {
811
+ const a = ring[i];
812
+ const b = ring[(i + 1) % n];
813
+ const abx = b[0] - a[0];
814
+ const aby = b[1] - a[1];
815
+ const abLen2 = abx * abx + aby * aby;
816
+ if (abLen2 <= 0) continue;
817
+ let t = ((px - a[0]) * abx + (py - a[1]) * aby) / abLen2;
818
+ t = Math.max(0, Math.min(1, t));
819
+ const cx = a[0] + t * abx;
820
+ const cy = a[1] + t * aby;
821
+ const dx = px - cx;
822
+ const dy = py - cy;
823
+ const d2 = dx * dx + dy * dy;
824
+ if (d2 < out.dist2) {
825
+ out.dist2 = d2;
826
+ out.point = [cx, cy];
827
+ }
828
+ }
829
+ }
830
+ return out;
831
+ }
832
+
833
+ _toggleManualBreak(ix, iy) {
834
+ if (this._vectorDirty) this._updateVectorOverlay();
835
+ const breaks = this._getManualBreaks();
836
+ const autoBreaksEnabled = this._autoBreaksEnabled === true;
837
+ const suppressed = autoBreaksEnabled ? this._getSuppressedBreaks() : [];
838
+ const viewScale = Math.max(1e-6, this.scale || 1);
839
+ const removeDist = Math.max(1e-6, this._breakRemovePx / viewScale);
840
+ let removeIdx = -1;
841
+ let best = removeDist * removeDist;
842
+ for (let i = 0; i < breaks.length; i++) {
843
+ const bp = breaks[i];
844
+ const dx = bp[0] - ix;
845
+ const dy = bp[1] - iy;
846
+ const d2 = dx * dx + dy * dy;
847
+ if (d2 <= best) {
848
+ best = d2;
849
+ removeIdx = i;
850
+ }
851
+ }
852
+ if (removeIdx >= 0) {
853
+ breaks.splice(removeIdx, 1);
854
+ this._setManualBreaks(breaks);
855
+ this._render();
856
+ return;
857
+ }
858
+
859
+ if (autoBreaksEnabled) {
860
+ let suppressIdx = -1;
861
+ best = removeDist * removeDist;
862
+ for (let i = 0; i < suppressed.length; i++) {
863
+ const bp = suppressed[i];
864
+ const dx = bp[0] - ix;
865
+ const dy = bp[1] - iy;
866
+ const d2 = dx * dx + dy * dy;
867
+ if (d2 <= best) {
868
+ best = d2;
869
+ suppressIdx = i;
870
+ }
871
+ }
872
+ if (suppressIdx >= 0) {
873
+ suppressed.splice(suppressIdx, 1);
874
+ this._setSuppressedBreaks(suppressed);
875
+ this._render();
876
+ return;
877
+ }
878
+ }
879
+
880
+ const loops = this._vectorLoops;
881
+ if (!loops || !loops.length) return;
882
+ const snapDist = Math.max(1e-6, this._breakSnapPx / viewScale);
883
+ const nearest = this._findNearestPointOnLoops(ix, iy, loops);
884
+ if (!nearest.point || nearest.dist2 > snapDist * snapDist) return;
885
+ const dedupeDist = Math.max(1e-6, this._breakDedupePx / viewScale);
886
+ for (const bp of breaks) {
887
+ const dx = bp[0] - nearest.point[0];
888
+ const dy = bp[1] - nearest.point[1];
889
+ if ((dx * dx + dy * dy) <= dedupeDist * dedupeDist) return;
890
+ }
891
+ for (const bp of suppressed) {
892
+ const dx = bp[0] - nearest.point[0];
893
+ const dy = bp[1] - nearest.point[1];
894
+ if ((dx * dx + dy * dy) <= dedupeDist * dedupeDist) return;
895
+ }
896
+
897
+ if (autoBreaksEnabled) {
898
+ const autoPoints = Array.isArray(this._autoBreakPoints) ? this._autoBreakPoints : [];
899
+ let autoIdx = -1;
900
+ let autoBest = removeDist * removeDist;
901
+ for (let i = 0; i < autoPoints.length; i++) {
902
+ const ap = autoPoints[i];
903
+ const dx = ap[0] - nearest.point[0];
904
+ const dy = ap[1] - nearest.point[1];
905
+ const d2 = dx * dx + dy * dy;
906
+ if (d2 <= autoBest) {
907
+ autoBest = d2;
908
+ autoIdx = i;
909
+ }
910
+ }
911
+ if (autoIdx >= 0) {
912
+ suppressed.push([autoPoints[autoIdx][0], autoPoints[autoIdx][1]]);
913
+ this._setSuppressedBreaks(suppressed);
914
+ this._render();
915
+ return;
916
+ }
917
+ }
918
+
919
+ breaks.push([nearest.point[0], nearest.point[1]]);
920
+ this._setManualBreaks(breaks);
921
+ this._render();
922
+ }
923
+
924
+ _pointerDown(e) {
925
+ if (!this.canvas) return;
926
+ const rect = this.canvas.getBoundingClientRect();
927
+ const x = e.clientX - rect.left;
928
+ const y = e.clientY - rect.top;
929
+
930
+ const spacePan = e.buttons === 1 && this._spaceHeld;
931
+ const middlePan = e.buttons === 4; // middle mouse
932
+ const rightPan = e.button === 2 || e.buttons === 2; // right mouse
933
+ const activePan = (this.tool === 'pan') || spacePan || middlePan || rightPan;
934
+
935
+ // Check resize handle first
936
+ if (this._hitResizeHandle(x, y)) {
937
+ this.isResizingCanvas = true;
938
+ this.lastX = x; this.lastY = y;
939
+ return;
940
+ }
941
+
942
+ if (activePan) {
943
+ this.isPanning = true;
944
+ this.lastX = x; this.lastY = y;
945
+ return;
946
+ }
947
+
948
+ if (e.buttons !== 1) return; // left only for drawing
949
+ const [ix, iy] = this._canvasToImage(x, y);
950
+ // update hover
951
+ this.hoverX = ix; this.hoverY = iy; this.isHovering = true;
952
+ if (this.tool === 'break') {
953
+ this._toggleManualBreak(ix, iy);
954
+ return;
955
+ }
956
+ if (this.tool === 'bucket') {
957
+ this._applyBucket(Math.floor(ix), Math.floor(iy));
958
+ this._pushHistory();
959
+ this._render();
960
+ return;
961
+ }
962
+ this.isDrawing = true;
963
+ this.lastX = ix; this.lastY = iy;
964
+ this._applyStroke(ix, iy, true);
965
+ }
966
+
967
+ _pointerMove(e) {
968
+ if (!this.canvas) return;
969
+ const rect = this.canvas.getBoundingClientRect();
970
+ const x = e.clientX - rect.left;
971
+ const y = e.clientY - rect.top;
972
+
973
+ // Cursor feedback for resize handle
974
+ if (!this.isPanning && !this.isDrawing && !this.isResizingCanvas) {
975
+ if (this._hitResizeHandle(x, y)) this.canvas.style.cursor = 'nwse-resize';
976
+ else if (this.tool === 'break') this.canvas.style.cursor = 'crosshair';
977
+ else this.canvas.style.cursor = '';
978
+ }
979
+
980
+ if (this.isResizingCanvas) {
981
+ // compute new size in image pixels based on mouse position
982
+ const newW = Math.max(1, Math.round((x - this.offsetX) / (this.scale || 1)));
983
+ const newH = Math.max(1, Math.round((y - this.offsetY) / (this.scale || 1)));
984
+ this._resizeWorkArea(newW, newH);
985
+ this._render();
986
+ this.lastX = x; this.lastY = y;
987
+ return;
988
+ }
989
+
990
+ if (this.isPanning) {
991
+ const dx = x - this.lastX; const dy = y - this.lastY;
992
+ this.offsetX += dx; this.offsetY += dy;
993
+ this.lastX = x; this.lastY = y;
994
+ this._render();
995
+ return;
996
+ }
997
+
998
+ if (this.isDrawing) {
999
+ const [ix, iy] = this._canvasToImage(x, y);
1000
+ this._applyStroke(ix, iy, false);
1001
+ this.lastX = ix; this.lastY = iy;
1002
+ this._render();
1003
+ return;
1004
+ }
1005
+
1006
+ // Update hover and render cursor preview when idle
1007
+ const [hix, hiy] = this._canvasToImage(x, y);
1008
+ this.hoverX = hix; this.hoverY = hiy; this.isHovering = true;
1009
+ this._render();
1010
+ }
1011
+
1012
+ _pointerUp(_e) {
1013
+ if (this.isResizingCanvas) { this.isResizingCanvas = false; this._pushHistory(); return; }
1014
+ if (this.isPanning) { this.isPanning = false; return; }
1015
+ if (!this.isDrawing) return;
1016
+ this.isDrawing = false;
1017
+ this._pushHistory();
1018
+ }
1019
+
1020
+ _hitResizeHandle(viewX, viewY) {
1021
+ if (!this.workWidth || !this.workHeight) return false;
1022
+ const hs = this.resizeHandleSize;
1023
+ const rx = this.offsetX + this.workWidth * this.scale - hs;
1024
+ const ry = this.offsetY + this.workHeight * this.scale - hs;
1025
+ return viewX >= rx && viewY >= ry && viewX <= rx + hs && viewY <= ry + hs;
1026
+ }
1027
+
1028
+ _resizeWorkArea(newW, newH) {
1029
+ if (newW === this.workWidth && newH === this.workHeight) return;
1030
+ this.workWidth = newW;
1031
+ this.workHeight = newH;
1032
+ // ensure draw canvas matches work area, preserving edits
1033
+ this._resizeDrawCanvas(newW, newH, /*preserve*/ true);
1034
+ this._vectorDirty = true;
1035
+ this._scheduleVectorOverlayUpdate();
1036
+ }
1037
+
1038
+ _resizeDrawCanvas(newW, newH, preserve) {
1039
+ const old = this.drawCanvas;
1040
+ if (!old || (!preserve && (old.width === newW && old.height === newH))) {
1041
+ if (old) { old.width = newW; old.height = newH; this.drawCtx = old.getContext('2d'); }
1042
+ return;
1043
+ }
1044
+ const nc = document.createElement('canvas');
1045
+ nc.width = newW; nc.height = newH;
1046
+ const nctx = nc.getContext('2d');
1047
+ if (preserve && old.width && old.height) {
1048
+ nctx.drawImage(old, 0, 0);
1049
+ }
1050
+ this.drawCanvas = nc;
1051
+ this.drawCtx = nctx;
1052
+ }
1053
+
1054
+ _applyStroke(ix, iy, start) {
1055
+ const ctx = this.drawCtx;
1056
+ if (!ctx) return;
1057
+ const r = Math.max(0.5, this.brushSize / 2);
1058
+ const drawDab = (x, y) => {
1059
+ ctx.beginPath();
1060
+ if (this.brushShape === 'square') {
1061
+ ctx.rect(x - r, y - r, 2 * r, 2 * r);
1062
+ } else if (this.brushShape === 'diamond') {
1063
+ ctx.moveTo(x, y - r);
1064
+ ctx.lineTo(x + r, y);
1065
+ ctx.lineTo(x, y + r);
1066
+ ctx.lineTo(x - r, y);
1067
+ ctx.closePath();
1068
+ } else {
1069
+ ctx.arc(x, y, r, 0, Math.PI * 2);
1070
+ }
1071
+ if (this.tool === 'eraser') {
1072
+ ctx.globalCompositeOperation = 'destination-out';
1073
+ ctx.fillStyle = 'rgba(0,0,0,1)';
1074
+ } else {
1075
+ ctx.globalCompositeOperation = 'source-over';
1076
+ ctx.fillStyle = this.brushColor;
1077
+ }
1078
+ ctx.fill();
1079
+ };
1080
+
1081
+ ctx.save();
1082
+ if (start) {
1083
+ drawDab(ix, iy);
1084
+ } else {
1085
+ const sx = this.lastX, sy = this.lastY;
1086
+ const dx = ix - sx, dy = iy - sy;
1087
+ const dist = Math.hypot(dx, dy);
1088
+ const step = Math.max(0.5, r * 0.6);
1089
+ const steps = Math.max(1, Math.ceil(dist / step));
1090
+ for (let i = 1; i <= steps; i++) {
1091
+ const t = i / steps;
1092
+ drawDab(sx + dx * t, sy + dy * t);
1093
+ }
1094
+ }
1095
+ this._vectorDirty = true;
1096
+ ctx.restore();
1097
+ }
1098
+
1099
+ _applyBucket(ix, iy) {
1100
+ if (!this.workWidth || !this.workHeight) return;
1101
+ if (!this.drawCtx) return;
1102
+ const w = this.workWidth | 0, h = this.workHeight | 0;
1103
+ const x0 = Math.max(0, Math.min(w - 1, Math.floor(ix)));
1104
+ const y0 = Math.max(0, Math.min(h - 1, Math.floor(iy)));
1105
+ // Composite image for region detection
1106
+ const comp = document.createElement('canvas');
1107
+ comp.width = w; comp.height = h;
1108
+ const cctx = comp.getContext('2d');
1109
+ if (this.bgImage && !this._baseImageOnDrawCanvas) cctx.drawImage(this.bgImage, 0, 0);
1110
+ if (this.drawCanvas) cctx.drawImage(this.drawCanvas, 0, 0);
1111
+ const id = cctx.getImageData(0, 0, w, h);
1112
+ const data = id.data;
1113
+ const idx0 = (y0 * w + x0) * 4;
1114
+ const tr = data[idx0], tg = data[idx0 + 1], tb = data[idx0 + 2], ta = data[idx0 + 3];
1115
+ const target = (ta << 24) | (tb << 16) | (tg << 8) | tr;
1116
+
1117
+ // Flood fill mask
1118
+ const stack = [x0, y0];
1119
+ const visited = new Uint8Array(w * h);
1120
+ const mask = new Uint8Array(w * h);
1121
+ const tol = Math.max(0, Math.min(255, this.bucketTolerance | 0));
1122
+ while (stack.length) {
1123
+ const y = stack.pop() | 0; const x = stack.pop() | 0;
1124
+ if (x < 0 || y < 0 || x >= w || y >= h) continue;
1125
+ const i = y * w + x;
1126
+ if (visited[i]) continue;
1127
+ const k = i * 4; const r = data[k], g = data[k + 1], b = data[k + 2];
1128
+ // RGB max-channel distance tolerance
1129
+ if (Math.max(Math.abs(r - tr), Math.abs(g - tg), Math.abs(b - tb)) > tol) { visited[i] = 1; continue; }
1130
+ visited[i] = 1;
1131
+ mask[i] = 1;
1132
+ stack.push(x - 1, y);
1133
+ stack.push(x + 1, y);
1134
+ stack.push(x, y - 1);
1135
+ stack.push(x, y + 1);
1136
+ }
1137
+
1138
+ // Apply fill color to draw layer only
1139
+ const di = this.drawCtx.getImageData(0, 0, w, h);
1140
+ const dd = di.data;
1141
+ const [fr, fg, fb, fa] = this._hexToRgba(this.brushColor, 255);
1142
+ for (let i = 0; i < w * h; i++) {
1143
+ if (!mask[i]) continue;
1144
+ const k = i * 4;
1145
+ dd[k] = fr; dd[k + 1] = fg; dd[k + 2] = fb; dd[k + 3] = fa;
1146
+ }
1147
+ this.drawCtx.putImageData(di, 0, 0);
1148
+ this._vectorDirty = true;
1149
+ }
1150
+
1151
+ _hexToRgba(hex, alphaOverride) {
1152
+ let s = String(hex || '').trim();
1153
+ if (s[0] === '#') s = s.slice(1);
1154
+ if (s.length === 3) s = s.split('').map(ch => ch + ch).join('');
1155
+ let r = 0, g = 0, b = 0, a = 255;
1156
+ if (s.length >= 6) {
1157
+ r = parseInt(s.slice(0, 2), 16) | 0;
1158
+ g = parseInt(s.slice(2, 4), 16) | 0;
1159
+ b = parseInt(s.slice(4, 6), 16) | 0;
1160
+ }
1161
+ if (typeof alphaOverride === 'number') a = Math.max(0, Math.min(255, alphaOverride | 0));
1162
+ return [r, g, b, a];
1163
+ }
1164
+
1165
+ _wheel(e) {
1166
+ e.preventDefault();
1167
+ const rect = this.canvas.getBoundingClientRect();
1168
+ const mx = e.clientX - rect.left;
1169
+ const my = e.clientY - rect.top;
1170
+ const [ix, iy] = this._canvasToImage(mx, my);
1171
+ const delta = e.deltaY > 0 ? 0.9 : 1.1111111;
1172
+ const newScale = Math.max(this.minScale, Math.min(this.maxScale, this.scale * delta));
1173
+ const k = newScale / (this.scale || 1);
1174
+ // zoom around mouse
1175
+ this.offsetX = mx - (ix * newScale);
1176
+ this.offsetY = my - (iy * newScale);
1177
+ this.scale = newScale;
1178
+ this._render();
1179
+ }
1180
+
1181
+ _key(e) {
1182
+ this._spaceHeld = (e.type === 'keydown' && e.code === 'Space') ? true : (e.type === 'keyup' && e.code === 'Space' ? false : this._spaceHeld);
1183
+ if (e.type === 'keydown') {
1184
+ if (e.key === 'Escape') { this._cancel(); }
1185
+ if (e.key === 'Enter') { this._finish(); }
1186
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z') { this._undo(); e.preventDefault(); }
1187
+ if ((e.ctrlKey || e.metaKey) && (e.key.toLowerCase() === 'y' || (e.shiftKey && e.key.toLowerCase() === 'z'))) { this._redo(); e.preventDefault(); }
1188
+ if (e.key.toLowerCase() === 'b') { this.tool = 'brush'; this._updateButtons(); }
1189
+ if (e.key.toLowerCase() === 'e') { this.tool = 'eraser'; this._updateButtons(); }
1190
+ if (e.key.toLowerCase() === 'g') { this.tool = 'bucket'; this._updateButtons(); }
1191
+ if (e.key.toLowerCase() === 'f') { this._resetViewToFit(); this._render(); }
1192
+ }
1193
+ }
1194
+
1195
+ _updateButtons() {
1196
+ const setActive = (el, on) => { if (!el) return; el.classList.toggle('active', !!on); };
1197
+ setActive(this.brushBtn, this.tool === 'brush');
1198
+ setActive(this.eraserBtn, this.tool === 'eraser');
1199
+ setActive(this.panBtn, this.tool === 'pan');
1200
+ setActive(this.breakBtn, this.tool === 'break');
1201
+ setActive(this.bucketBtn, this.tool === 'bucket');
1202
+ if (this.colorInput && this.brushColor) this.colorInput.value = this.brushColor;
1203
+ if (this.sizeInput) this.sizeInput.value = String(this.brushSize);
1204
+ if (this.shapeSelect) this.shapeSelect.value = String(this.brushShape || 'round');
1205
+ if (this.undoBtn) this.undoBtn.disabled = this.undoStack.length <= 1;
1206
+ if (this.redoBtn) this.redoBtn.disabled = this.redoStack.length === 0;
1207
+ }
1208
+
1209
+ // ------------------------------ History --------------------------------
1210
+ _pushHistory() {
1211
+ if (!this.drawCtx || !this.drawCanvas) return;
1212
+ try {
1213
+ const snap = this.drawCtx.getImageData(0, 0, this.drawCanvas.width, this.drawCanvas.height);
1214
+ this.undoStack.push(snap);
1215
+ if (this.undoStack.length > this.maxHistory) this.undoStack.shift();
1216
+ this.redoStack.length = 0; // clear redo on new action
1217
+ this._updateButtons();
1218
+ } catch { }
1219
+ }
1220
+
1221
+ _undo() {
1222
+ if (this.undoStack.length <= 1) return;
1223
+ const current = this.undoStack.pop();
1224
+ if (current) this.redoStack.push(current);
1225
+ const prev = this.undoStack[this.undoStack.length - 1];
1226
+ if (prev) {
1227
+ this.drawCtx.putImageData(prev, 0, 0);
1228
+ this._render();
1229
+ this._updateButtons();
1230
+ this._vectorDirty = true;
1231
+ }
1232
+ }
1233
+
1234
+ _redo() {
1235
+ if (!this.redoStack.length) return;
1236
+ const next = this.redoStack.pop();
1237
+ if (next) {
1238
+ this.undoStack.push(next);
1239
+ this.drawCtx.putImageData(next, 0, 0);
1240
+ this._render();
1241
+ this._updateButtons();
1242
+ this._vectorDirty = true;
1243
+ }
1244
+ }
1245
+
1246
+ // ------------------------------ Finalize --------------------------------
1247
+ _finish() {
1248
+ // Composite background + draw layer at current work area size
1249
+ const w = this.workWidth || this.bgImage?.width || this.drawCanvas?.width || 0;
1250
+ const h = this.workHeight || this.bgImage?.height || this.drawCanvas?.height || 0;
1251
+ if (!w || !h) { this._cancel(); return; }
1252
+ const out = document.createElement('canvas');
1253
+ out.width = w; out.height = h;
1254
+ const octx = out.getContext('2d');
1255
+ if (this.bgImage && !this._baseImageOnDrawCanvas) octx.drawImage(this.bgImage, 0, 0);
1256
+ if (this.drawCanvas) octx.drawImage(this.drawCanvas, 0, 0);
1257
+ const dataUrl = out.toDataURL('image/png');
1258
+ if (typeof this.onSaveCallback === 'function') {
1259
+ try { this.onSaveCallback(dataUrl); } catch { }
1260
+ }
1261
+ this.close();
1262
+ }
1263
+
1264
+ _cancel() {
1265
+ if (typeof this.onCancelCallback === 'function') {
1266
+ try { this.onCancelCallback(); } catch { }
1267
+ }
1268
+ this.close();
1269
+ }
1270
+ }