Complete research project

This commit is contained in:
Nettika 2026-01-27 17:14:59 -08:00
parent 94acfe3ba1
commit 58b74dcc50
No known key found for this signature in database
16 changed files with 2973 additions and 53 deletions

View file

@ -0,0 +1,142 @@
# Core Architecture
## Summary
MatterControl is a comprehensive 3D printing workflow application built on .NET 6.0, utilizing a custom 2D/3D rendering engine (agg-sharp) with OpenGL acceleration. The architecture follows a modular design with clear separation between UI, printing infrastructure, slicing, and data persistence layers.
## Technical Description
### Overall Architecture
MatterControl employs a layered architecture consisting of:
1. **Presentation Layer** - Custom UI framework (agg-sharp/Gui) with OpenGL rendering
2. **Application Layer** - Central controller pattern via `ApplicationController`
3. **Domain Layer** - Printing, slicing, mesh operations, design tools
4. **Infrastructure Layer** - SQLite persistence, file I/O, serial communication
### Entry Point and Initialization Flow
The application entry point is `Program.cs` which orchestrates the following initialization sequence:
1. **StaticData Resolution** - Locates the `StaticData` directory containing resources (icons, fonts, profiles, translations)
2. **Culture Configuration** - Sets `CultureInfo.InvariantCulture` globally for consistent number/date formatting
3. **Serial Port Factory** - Registers platform-specific serial port implementation (`CSharpSerialPortWrapper`)
4. **Window Provider Selection** - Configures either GLFW or WinForms-based window provider
5. **Single Instance Handling** - Uses `LocalService` to ensure only one instance runs (production builds)
6. **Configuration Loading** - Loads settings from `appsettings.json` and user profile `MatterControl.json`
7. **Database Initialization** - Initializes SQLite datastore via `Datastore.Instance.Initialize()`
8. **DPI Awareness** - Configures per-monitor DPI awareness on Windows
9. **Root Window Creation** - Creates `RootSystemWindow` and displays it
### Design Rationale
**Custom Rendering Engine (agg-sharp)**: Rather than using WPF or WinForms controls directly, MatterControl uses a custom rendering abstraction. This provides:
- Cross-platform consistency (same rendering on Windows, Mac, Linux)
- Direct control over 3D viewport rendering with OpenGL
- Pixel-perfect UI scaling with `GuiWidget.DeviceScale`
- Unified input handling across platforms
**Single ApplicationController Instance**: The singleton `ApplicationController.Instance` serves as the central coordination point, managing:
- Active workspaces and printers
- Theme configuration
- Library and content providers
- Plugin registration points
- Application lifecycle events
**Workspace-Based Model**: The application uses `PartWorkspace` objects to represent open "tabs" which can be either:
- Design workspaces (standalone 3D scenes)
- Printer workspaces (associated with a specific printer)
This allows multiple concurrent editing sessions while supporting multiple connected printers.
### Module Organization
| Project | Purpose |
|---------|---------|
| `MatterControl` | Main executable, entry point, Windows-specific code |
| `MatterControlLib` | Core application logic, UI, all major features |
| `MatterControl.Printing` | GCode processing, printer communication abstractions |
| `MatterControl.OpenGL` | OpenGL rendering utilities |
| `MatterControl.MeshOperations` | Property grid and mesh editing interfaces |
| `MatterControl.SLA` | SLA/resin printer support (Photon format) |
| `MatterControl.Winforms` | WinForms window provider implementation |
| `MatterControl.Common` | Shared utilities and interfaces |
| `Community.CsharpSqlite` | SQLite database implementation |
### Key External Dependencies
- **agg-sharp**: Custom 2D graphics, UI widgets, vector math, polygon mesh operations
- **MatterSlice**: Integrated slicing engine
- **Newtonsoft.Json**: JSON serialization
- **Markdig**: Markdown rendering
- **PDFsharpNetStandard2**: PDF generation
- **Lucene.Net**: Full-text search indexing
- **Zeroconf**: Network printer discovery
### Configuration System
Configuration is loaded from multiple sources with increasing priority:
1. Built-in defaults
2. `appsettings.json` (application-level)
3. `~/MatterControl.json` (user-level)
4. Command-line arguments
The `IConfiguration` interface binds to:
- `Agg:ProviderTypes` - Window/graphics providers
- `Agg:GraphicsMode` - OpenGL configuration
- `MatterControl:Slicer:Debug` - In-process slicing for debugging
- `MatterControl:Application:EnableNetworkTraffic` - Network features toggle
## Reference
### Entry Point
| Class/Method | Location | Description |
|--------------|----------|-------------|
| `Program.Main()` | [Program.cs:83](Program.cs#L83) | Application entry point |
| `MainOutputDirectoryAttribute` | [Program.cs:326](Program.cs#L326) | Assembly attribute for build path resolution |
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `ApplicationController` | [MatterControlLib/ApplicationView/ApplicationController.cs](MatterControlLib/ApplicationView/ApplicationController.cs) | Central singleton managing application state |
| `RootSystemWindow` | [MatterControlLib/RootSystemWindow.cs](MatterControlLib/RootSystemWindow.cs) | Main application window |
| `MatterControlApplication` | [MatterControlLib/MatterControlApplication.cs](MatterControlLib/MatterControlApplication.cs) | Static configuration (MCWS base URI) |
| `AppContext` | [MatterControlLib/ApplicationView/AppContext.cs](MatterControlLib/ApplicationView/AppContext.cs) | Global context (theme, platform features) |
### Key Interfaces
| Interface | Purpose |
|-----------|---------|
| `INativePlatformFeatures` | Platform-specific functionality abstraction |
| `ISystemWindowProvider` | Window creation and management |
| `IStaticData` | Static resource access |
### Important Events
| Event | Publisher | Description |
|-------|-----------|-------------|
| `WorkspacesChanged` | `ApplicationController` | Fired when tabs are added/removed |
| `ApplicationError` | `ApplicationController` | Error logging hook |
| `ApplicationEvent` | `ApplicationController` | General event logging |
| `AnyPrintStarted/Canceled/Complete` | `ApplicationController` | Print lifecycle events |
### Initialization Order
```
Program.Main()
├── StaticData.OverrideRootPath()
├── CultureInfo configuration
├── FrostedSerialPortFactory setup
├── AggContext.Config.ProviderTypes
├── LocalService.TryStartServer()
├── IConfiguration loading
├── Datastore.Instance.Initialize()
├── DPI awareness setup
├── RootSystemWindow.GetStartupBounds()
├── Application.LoadRootWindow()
├── ApplicationController.Instance.Theme
└── rootSystemWindow.ShowAsSystemWindow()
```

View file

@ -0,0 +1,197 @@
# Application Controller
## Summary
The `ApplicationController` is the central singleton orchestrating all major application functionality in MatterControl. It manages workspaces, printers, library containers, tasks, theming, and serves as the plugin registration point for extensibility.
## Technical Description
### Singleton Architecture
`ApplicationController` uses a lazy singleton pattern accessed via `ApplicationController.Instance`. The constructor is private, ensuring only one instance exists throughout the application lifecycle. This design:
- Provides a single coordination point for all subsystems
- Enables plugins to register callbacks and hooks
- Maintains consistent state across the application
- Simplifies cross-component communication
### Workspace Management
The application uses an `ObservableCollection<PartWorkspace>` to manage open tabs:
```
PartWorkspace
├── SceneContext (ISceneContext) - 3D scene editing context
├── Printer (PrinterConfig) - Associated printer (null for design-only tabs)
├── LibraryView (ILibraryContext) - Library browsing context
├── Name - Display name for the tab
└── ContentPath - Path to source file
```
**Workspace Types:**
1. **Design Workspaces**: `Printer == null`, standalone 3D design editing
2. **Printer Workspaces**: `Printer != null`, tied to a specific printer for printing
**Persistence**: Workspace layouts are persisted to `OpenTabsPath` as JSON when:
- Tabs are added/removed (via `CollectionChanged` event)
- Application closes
- User explicitly saves
### Library System Integration
ApplicationController initializes and manages the library hierarchy:
```
Library.RootLibaryContainer
├── Computer (FileSystemContainer)
├── Local Library (SqliteLibraryContainer) - if items exist
├── Queue (FileSystemContainer)
├── Bundled Parts (BundledPartsCollectionContainer)
├── Custom Library Folders (from CustomLibraryFoldersPath)
└── History (RootHistoryContainer)
```
Content providers are registered for file types:
| Extensions | Provider |
|------------|----------|
| stl, obj, 3mf, amf, mcx | `MeshContentProvider` |
| gcode | `GCodeContentProvider` |
| png, gif, jpg, jpeg | `ImageContentProvider` |
| scad | `OpenScadContentProvider` |
### Task Management System
The `Tasks` property (`RunningTasksConfig`) provides background task execution:
```csharp
Tasks.Execute("Task Name", owner, async (progress, cancellationToken) => {
// Background work with progress reporting
progress?.Invoke(0.5, "Halfway done");
});
```
Features:
- Progress reporting with percentage and status text
- Cancellation support
- Optional pause/resume/stop actions
- Visual task display in UI via `RunningTasksWidget`
### Plugin Registration Points
ApplicationController exposes several `Func` and `Action` delegates for plugin integration:
| Property | Type | Purpose |
|----------|------|---------|
| `GetPrinterProfileAsync` | `Func<PrinterInfo, string, Task<PrinterSettings>>` | Cloud profile retrieval |
| `SyncCloudProfiles` | `Func<string, Action<double,string>, Task>` | Cloud sync execution |
| `GetPublicProfileList` | `Func<Task<OemProfileDictionary>>` | Public profile listing |
| `DownloadPublicProfileAsync` | `Func<string, Task<PrinterSettings>>` | Public profile download |
| `GuestUserActive` | `Func<bool>` | Authentication state check |
| `GetAuthPage` | `Func<AuthenticationContext, DialogPage>` | Auth dialog factory |
| `UserHasPermission` | `Func<IObject3D, bool>` | Object permission check |
| `UserHasPro` | `Func<bool>` | Pro license validation |
| `PushPrintTaskToServer` | `Func<PrintTask, Task<Dictionary<string,string>>>` | Cloud print tracking |
### Font Management
The `TypeFaceCache` dictionary manages loaded fonts with lazy loading:
1. Static fonts loaded at startup (Liberation Sans/Mono)
2. User fonts loaded from `ApplicationFontsDataPath` on demand
3. System fonts loaded from Windows Fonts folder as fallback
4. Falls back to Liberation_Sans if font not found
### Event System
Key events for application coordination:
| Event | Purpose |
|-------|---------|
| `WorkspacesChanged` | Tab added/removed/restored |
| `CloudSyncStatusChanged` | Cloud sync state changes |
| `DoneReloadingAll` | Full UI reload completed |
| `ActiveProfileModified` | Printer profile changed |
| `ReloadSettingsTriggered` | Settings panel refresh needed |
| `ShellFileOpened` | External file opened |
| `AnyPrintStarted/Canceled/Complete` | Print lifecycle |
| `ApplicationError` | Error logging |
| `ApplicationEvent` | General event logging |
### AppContext Static Class
`AppContext` provides global application state:
| Property | Type | Description |
|----------|------|-------------|
| `Platform` | `INativePlatformFeatures` | Platform-specific functionality |
| `Options` | `MatterControlOptions` | Runtime options |
| `IsLoading` | `bool` | Application loading state |
| `RootSystemWindow` | `SystemWindow` | Main window reference |
| `Theme` | `ThemeConfig` | Current theme |
| `MenuTheme` | `ThemeConfig` | Menu theme variant |
| `ThemeProviders` | `Dictionary<string, IColorTheme>` | Available themes |
### Design Rationale
**Singleton vs Dependency Injection**: The singleton pattern was chosen over DI for simplicity and because the application has a single-user, single-window model. All state is naturally global.
**Plugin Delegates vs Interfaces**: Using `Func`/`Action` delegates instead of interfaces for plugins allows:
- Optional plugin features (null = not implemented)
- Simple registration without assembly scanning
- Runtime flexibility in plugin loading
**Observable Workspaces**: Using `ObservableCollection` enables automatic UI updates when tabs change without manual event wiring in the view layer.
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `ApplicationController` | [ApplicationView/ApplicationController.cs](MatterControlLib/ApplicationView/ApplicationController.cs) | Central singleton |
| `AppContext` | [ApplicationView/AppContext.cs](MatterControlLib/ApplicationView/AppContext.cs) | Global static state |
| `PartWorkspace` | [ApplicationView/PartWorkspace.cs](MatterControlLib/ApplicationView/PartWorkspace.cs) | Tab/workspace definition |
| `WorkspacesChangedEventArgs` | [ApplicationView/WorkspacesChangedEventArgs.cs](MatterControlLib/ApplicationView/WorkspacesChangedEventArgs.cs) | Workspace change event |
### Key Properties
| Property | Type | Description |
|----------|------|-------------|
| `Instance` | `ApplicationController` | Singleton accessor |
| `Workspaces` | `ObservableCollection<PartWorkspace>` | Open tabs |
| `ActivePrinters` | `IEnumerable<PrinterConfig>` | Connected printers |
| `Library` | `LibraryConfig` | Library configuration |
| `LibraryTabContext` | `ILibraryContext` | SaveAs library context |
| `Tasks` | `RunningTasksConfig` | Background task manager |
| `Thumbnails` | `ThumbnailsConfig` | Thumbnail generation |
| `EditorExtensions` | `EditorExtensionsConfig` | Editor plugin registry |
| `Theme` | `ThemeConfig` | Current theme |
| `MenuTheme` | `ThemeConfig` | Menu theme |
| `MainView` | `MainViewWidget` | Main UI widget |
| `HelpArticles` | `HelpArticle` | Help content |
| `TypeFaceCache` | `Dictionary<string, TypeFace>` | Loaded fonts |
### Key Methods
| Method | Description |
|--------|-------------|
| `OnWorkspacesChanged()` | Fire workspace change event |
| `ClosePrinter()` | Disconnect and close printer |
| `ExportLibraryItems()` | Export items to file |
| `PersistOpenTabsLayout()` | Save workspace state |
| `PersistPrintTabsContent()` | Save printer workspace content |
| `ReloadSettings()` | Refresh settings UI |
| `ShowNotification()` | Display timed notification |
| `Shutdown()` | Graceful application shutdown |
| `GetTypeFace()` | Lazy-load font by name |
| `GetWorkspaceActions()` | Build context menu actions |
| `LaunchBrowser()` | Open URL in default browser |
### Supporting Classes
| Class | Location | Description |
|-------|----------|-------------|
| `RunningTasksConfig` | [PartPreviewWindow/RunningTasksConfig.cs](MatterControlLib/PartPreviewWindow/RunningTasksConfig.cs) | Task execution |
| `LibraryConfig` | [Library/LibraryConfig.cs](MatterControlLib/Library/LibraryConfig.cs) | Library management |
| `ThumbnailsConfig` | [Library/ThumbnailsConfig.cs](MatterControlLib/Library/ThumbnailsConfig.cs) | Thumbnail generation |
| `EditorExtensionsConfig` | [DesignTools/EditorExtensionsConfig.cs](MatterControlLib/DesignTools/EditorExtensionsConfig.cs) | Editor plugins |

217
research/03-ui-rendering.md Normal file
View file

@ -0,0 +1,217 @@
# UI & Rendering System
## Summary
MatterControl uses a custom UI framework called **agg-sharp** that provides both 2D vector graphics rendering and OpenGL-accelerated 3D viewport rendering. The UI is built on `GuiWidget` components with a flexible layout system, theming support, and cross-platform window abstraction.
## Technical Description
### agg-sharp Framework
The agg-sharp library (Anti-Grain Geometry for C#) is a custom rendering abstraction layer providing:
1. **2D Vector Graphics** - Software rendering with optional hardware acceleration
2. **Widget System** - `GuiWidget` base class with layout, input handling, and invalidation
3. **OpenGL Integration** - Hardware-accelerated 3D rendering
4. **Platform Abstraction** - Window creation via `ISystemWindowProvider`
### Widget Architecture
All UI elements inherit from `GuiWidget`:
```
GuiWidget (base)
├── BackgroundColor, Border, Padding, Margin
├── HAnchor, VAnchor (layout anchoring)
├── Children collection
├── Input events (Click, MouseMove, KeyDown, etc.)
└── Invalidation and redraw system
```
**Layout System:**
- `HAnchor` / `VAnchor` enums: `None`, `Left`, `Center`, `Right`, `Stretch`, `Fit`
- `FlowLayoutWidget` - horizontal or vertical flow layout
- `Toolbar` - specialized horizontal toolbar with overflow support
- `DockingTabControl` - sidebar panel docking
### Main UI Structure
```
RootSystemWindow
└── MainViewWidget (FlowLayoutWidget, TopToBottom)
├── TabBar (ChromeTabs)
│ ├── ChromeTab (Design/Printer tabs)
│ │ └── TabContent (PrinterTabPage or DesignTabPage)
│ └── NewTabButton (+)
└── StatusBar (Toolbar)
├── StatusMessage
├── UpdateAvailableButton
└── TasksContainer
```
### Tab System
MatterControl uses a Chrome-style tabbed interface:
| Class | Purpose |
|-------|---------|
| `SimpleTabs` | Base tabs with toolbar and content area |
| `ChromeTabs` | Chrome-style tabs with drag, reorder, close |
| `ChromeTab` | Individual draggable tab |
| `ITab` | Tab interface (TabContent, Key, Text) |
**Tab Types:**
- **PrinterTabPage** - Printer-specific view with 3D preview, controls, settings
- **DesignTabPage** - Standalone design editing view
- **HelpTabPage** - Integrated help browser
### Theming System
Themes are managed through `ThemeConfig` and `ThemeSet`:
```
ThemeSet
├── Theme (ThemeConfig) - Main theme
├── MenuTheme (ThemeConfig) - Menu variant
└── Name, SchemeVersion
```
**ThemeConfig Properties:**
| Property | Type | Description |
|----------|------|-------------|
| `PrimaryAccentColor` | `Color` | Main accent color |
| `BackgroundColor` | `Color` | Window background |
| `TextColor` | `Color` | Primary text |
| `TabBarBackground` | `Color` | Tab bar background |
| `TabBodyBackground` | `Color` | Tab content background |
| `DefaultFontSize` | `int` | Base font size |
| `ButtonHeight` | `double` | Standard button height |
Themes are loaded from JSON files in `StaticData/Themes/System/`:
- `Modern-Dark.json`
- `Modern-Light.json`
- Custom OEM themes
### Custom Widgets
MatterControl provides specialized widgets beyond basic agg-sharp:
| Widget | Location | Purpose |
|--------|----------|---------|
| `DockingTabControl` | CustomWidgets/ | Collapsible side panel |
| `SolidSlider` | CustomWidgets/ | Value slider with fill |
| `DoubleSolidSlider` | CustomWidgets/ | Range slider (min/max) |
| `InlineEditControl` | CustomWidgets/ | Click-to-edit text |
| `DataViewGraph` | CustomWidgets/ | Real-time data graphing |
| `SlidePanelWidget` | CustomWidgets/ | Animated slide panel |
| `ColorPicker` | CustomWidgets/ColorPicker/ | HSV/RGB color selection |
| `ResizeContainer` | CustomWidgets/ResizeContainer/ | Resizable panels |
### Popover System
For context menus and tooltips:
```
Popover
├── ArrowDirection (Up, Down, Left, Right)
├── ArrowOffset
├── TagColor (accent color bar)
└── Content (any GuiWidget)
ClickablePopover extends Popover
└── Adds click-to-show behavior
```
Popovers are shown via `SystemWindow.ShowPopover()` with mate points:
```csharp
systemWindow.ShowPopover(
new MatePoint(anchorWidget) { Mate = MateOptions(MateEdge.Right, MateEdge.Bottom) },
new MatePoint(popover) { Mate = MateOptions(MateEdge.Left, MateEdge.Top) }
);
```
### Scaling and DPI
Device scaling is handled via `GuiWidget.DeviceScale`:
```csharp
// Set by user preference or TouchScreen detection
GuiWidget.DeviceScale = 1.3; // 130% scaling
// All widgets should use scaled values
var buttonHeight = 30 * GuiWidget.DeviceScale;
```
Settings:
- `UserSettingsKey.ApplicationTextSize` - User-selected scale
- `UserSettingsKey.ApplicationUseHeigResDisplays` - Per-monitor DPI awareness
### Window Providers
Platform-specific window creation is abstracted:
| Provider | Assembly | Platform |
|----------|----------|----------|
| `WinformsSingleWindowProvider` | MatterControl.Winforms | Windows (primary) |
| `GlfwWindowProvider` | GlfwProvider | Cross-platform (secondary) |
Configuration via `AggContext.Config.ProviderTypes.SystemWindowProvider`.
### Design Rationale
**Custom UI Framework**: Using agg-sharp instead of WPF/WinForms/Qt provides:
- Identical rendering across platforms (pixel-perfect consistency)
- Full control over 3D viewport integration
- No dependency on platform-specific UI toolkits
- Easier custom widget creation
**Chrome-Style Tabs**: Familiar browser-like UX for managing multiple workspaces
**Theme System**: JSON-based themes allow:
- Easy customization by OEMs
- User-selectable themes
- Consistent styling across all widgets
**Popover System**: Provides contextual UI without modal dialogs, keeping workflow fluid
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `MainViewWidget` | [PartPreviewWindow/MainViewWidget.cs](MatterControlLib/PartPreviewWindow/MainViewWidget.cs) | Main application view |
| `SimpleTabs` | [PartPreviewWindow/Tabs.cs](MatterControlLib/PartPreviewWindow/Tabs.cs) | Base tab implementation |
| `ChromeTabs` | [PartPreviewWindow/Tabs.cs](MatterControlLib/PartPreviewWindow/Tabs.cs) | Chrome-style tabs |
| `ThemeConfig` | Submodules/agg-sharp | Theme configuration |
| `ThemeSet` | [ApplicationView/Themes/ThemeSet.cs](MatterControlLib/ApplicationView/Themes/ThemeSet.cs) | Theme container |
| `ThemeConfigExtensions` | [ApplicationView/Themes/ThemeConfigExtensions.cs](MatterControlLib/ApplicationView/Themes/ThemeConfigExtensions.cs) | Theme helpers |
### Key Widgets
| Class | Location | Description |
|-------|----------|-------------|
| `DockingTabControl` | [CustomWidgets/DockingTabControl.cs](MatterControlLib/CustomWidgets/DockingTabControl.cs) | Side panel docking |
| `SolidSlider` | [CustomWidgets/SolidSlider.cs](MatterControlLib/CustomWidgets/SolidSlider.cs) | Value slider |
| `InlineEditControl` | [CustomWidgets/InlineEditControl.cs](MatterControlLib/CustomWidgets/InlineEditControl.cs) | Click-to-edit |
| `Popover` | [PartPreviewWindow/Popover.cs](MatterControlLib/PartPreviewWindow/Popover.cs) | Floating panel |
| `SearchPanel` | [PartPreviewWindow/SearchPanel.cs](MatterControlLib/PartPreviewWindow/SearchPanel.cs) | Search UI |
### Layout Classes
| Class | Purpose |
|-------|---------|
| `FlowLayoutWidget` | Horizontal/vertical flow |
| `Toolbar` | Horizontal toolbar with items |
| `OverflowBar` | Toolbar with overflow menu |
| `SectionWidget` | Collapsible section |
| `ResizableSectionWidget` | Section with resize handle |
### Events
| Event | Source | Description |
|-------|--------|-------------|
| `ActiveTabChanged` | `SimpleTabs` | Tab selection changed |
| `WorkspacesChanged` | `ApplicationController` | Tab added/removed |
| `AnyPrinterSettingChanged` | `PrinterSettings` | Setting modified |
| `UiHintChanged` | `ApplicationController` | Status message update |

229
research/04-part-preview.md Normal file
View file

@ -0,0 +1,229 @@
# 3D View & Part Preview
## Summary
The 3D View system provides interactive visualization and manipulation of 3D models and G-code. It combines OpenGL-accelerated rendering with a trackball camera system, object selection, transformation controls, and a hierarchical scene tree.
## Technical Description
### Core Components
The 3D preview system consists of several layered components:
```
View3DWidget
├── Object3DControlsLayer - Interaction handling, drawing coordination
│ ├── TrackballTumbleWidgetExtended - Camera rotation/pan/zoom
│ ├── FloorDrawable - Bed visualization
│ └── IObject3DControl instances - Transform handles
├── SelectedObjectPanel - Property editing
├── TreeView - Scene hierarchy browser
└── TumbleCubeControl - View orientation indicator
```
### Scene Context (ISceneContext)
The `ISceneContext` interface abstracts the 3D editing environment:
| Property | Type | Description |
|----------|------|-------------|
| `Scene` | `InteractiveScene` | Root scene graph |
| `World` | `WorldView` | Camera/projection state |
| `EditContext` | `EditContext` | Source file and content store |
| `ViewState` | `SceneContextViewState` | View configuration |
| `BedCenter` | `Vector2` | Print bed center point |
| `Printer` | `PrinterConfig` | Associated printer (optional) |
| `GCodeRenderer` | `GCodeRenderer` | G-code visualization |
**Key Methods:**
- `AddToPlate()` - Insert items into scene
- `ClearPlate()` - Remove all objects
- `LoadContent()` - Load from file/library
- `SaveChanges()` - Persist scene to disk
- `LoadGCode()` - Load G-code for preview
### View3DWidget
The main 3D viewport widget providing:
**Camera Control:**
- Trackball rotation (middle mouse / drag)
- Pan (Shift + drag)
- Zoom (scroll wheel / pinch)
- View cube for quick orientation
**Selection:**
- Click to select objects
- Ctrl+Click for multi-select
- Rectangular selection via drag
- Tree view synchronization
**Transform Modes:**
- Part Select - Object picking
- Translate - Move objects
- Rotate - Rotate around axes
- Zoom/Scale - Size adjustment
### Object3DControlsLayer
The interaction layer manages:
1. **3D Control Handles**: Transform gizmos for selected objects
2. **Drawable Registration**: Custom rendering callbacks
3. **Hit Testing**: Ray casting for object picking
4. **Floor Rendering**: Bed mesh and grid visualization
**Control Types (Flags):**
| Flag | Purpose |
|------|---------|
| `MoveInZ` | Vertical movement handle |
| `RotateXYZ` | 3-axis rotation gizmo |
| `RotateZ` | Z-axis only rotation |
| `ScaleMatrixXY` | XY scaling handles |
| `Shadow` | Object shadow rendering |
| `SnappingIndicators` | Snap guide display |
### Scene Graph (InteractiveScene)
The scene uses a hierarchical object model:
```
InteractiveScene
├── UndoBuffer - Change history
├── SelectedItem - Current selection
└── Children (IObject3D)
├── Meshes
├── Groups
└── Operations (CSG, transforms, etc.)
```
**IObject3D Interface:**
| Property | Type | Description |
|----------|------|-------------|
| `ID` | `string` | Unique identifier |
| `Name` | `string` | Display name |
| `Matrix` | `Matrix4X4` | Local transform |
| `Color` | `Color` | Material color |
| `MaterialIndex` | `int` | Material assignment |
| `OutputType` | `PrintOutputTypes` | Print behavior |
| `Children` | `SafeList<IObject3D>` | Child objects |
| `Mesh` | `Mesh` | Geometry data |
### Camera System
The `WorldView` class manages:
- **Model Matrix**: Scene rotation/position
- **View Matrix**: Camera position/orientation
- **Projection Matrix**: Perspective or orthographic
- **Near/Far Planes**: Dynamic clipping adjustment
**TrackballTumbleWidgetExtended** extends basic trackball with:
- Smooth momentum rotation
- Double-click to fit view
- Keyboard navigation (arrow keys)
- Dynamic near/far plane calculation
### GCode Visualization
When viewing G-code:
```
GCodeRenderer
├── GCodeFile - Parsed G-code data
├── RenderInfo - Layer/speed coloring
└── Layer visualization
├── Travel moves (thin lines)
├── Extrusion (thick, colored)
└── Retractions (markers)
```
**Layer Controls:**
- `ActiveLayerIndex` - Current layer
- `SliceLayerSelector` - Layer scrubber widget
- Speed/feature coloring modes
### Tree View Integration
The scene tree (`TreeView`) provides:
- Hierarchical object display
- Drag-and-drop reordering
- Right-click context menus
- Selection synchronization
- Expand/collapse groups
**Object3DTreeBuilder** creates tree nodes from scene:
```csharp
treeNodeContainer.AddChild(Object3DTreeBuilder.Build(scene, treeView));
```
### Selected Object Panel
Property editing for selected objects:
```
SelectedObjectPanel
├── Object name/color editors
├── Transform fields (X, Y, Z, rotation)
├── Material selection
└── Operation-specific editors
├── Primitive parameters
├── Boolean operation settings
└── Custom object3D properties
```
### Design Rationale
**Layered Architecture**: Separating View3DWidget, Object3DControlsLayer, and TrackballTumbleWidget allows:
- Independent testing of each layer
- Flexible composition (e.g., GCode-only vs full editing)
- Clear responsibility boundaries
**ISceneContext Abstraction**: Decouples view from editing context, enabling:
- Same view for printer beds and standalone designs
- Consistent API across different content types
- Easy mocking for tests
**Dynamic Near/Far Planes**: Automatically adjusting clipping planes based on scene bounds prevents:
- Z-fighting on large objects
- Clipping on small detailed parts
- Visual artifacts at extreme zooms
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `View3DWidget` | [View3D/View3DWidget.cs](MatterControlLib/PartPreviewWindow/View3D/View3DWidget.cs) | Main 3D viewport |
| `Object3DControlsLayer` | [View3D/Object3DControlsLayer.cs](MatterControlLib/PartPreviewWindow/View3D/Object3DControlsLayer.cs) | Interaction layer |
| `TrackballTumbleWidgetExtended` | [View3D/TrackballTumbleWidgetExtended.cs](MatterControlLib/PartPreviewWindow/View3D/TrackballTumbleWidgetExtended.cs) | Camera controls |
| `TumbleCubeControl` | [View3D/TumbleCubeControl.cs](MatterControlLib/PartPreviewWindow/View3D/TumbleCubeControl.cs) | View cube widget |
| `SelectedObjectPanel` | [PartPreviewWindow/SelectedObjectPanel.cs](MatterControlLib/PartPreviewWindow/SelectedObjectPanel.cs) | Property panel |
### Scene Classes
| Class | Location | Description |
|-------|----------|-------------|
| `ISceneContext` | [ApplicationView/ISceneContext.cs](MatterControlLib/ApplicationView/ISceneContext.cs) | Scene context interface |
| `InteractiveScene` | Submodules/agg-sharp/DataConverters3D | Scene root |
| `IObject3D` | Submodules/agg-sharp/DataConverters3D | Object interface |
| `EditContext` | [ApplicationView/EditContext.cs](MatterControlLib/ApplicationView/EditContext.cs) | Edit state |
### Interaction Classes
| Class | Location | Description |
|-------|----------|-------------|
| `IObject3DControl` | [View3D/Interaction/IObject3DControl.cs](MatterControlLib/PartPreviewWindow/View3D/Interaction/IObject3DControl.cs) | Control handle interface |
| `Object3DControl` | [View3D/Interaction/Object3DControl.cs](MatterControlLib/PartPreviewWindow/View3D/Interaction/Object3DControl.cs) | Base control |
| `SceneActions` | [View3D/SceneActions.cs](MatterControlLib/PartPreviewWindow/View3D/SceneActions.cs) | Scene operations |
### Rendering
| Class | Location | Description |
|-------|----------|-------------|
| `GCodeRenderer` | Submodules/agg-sharp | G-code visualization |
| `FloorDrawable` | Internal | Bed/grid rendering |
| `BedMeshGenerator` | [View3D/BedMeshGenerator.cs](MatterControlLib/PartPreviewWindow/View3D/BedMeshGenerator.cs) | Bed geometry |
| `WorldView` | Submodules/agg-sharp/VectorMath | Camera/projection |

View file

@ -0,0 +1,227 @@
# Printer Communication
## Summary
The printer communication system handles serial port connections to 3D printers, sending G-code commands, receiving responses, and managing print state. It uses a stream-based architecture for G-code processing with modular transformers for features like print leveling, pause handling, and temperature monitoring.
## Technical Description
### PrinterConnection Class
`PrinterConnection` is the main class managing printer communication:
**Communication States:**
| State | Description |
|-------|-------------|
| `Disconnected` | No active connection |
| `AttemptingToConnect` | Connection in progress |
| `FailedToConnect` | Connection attempt failed |
| `Connected` | Ready to receive commands |
| `PreparingToPrint` | Setting up for print |
| `Printing` | Active print from host |
| `PrintingFromSd` | Printing from SD card |
| `Paused` | Print paused |
| `FinishedPrint` | Print completed |
| `Disconnecting` | Closing connection |
| `ConnectionLost` | Unexpected disconnect |
**Supported Firmware:**
- Marlin
- Repetier
- Sprinter
- Smoothie
### Serial Communication
Connection parameters:
- `BaudRate` - Typically 115200 or 250000
- `SerialPort` - Platform-specific via `IFrostedSerialPort`
- Checksum support for error detection
- Line-by-line send/receive with buffering
**Response Parsing:**
```csharp
// Register callbacks for specific responses
readLineStartCallBacks.Register("ok", PrintingCanContinue);
readLineStartCallBacks.Register("T:", ReadTemperatures);
readLineStartCallBacks.Register("Error:", PrinterReportsError);
```
**Write Callbacks:**
```csharp
writeLineStartCallBacks.Register("M104", HotendTemperatureWasWritenToPrinter);
writeLineStartCallBacks.Register("M140", BedTemperatureWasWritenToPrinter);
```
### G-Code Stream Pipeline
G-code is processed through a chain of `GCodeStream` transformers:
```
GCodeFileStream (source)
└── GCodeSwitcher (file switching)
└── QueuedCommandsStream (injected commands)
└── PauseHandlingStream (pause/resume)
└── RelativeToAbsoluteStream (coordinate conversion)
└── PrintLevelingStream (bed leveling adjustments)
└── BabyStepsStream (live Z offset)
└── MaxLengthStream (segment splitting)
└── ToolChangeStream (extruder switching)
└── ExtrusionMultiplierStream
└── FeedRateMultiplierStream
└── WaitForTempStream
└── RequestTemperaturesStream
└── to Serial Port
```
Each stream can:
- Modify G-code lines passing through
- Inject additional commands
- Block/delay commands
- Monitor state
### Key G-Code Streams
| Stream | Purpose |
|--------|---------|
| `GCodeFileStream` | Reads G-code from file |
| `GCodeSwitcher` | Switches between print files |
| `QueuedCommandsStream` | Injects immediate commands |
| `PauseHandlingStream` | Manages pause/resume logic |
| `PrintLevelingStream` | Applies bed leveling corrections |
| `MaxLengthStream` | Splits long moves into segments |
| `ToolChangeStream` | Handles multi-extruder switching |
| `WaitForTempStream` | Waits for temperature targets |
| `PrintRecoveryStream` | Enables print recovery after failure |
| `ValidatePrintLevelingStream` | Validates leveling data |
| `SoftwareEndstopsStream` | Enforces software limits |
| `BabyStepsStream` | Applies live Z offset adjustments |
### Temperature Management
Temperature tracking for:
- Heated bed (`ActualBedTemperature`, `TargetBedTemperature`)
- Up to 16 hotends (`actualHotendTemperature[]`, `targetHotendTemperature[]`)
**Temperature Reading:**
```csharp
// Parses responses like "T:205.3 /210.0 B:60.0 /60.0"
readLineContainsCallBacks.Register("T:", ReadTemperatures);
```
**Automatic Heater Shutdown:**
- `TimeToHoldTemperature` - Configurable delay
- `SecondsToHoldTemperature` - Countdown timer
- `TurnOffBedAndExtruders(TurnOff.AfterDelay)` - Scheduled shutdown
### Print State Management
**Detailed Printing States:**
| State | Description |
|-------|-------------|
| `HomingAxis` | Executing homing sequence |
| `HeatingBed` | Waiting for bed temperature |
| `HeatingT0` | Waiting for extruder 0 temp |
| `HeatingT1` | Waiting for extruder 1 temp |
| `Printing` | Active G-code execution |
**Events:**
| Event | Description |
|-------|-------------|
| `PrintStarted` | Print begins |
| `PrintFinished` | Print completes |
| `CancelRequested` | Cancel initiated |
| `CancelCompleted` | Cancel finished |
| `PauseOnLayer` | Pause at specific layer |
| `FilamentRunout` | Filament sensor triggered |
### Error Handling
Error detection via response parsing:
```csharp
readLineContainsCallBacks.Register("MINTEMP", PrinterReportsError);
readLineContainsCallBacks.Register("MAXTEMP", PrinterReportsError);
readLineContainsCallBacks.Register("Thermal Runaway", PrinterReportsError);
```
Errors trigger:
1. `ErrorReported` event
2. Print pause (if printing)
3. User notification dialog
### Alternative Drivers
The system supports alternative communication protocols:
| Driver | Location | Purpose |
|--------|----------|---------|
| Emulator | Drivers/Emulator | Virtual printer for testing |
| TCPIP | Drivers/TCPIP | Network-connected printers |
| X3G | Drivers/X3G | MakerBot X3G protocol |
### TerminalLog
All communication is logged via `TerminalLog`:
- Send/receive history
- Exportable for debugging
- Real-time display in UI terminal
### Design Rationale
**Stream Pipeline**: The chain-of-responsibility pattern allows:
- Modular feature implementation
- Easy addition/removal of processing stages
- Clear data flow through transformations
- Independent testing of each stage
**Callback-Based Parsing**: Using `StartsWith` and `Contains` callbacks:
- Efficient string matching
- Handles firmware variations
- Easy to extend for new responses
**State Machine**: The `CommunicationStates` enum ensures:
- Clear state transitions
- Appropriate UI updates
- Safe operation sequencing
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `PrinterConnection` | [PrinterCommunication/PrinterConnection.cs](MatterControlLib/PrinterCommunication/PrinterConnection.cs) | Main communication class |
| `TerminalLog` | [PrinterCommunication/TerminalLog.cs](MatterControlLib/PrinterCommunication/TerminalLog.cs) | Communication log |
| `PrinterConfig` | [SlicerConfiguration/PrinterConfig.cs](MatterControlLib/SlicerConfiguration/Settings/PrinterConfig.cs) | Printer configuration |
### G-Code Streams
| Class | Location | Description |
|-------|----------|-------------|
| `GCodeStream` | [PrinterCommunication/Io/GCodeStream.cs](MatterControlLib/PrinterCommunication/Io/GCodeStream.cs) | Base stream class |
| `GCodeSwitcher` | [PrinterCommunication/Io/GCodeSwitcher.cs](MatterControlLib/PrinterCommunication/Io/GCodeSwitcher.cs) | File switching |
| `PauseHandlingStream` | [PrinterCommunication/Io/PauseHandlingStream.cs](MatterControlLib/PrinterCommunication/Io/PauseHandlingStream.cs) | Pause/resume |
| `PrintLevelingStream` | [PrinterCommunication/Io/PrintLevelingStream.cs](MatterControlLib/PrinterCommunication/Io/PrintLevelingStream.cs) | Bed leveling |
| `ToolChangeStream` | [PrinterCommunication/Io/ToolChangeStream.cs](MatterControlLib/PrinterCommunication/Io/ToolChangeStream.cs) | Tool changes |
| `WaitForTempStream` | [PrinterCommunication/Io/WaitForTempStream.cs](MatterControlLib/PrinterCommunication/Io/WaitForTempStream.cs) | Temperature wait |
### Events
| Event | Source | Description |
|-------|--------|-------------|
| `CommunicationStateChanged` | `PrinterConnection` | State transition |
| `TemperatureRead` | `PrinterConnection` | Temp update |
| `LineReceived` | `PrinterConnection` | Serial input |
| `LineSent` | `PrinterConnection` | Serial output |
| `PrintFinished` | `PrinterConnection` | Print complete |
| `ErrorReported` | `PrinterConnection` | Printer error |
### Enums
| Enum | Values |
|------|--------|
| `CommunicationStates` | Disconnected, Connected, Printing, Paused, etc. |
| `DetailedPrintingState` | HomingAxis, HeatingBed, HeatingT0, Printing |
| `FirmwareTypes` | Unknown, Repetier, Marlin, Sprinter, Smoothie |
| `TurnOff` | Now, AfterDelay |
| `Axis` | X, Y, Z, E, XYZ, C |

View file

@ -0,0 +1,208 @@
# Slicing System
## Summary
MatterControl integrates the **MatterSlice** slicing engine to convert 3D models into G-code instructions for printing. The system maps printer settings to slicer parameters, handles multi-extruder configurations, and supports features like rafts, supports, and custom start/end G-code.
## Technical Description
### Architecture Overview
```
PrinterConfig.Settings
EngineMappingsMatterSlice (IObjectSlicer)
├── Settings Mapping (Exports dictionary)
MatterSlice Engine
G-code Output File
```
### Slicer Static Class
The `Slicer` static class provides helper methods:
**Key Methods:**
| Method | Purpose |
|--------|---------|
| `SliceItem()` | Entry point for slicing objects |
| `GetExtrudersUsed()` | Determine which extruders are needed |
| `GetSolidsForExtruder()` | Filter objects by extruder assignment |
| `GetAllHoles()` | Find hole/negative objects |
| `T1OrGreaterUsed()` | Check if multi-extruder print |
**Configuration:**
- `RunInProcess` - Run slicer in-process (debug) vs subprocess
### EngineMappingsMatterSlice
Implements `IObjectSlicer` interface to translate MatterControl settings to MatterSlice parameters:
**Export Mapping:**
```csharp
Exports = new Dictionary<string, ExportField>()
{
[SettingsKey.layer_height] = new ExportField("layerThickness"),
[SettingsKey.perimeters] = new ExportField("numberOfPerimeters"),
[SettingsKey.fill_density] = new ExportField("infillPercent", transformer),
// ...
};
```
**Mapping Categories:**
| Category | Sample Settings |
|----------|-----------------|
| Layer | `layer_height`, `first_layer_height` |
| Perimeters | `perimeters`, `external_perimeter_speed` |
| Infill | `fill_density`, `infill_type`, `fill_angle` |
| Speed | `travel_speed`, `perimeter_speed`, `infill_speed` |
| Retraction | `retract_length`, `retract_speed`, `retract_lift` |
| Support | `support_material_spacing`, `support_air_gap` |
| Raft/Brim | `create_raft`, `raft_air_gap`, `skirts` |
| Fan | `min_fan_speed`, `max_fan_speed`, `bridge_fan_speed` |
| Extruder | `filament_diameter`, `nozzle_diameter`, `extrusion_multiplier` |
### Export Field Transformers
Some settings require transformation:
```csharp
// Percentage to decimal conversion
[SettingsKey.fill_density] = new ExportField(
"infillPercent",
(value, settings) => {
if (double.TryParse(value, out double infillRatio))
return $"{infillRatio * 100}";
return "0";
})
// Start G-code processing
[SettingsKey.start_gcode] = new ExportField(
"startCode",
(value, settings) => StartGCodeGenerator.BuildStartGCode(settings, value))
```
### Multi-Extruder Support
Extruder assignment based on `MaterialIndex`:
```csharp
var itemsThisExtruder = meshItemsOnBuildPlate.Where((item) => {
var material = item.WorldMaterialIndex();
return material == extruderIndex
|| (extruderIndex == 0 && material >= extruderCount);
});
```
**Extruder-Specific Settings:**
- `support_material_extruder`
- `support_material_interface_extruder`
- `raft_extruder`
- `brim_extruder`
### Print Output Types
Objects can have different output behaviors:
| Type | Description |
|------|-------------|
| `Default` | Normal solid printing |
| `Solid` | Explicitly solid |
| `Support` | Support material |
| `Hole` | Negative/subtraction |
| `Fuzzy` | Fuzzy skin effect |
### Slicing Process
1. **Collect Printable Items**: Filter scene for printable objects
2. **Determine Extruders**: Calculate which extruders are needed
3. **Map Settings**: Convert settings to slicer parameters
4. **Run Slicer**: Execute MatterSlice engine
5. **Progress Reporting**: Update UI with slice progress
6. **Output G-code**: Write to file
### MatterSlice Integration
MatterSlice is included as a submodule:
- `Submodules/MatterSlice/MatterSlice.csproj`
- `Submodules/MatterSlice/MatterSliceLib/MatterSliceLib.csproj`
**Key Settings Files:**
- `StaticData/SliceSettings/Layouts.txt` - UI layout definitions
- Settings JSON files in printer profiles
### Slicer Settings UI
Settings are organized via `SliceSettingsWidget`:
```
SliceSettingsWidget
├── Category tabs (General, Infill, Support, etc.)
├── Settings rows (SliceSettingsRow)
└── Preset selector (PresetSelectorWidget)
```
### Design Rationale
**Integrated Slicer**: Bundling MatterSlice provides:
- Seamless user experience
- Direct control over slicing behavior
- No external dependencies to manage
- Consistent cross-platform behavior
**Export Field Pattern**: The mapping dictionary allows:
- Declarative settings mapping
- Custom transformers where needed
- Easy addition of new settings
- Clear documentation of mappings
**Extruder Detection**: Pre-calculating used extruders enables:
- Appropriate temperature settings
- Correct tool change G-code
- Optimized print preparation
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `Slicer` | [SlicerConfiguration/Slicer.cs](MatterControlLib/SlicerConfiguration/Slicer.cs) | Static slicer helpers |
| `EngineMappingsMatterSlice` | [SlicerConfiguration/EngineMappingsMatterSlice.cs](MatterControlLib/SlicerConfiguration/EngineMappingsMatterSlice.cs) | Settings mapping |
| `ExportField` | [MatterControl.Printing/ExportField.cs](MatterControl.Printing/ExportField.cs) | Field definition |
| `SliceSettingsWidget` | [SlicerConfiguration/SliceSettingsWidget.cs](MatterControlLib/SlicerConfiguration/SliceSettingsWidget.cs) | Settings UI |
### UI Components
| Class | Location | Description |
|-------|----------|-------------|
| `SliceSettingsRow` | [SlicerConfiguration/SliceSettingsRow.cs](MatterControlLib/SlicerConfiguration/SliceSettingsRow.cs) | Individual setting row |
| `PresetSelectorWidget` | [SlicerConfiguration/PresetSelectorWidget.cs](MatterControlLib/SlicerConfiguration/PresetSelectorWidget.cs) | Preset dropdown |
| `SettingsRow` | [SlicerConfiguration/SettingsRow.cs](MatterControlLib/SlicerConfiguration/SettingsRow.cs) | Base row widget |
### Key Enums
| Enum | Values |
|------|--------|
| `PrintOutputTypes` | Default, Solid, Support, Hole, Fuzzy |
| `InfillType` | Grid, Triangles, Gyroid, Lines, etc. |
| `SeamPlacement` | Random, Nearest, Aligned |
| `SupportType` | None, Lines, Grid, FromBed, Everywhere |
### Settings Keys (Sample)
| Key | Description |
|-----|-------------|
| `layer_height` | Layer thickness |
| `perimeters` | Number of perimeter shells |
| `fill_density` | Infill percentage |
| `support_material` | Enable supports |
| `create_raft` | Create print raft |
| `retract_length` | Retraction distance |
| `travel_speed` | Non-printing move speed |

View file

@ -0,0 +1,228 @@
# Library & Content Management
## Summary
The Library system provides a hierarchical content browser for managing 3D models, designs, and print files. It uses a container-based architecture supporting multiple backends including file system, SQLite database, cloud storage, and bundled assets.
## Technical Description
### Architecture
```
LibraryConfig (ILibraryContext)
├── RootLibraryContainer
│ ├── Computer (FileSystemContainer)
│ ├── Local Library (SqliteLibraryContainer)
│ ├── Queue (FileSystemContainer)
│ ├── Bundled Parts (BundledPartsCollectionContainer)
│ ├── History (RootHistoryContainer)
│ └── Custom Library Folders...
├── ContentProviders (file type handlers)
└── MenuExtensions (context menu actions)
```
### Core Interfaces
**ILibraryContext:**
```csharp
public interface ILibraryContext
{
event EventHandler<ContainerChangedEventArgs> ContainerChanged;
event EventHandler<ContainerChangedEventArgs> ContentChanged;
ILibraryContainer ActiveContainer { get; set; }
}
```
**ILibraryContainer:**
| Property/Method | Description |
|-----------------|-------------|
| `Items` | Child items (files) |
| `ChildContainers` | Sub-containers (folders) |
| `Parent` | Parent container |
| `Load()` | Load container contents |
| `Activate()/Deactivate()` | Lifecycle hooks |
| `GetThumbnail()` | Generate item thumbnail |
**ILibraryItem:**
| Property | Description |
|----------|-------------|
| `ID` | Unique identifier |
| `Name` | Display name |
| `DateCreated` | Creation timestamp |
| `DateModified` | Last modified timestamp |
### Container Types
| Container | Purpose | Location |
|-----------|---------|----------|
| `RootLibraryContainer` | Top-level root | Providers/ |
| `FileSystemContainer` | File/folder access | Providers/FileSystem/ |
| `SqliteLibraryContainer` | Database-backed library | Providers/Sqlite/ |
| `BundledPartsCollectionContainer` | Built-in parts | Providers/MatterControl/ |
| `PlatingHistoryContainer` | Print history | Providers/MatterControl/ |
| `PrinterContainer` | Printer-specific storage | Providers/Printer/ |
| `ZipContainer` | ZIP archive browsing | Providers/Zip/ |
| `GitHubContainer` | GitHub repo browsing | Providers/GitHub/ |
### Content Providers
Content providers handle loading and saving specific file types:
| Provider | Extensions |
|----------|------------|
| `MeshContentProvider` | stl, obj, 3mf, amf, mcx |
| `GCodeContentProvider` | gcode |
| `ImageContentProvider` | png, gif, jpg, jpeg |
| `OpenScadContentProvider` | scad |
Registration:
```csharp
Library.ContentProviders.Add("stl", new MeshContentProvider());
Library.ContentProviders.Add("gcode", new GCodeContentProvider());
```
### Item Types
**ILibraryAsset:** File-based items with content
```csharp
public interface ILibraryAsset : ILibraryItem
{
string FileName { get; }
string ContentType { get; }
long FileSize { get; }
}
```
**ILibraryObject3D:** 3D model items
```csharp
public interface ILibraryObject3D : ILibraryItem
{
Task<IObject3D> GetObject3D(Action<double, string> progress);
}
```
**ILibraryContainerLink:** Lazy-loaded container reference
```csharp
public interface ILibraryContainerLink : ILibraryItem
{
ILibraryContainer GetContainer();
bool IsReadOnly { get; }
}
```
### Container Actions
| Action | Description |
|--------|-------------|
| `AddItems` | Add new files |
| `AddContainers` | Create sub-folders |
| `RenameItems` | Rename items |
| `RemoveItems` | Delete items |
### Writable Containers
`ILibraryWritableContainer` extends containers with write operations:
```csharp
public interface ILibraryWritableContainer
{
void Add(IEnumerable<ILibraryItem> items);
void Remove(IEnumerable<ILibraryItem> items);
void Rename(ILibraryItem item, string revisedName);
void Move(IEnumerable<ILibraryItem> items, ILibraryWritableContainer dest);
void SetThumbnail(ILibraryItem item, int width, int height, ImageBuffer thumbnail);
}
```
### Navigation
Container navigation uses parent references:
```csharp
// Navigate up
ActiveContainer = ActiveContainer.Parent;
// Get breadcrumb path
var ancestors = activeContainer.Ancestors();
```
### Thumbnails
`ThumbnailsConfig` manages thumbnail generation:
```csharp
// Request thumbnail
var thumbnail = await Library.EnsureCorrectThumbnailSizing(
originalThumbnail,
thumbWidth,
thumbHeight,
resizedCallback);
```
Thumbnail sources:
1. Cached thumbnail in database
2. Generated from 3D model render
3. Extracted from file (3MF, AMF)
4. Default icon fallback
### Library UI Widgets
| Widget | Location | Purpose |
|--------|----------|---------|
| `LibraryListView` | Library/Widgets/ | List/grid item display |
| `LibraryBrowserPage` | PartPreviewWindow/ | Full library browser |
| `LibrarySelector` | CustomWidgets/LibrarySelector/ | Folder picker |
| `SaveAsPage` | PartPreviewWindow/ | Save dialog |
### Design Rationale
**Container Pattern**: Using a container abstraction allows:
- Uniform navigation across different storage backends
- Easy addition of new storage types (cloud, network, etc.)
- Consistent UI regardless of data source
**Lazy Loading**: `ILibraryContainerLink` enables:
- Fast initial display
- Load content only when expanded
- Memory-efficient browsing
**Content Providers**: Separating file handling from containers:
- Same file types work in any container
- Easy to add new format support
- Clear responsibility separation
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `LibraryConfig` | [Library/Providers/LibraryConfig.cs](MatterControlLib/Library/Providers/LibraryConfig.cs) | Library manager |
| `RootLibraryContainer` | [Library/Providers/RootLibraryContainer.cs](MatterControlLib/Library/Providers/RootLibraryContainer.cs) | Root container |
| `FileSystemContainer` | [Library/Providers/FileSystem/](MatterControlLib/Library/Providers/FileSystem/) | File system access |
| `LibraryContainer` | [Library/Providers/LibraryContainer.cs](MatterControlLib/Library/Providers/LibraryContainer.cs) | Base container |
### Interfaces
| Interface | Location | Description |
|-----------|----------|-------------|
| `ILibraryContext` | [Library/Providers/LibraryConfig.cs](MatterControlLib/Library/Providers/LibraryConfig.cs) | Context interface |
| `ILibraryContainer` | [Library/Interfaces/ILibraryContainer.cs](MatterControlLib/Library/Interfaces/ILibraryContainer.cs) | Container interface |
| `ILibraryItem` | [Library/Interfaces/ILibraryItem.cs](MatterControlLib/Library/Interfaces/ILibraryItem.cs) | Item interface |
| `ILibraryAsset` | [Library/Interfaces/ILibraryAsset.cs](MatterControlLib/Library/Interfaces/ILibraryAsset.cs) | Asset interface |
| `IContentProvider` | [Library/ContentProviders/](MatterControlLib/Library/ContentProviders/) | Content provider |
### Content Providers
| Class | Location | Extensions |
|-------|----------|------------|
| `MeshContentProvider` | [Library/ContentProviders/](MatterControlLib/Library/ContentProviders/) | stl, obj, 3mf, amf |
| `GCodeContentProvider` | [Library/ContentProviders/](MatterControlLib/Library/ContentProviders/) | gcode |
| `ImageContentProvider` | [Library/ContentProviders/](MatterControlLib/Library/ContentProviders/) | png, jpg, gif |
### Events
| Event | Source | Description |
|-------|--------|-------------|
| `ContainerChanged` | `ILibraryContext` | Active container changed |
| `ContentChanged` | `ILibraryContainer` | Container contents modified |

217
research/08-data-storage.md Normal file
View file

@ -0,0 +1,217 @@
# Data Storage & Persistence
## Summary
MatterControl uses SQLite for persistent data storage with a simple ORM pattern. The `Datastore` singleton manages database connections, schema validation, and session tracking. Entity classes provide CRUD operations through the `ISQLite` interface.
## Technical Description
### Architecture
```
Datastore (singleton)
├── ISQLite interface (database operations)
├── Entity tables
│ ├── PrintItemCollection
│ ├── PrintItem
│ ├── PrintTask
│ ├── Printer
│ ├── PrinterSetting
│ ├── CustomCommands
│ ├── SliceSetting
│ ├── SliceSettingsCollection
│ ├── SystemSetting
│ ├── UserSetting
│ └── ApplicationSession
└── ApplicationDataStorage (paths)
```
### Datastore Class
The `Datastore` singleton manages database lifecycle:
```csharp
public class Datastore
{
public ISQLite dbSQLite;
private string datastoreLocation;
private ApplicationSession activeSession;
public void Initialize(ISQLite dbSQLite);
public void Exit();
public int RecordCount(string tableName);
}
```
**Initialization:**
1. Check if database file exists (first run detection)
2. Connect to SQLite database
3. Validate/create schema tables
4. Initialize root library collection
5. Start application session
### Entity Base Class
All database models inherit from `Entity`:
```csharp
public class Entity
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public virtual void Commit(); // Insert or Update
public void Delete();
}
```
**Commit Logic:**
- `Id == 0`: Insert new record
- `Id != 0`: Update existing record
- Automatic retry on database lock
### Database Tables
| Table | Purpose | Key Fields |
|-------|---------|------------|
| `PrintItemCollection` | Library folders | Name, ParentCollectionId |
| `PrintItem` | Library items | Name, FileLocation, PrintItemCollectionId |
| `PrintTask` | Print job history | PrintName, PrintStart, PrintEnd, PercentDone |
| `Printer` | Printer definitions | Name (deprecated - use profiles) |
| `PrinterSetting` | Printer settings | Name, Value, PrinterId |
| `CustomCommands` | User macros | Name, Value, PrinterId |
| `SliceSetting` | Slice presets | Name, Value |
| `SliceSettingsCollection` | Setting groups | Name, Tag |
| `SystemSetting` | System config | Name, Value |
| `UserSetting` | User preferences | Name, Value |
| `ApplicationSession` | Session tracking | SessionStart, SessionEnd, PrintCount |
### ApplicationDataStorage
Manages file system paths:
| Path | Purpose |
|------|---------|
| `ApplicationDataPath` | Root data directory |
| `DatastorePath` | SQLite database file |
| `GCodeOutputPath` | Generated G-code files |
| `LibraryAssetsPath` | Library asset files |
| `ApplicationLibraryDataPath` | Library data |
| `ApplicationFontsDataPath` | Custom fonts |
| `CustomLibraryFoldersPath` | User library paths |
| `ProfilesPath` | Printer profiles |
**Default Location:**
- Windows: `%LOCALAPPDATA%\MatterControl`
- macOS: `~/Library/Application Support/MatterControl`
- Linux: `~/.local/share/MatterControl`
### Common Entity Models
**PrintItem:**
```csharp
public class PrintItem : Entity
{
public string Name { get; set; }
public string FileLocation { get; set; }
public DateTime DateAdded { get; set; }
[Indexed]
public int PrintItemCollectionId { get; set; }
}
```
**PrintTask:**
```csharp
public class PrintTask : Entity
{
public string PrintName { get; set; }
public DateTime PrintStart { get; set; }
public DateTime PrintEnd { get; set; }
public int PrintTimeSeconds { get; set; }
public double PercentDone { get; set; }
public bool PrintComplete { get; set; }
public string PrinterName { get; set; }
}
```
**UserSetting:**
```csharp
public class UserSetting : Entity
{
[Indexed]
public string Name { get; set; }
public string Value { get; set; }
}
```
### ISQLite Interface
Database operations abstracted for testability:
| Method | Description |
|--------|-------------|
| `CreateTable<T>()` | Create table from type |
| `Insert(object)` | Insert record |
| `Update(object)` | Update record |
| `Delete(object)` | Delete record |
| `Table<T>()` | Query table |
| `ExecuteScalar<T>(sql)` | Execute scalar query |
| `Close()` | Close connection |
### Session Tracking
`ApplicationSession` records usage:
```csharp
public class ApplicationSession : Entity
{
public DateTime SessionStart { get; set; }
public DateTime SessionEnd { get; set; }
public int PrintCount { get; set; }
}
```
### Design Rationale
**SQLite**: Chosen for:
- Zero configuration deployment
- Single-file database
- Cross-platform support
- ACID compliance
**Entity Pattern**: Simple ORM provides:
- Minimal boilerplate
- Type-safe queries
- Automatic schema management
**Singleton Datastore**: Ensures:
- Single database connection
- Coordinated access
- Clean shutdown
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `Datastore` | [DataStorage/Datastore.cs](MatterControlLib/DataStorage/Datastore.cs) | Database manager |
| `Entity` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | Base entity class |
| `ApplicationDataStorage` | [DataStorage/ApplicationDataStorage.cs](MatterControlLib/DataStorage/ApplicationDataStorage.cs) | Path management |
### Entity Models
| Class | Location | Description |
|-------|----------|-------------|
| `PrintItem` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | Library item |
| `PrintItemCollection` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | Library folder |
| `PrintTask` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | Print job record |
| `ApplicationSession` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | Session data |
| `UserSetting` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | User preference |
### Database Attributes
| Attribute | Purpose |
|-----------|---------|
| `[PrimaryKey]` | Primary key column |
| `[AutoIncrement]` | Auto-increment integer |
| `[Indexed]` | Create index on column |

View file

@ -0,0 +1,193 @@
# Settings Management
## Summary
MatterControl uses a hierarchical settings system managing printer configurations, slicer parameters, and user preferences. Settings are organized into profiles with inheritance, preset support, and real-time validation.
## Technical Description
### Architecture
```
ProfileManager
├── ActiveProfiles (list of printer profiles)
└── PrinterSettings (per printer)
├── BaseLayer (OEM defaults)
├── OemLayer (manufacturer overrides)
├── UserLayer (user customizations)
└── MaterialPresets / QualityPresets
```
### PrinterSettings Class
Central settings container with layered overrides:
```csharp
public class PrinterSettings
{
public SettingsLayer OemLayer { get; }
public SettingsLayer UserLayer { get; }
public List<SettingsLayer> MaterialPresets { get; }
public List<SettingsLayer> QualityPresets { get; }
public string GetValue(string key);
public T GetValue<T>(string key);
public void SetValue(string key, string value);
}
```
### Settings Layers
Settings resolution from highest to lowest priority:
1. **UserLayer** - User customizations
2. **ActiveQualityPreset** - Quality preset (Draft/Normal/Fine)
3. **ActiveMaterialPreset** - Material preset (PLA/ABS/etc.)
4. **OemLayer** - Manufacturer overrides
5. **BaseLayer** - Application defaults
### SettingsKey Constants
All settings keys defined in `SettingsKey` static class:
| Category | Sample Keys |
|----------|-------------|
| Printer | `printer_name`, `build_height`, `bed_size` |
| Layer | `layer_height`, `first_layer_height` |
| Perimeters | `perimeters`, `external_perimeter_speed` |
| Infill | `fill_density`, `infill_type` |
| Support | `support_material`, `support_type` |
| Temperature | `temperature`, `bed_temperature` |
| Speed | `travel_speed`, `perimeter_speed` |
| Retraction | `retract_length`, `retract_speed` |
| G-code | `start_gcode`, `end_gcode` |
### Profile Management
`ProfileManager` handles profile lifecycle:
```csharp
public class ProfileManager
{
public static ProfileManager Instance { get; }
public IEnumerable<PrinterInfo> ActiveProfiles { get; }
public static Task<PrinterSettings> LoadSettingsAsync(string profileId);
public void SaveSettings(PrinterSettings settings);
public void DeleteProfile(string profileId);
}
```
### Settings Validation
`SettingsValidation` checks configuration consistency:
| Check | Description |
|-------|-------------|
| Temperature bounds | Min/max temperature limits |
| Speed limits | Reasonable speed ranges |
| Layer height | Compatible with nozzle diameter |
| Retraction | Valid retraction settings |
| Bed size | Build volume constraints |
### UI Components
**SliceSettingsWidget:**
```
SliceSettingsWidget
├── Category Tabs (General, Infill, Support, etc.)
├── Settings Sections
│ └── SliceSettingsRow (individual settings)
└── PresetsToolbar
├── Material Preset Selector
└── Quality Preset Selector
```
**SliceSettingsRow:**
- Label and value editor
- Reset to default button
- Override indicator
- Help tooltip
### Preset System
**Material Presets:**
- PLA, ABS, PETG, TPU, etc.
- Temperature profiles
- Retraction settings
- Fan settings
**Quality Presets:**
- Draft (fast, low quality)
- Normal (balanced)
- Fine (slow, high quality)
- Custom user presets
### OEM Customization
Manufacturers can provide custom profiles via:
```
StaticData/
├── Printers/
│ └── {Manufacturer}/
│ └── {Model}.printer
│ ├── base.ini
│ ├── material_pla.ini
│ └── quality_normal.ini
└── OEMSettings/
└── OEMProfile.json
```
### Settings Events
| Event | Description |
|-------|-------------|
| `SettingChanged` | Individual setting modified |
| `AnyPrinterSettingChanged` | Static event for any printer |
| `ActiveProfileModified` | Active profile changed |
### Design Rationale
**Layered Settings**: Inheritance hierarchy provides:
- Clear override semantics
- Easy reset to defaults
- Manufacturer customization
- User freedom to modify
**Preset System**: Separating presets allows:
- Quick switching between materials/quality
- Consistent printing results
- OEM-tuned profiles
**Key-Value Model**: String-based settings enable:
- Flexible storage
- Easy serialization
- Runtime modification
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `PrinterSettings` | [SlicerConfiguration/Settings/PrinterSettings.cs](MatterControlLib/SlicerConfiguration/Settings/PrinterSettings.cs) | Settings container |
| `SettingsLayer` | [SlicerConfiguration/Settings/SettingsLayer.cs](MatterControlLib/SlicerConfiguration/Settings/SettingsLayer.cs) | Settings layer |
| `ProfileManager` | [SlicerConfiguration/Settings/ProfileManager.cs](MatterControlLib/SlicerConfiguration/Settings/ProfileManager.cs) | Profile manager |
| `SettingsKey` | [SlicerConfiguration/Settings/SettingsKey.cs](MatterControlLib/SlicerConfiguration/Settings/SettingsKey.cs) | Key constants |
### UI Components
| Class | Location | Description |
|-------|----------|-------------|
| `SliceSettingsWidget` | [SlicerConfiguration/SliceSettingsWidget.cs](MatterControlLib/SlicerConfiguration/SliceSettingsWidget.cs) | Settings panel |
| `SliceSettingsRow` | [SlicerConfiguration/SliceSettingsRow.cs](MatterControlLib/SlicerConfiguration/SliceSettingsRow.cs) | Settings row |
| `PresetSelectorWidget` | [SlicerConfiguration/PresetSelectorWidget.cs](MatterControlLib/SlicerConfiguration/PresetSelectorWidget.cs) | Preset dropdown |
### Application Settings
| Class | Location | Description |
|-------|----------|-------------|
| `ApplicationSettings` | [SettingsManagement/ApplicationSettings.cs](MatterControlLib/SettingsManagement/ApplicationSettings.cs) | App-level settings |
| `UserSettings` | [SettingsManagement/UserSettings.cs](MatterControlLib/SettingsManagement/UserSettings.cs) | User preferences |
| `OemSettings` | [SettingsManagement/OemSettings.cs](MatterControlLib/SettingsManagement/OemSettings.cs) | OEM config |

209
research/10-design-tools.md Normal file
View file

@ -0,0 +1,209 @@
# Design Tools
## Summary
MatterControl includes a comprehensive set of parametric design tools for creating and modifying 3D objects. Tools range from primitive shape generators to advanced boolean operations, mesh modifications, and text/image extrusion.
## Technical Description
### Architecture
Design tools are implemented as `IObject3D` subclasses:
```
Object3D (base)
├── Primitives (generators)
│ ├── CubeObject3D
│ ├── CylinderObject3D
│ ├── SphereObject3D
│ └── ...
├── Operations (modifiers)
│ ├── ScaleObject3D
│ ├── RotateObject3D
│ ├── AlignObject3D
│ └── ...
└── Boolean Operations
├── CombineObject3D (Union)
├── SubtractObject3D
└── IntersectObject3D
```
### Primitive Objects
Shape generators with parametric properties:
| Primitive | Parameters |
|-----------|------------|
| `CubeObject3D` | Width, Depth, Height |
| `CylinderObject3D` | Diameter, Height, Sides |
| `SphereObject3D` | Diameter, Latitude/Longitude Steps |
| `ConeObject3D` | Top/Bottom Diameter, Height |
| `TorusObject3D` | Outer Diameter, Ring Diameter |
| `HemisphereObject3D` | Diameter |
| `PyramidObject3D` | Width, Depth, Height |
| `WedgeObject3D` | Width, Depth, Height |
| `RingObject3D` | Outer/Inner Diameter, Height |
### Transform Operations
| Operation | Description | Parameters |
|-----------|-------------|------------|
| `ScaleObject3D` | Resize object | X/Y/Z scale factors |
| `RotateObject3D` | Rotate around axis | Angle, Axis |
| `TranslateObject3D` | Move object | X/Y/Z offset |
| `MirrorObject3D` | Mirror across plane | Mirror plane |
| `AlignObject3D` | Align to reference | Alignment mode |
### Array Operations
| Operation | Description |
|-----------|-------------|
| `ArrayLinearObject3D` | Linear array (copies in line) |
| `ArrayRadialObject3D` | Radial array (copies in circle) |
| `ArrayAdvancedObject3D` | Custom array patterns |
### Mesh Modifications
| Operation | Description |
|-----------|-------------|
| `CurveObject3D` | Bend mesh along curve |
| `TwistObject3D` | Twist mesh around axis |
| `PinchObject3D` | Pinch/bulge mesh |
| `HollowOutObject3D` | Create hollow shell |
| `DecimateObject3D` | Reduce polygon count |
| `RepairObject3D` | Fix mesh errors |
| `PlaneCutObject3D` | Cut with plane |
### Boolean Operations
Constructive Solid Geometry (CSG):
| Operation | Result |
|-----------|--------|
| `CombineObject3D` | Union (merge shapes) |
| `SubtractObject3D` | Difference (cut away) |
| `IntersectObject3D` | Intersection (common volume) |
| `SubtractAndReplaceObject3D` | Subtract with material replacement |
### Text and Image Tools
**TextObject3D:**
- Font selection
- Height/depth parameters
- Bold/italic options
**ImageToPathObject3D:**
- Image to vector outline
- Threshold control
- Extrusion depth
**LinearExtrudeObject3D:**
- Extrude 2D path to 3D
- Height, twist, scale parameters
### Path Operations
Located in `DesignTools/Operations/Path/`:
| Operation | Description |
|-----------|-------------|
| `LinearExtrudeObject3D` | Extrude path vertically |
| `RotateExtrudeObject3D` | Revolve path around axis |
| `SmoothPathObject3D` | Smooth path curves |
| `OffsetPathObject3D` | Offset/inset path |
### Property System
Design tools use `[ShowAsMutableObject]` and custom attributes:
```csharp
[ShowAsMutableObject]
public class CubeObject3D : PrimitiveObject3D
{
[DisplayName("Width")]
public double Width { get; set; } = 20;
[DisplayName("Depth")]
public double Depth { get; set; } = 20;
[DisplayName("Height")]
public double Height { get; set; } = 20;
}
```
### Rebuild System
Objects are rebuilt when properties change:
```csharp
public override Task Rebuild()
{
// Generate new mesh from parameters
var mesh = CreateMesh();
Mesh = mesh;
return Task.CompletedTask;
}
```
### Undo/Redo Support
Operations integrate with scene undo buffer:
```csharp
sceneContext.Scene.UndoBuffer.Add(new UndoCommand(
() => { /* undo action */ },
() => { /* redo action */ }
));
```
### Design Rationale
**Parametric Objects**: Storing parameters instead of fixed meshes enables:
- Non-destructive editing
- Dimension changes without re-creation
- Saved file size reduction
**Hierarchical Operations**: Nesting objects allows:
- Complex compositions
- Chained operations
- Clear modification history
**Property System**: Using attributes provides:
- Automatic UI generation
- Type-safe editing
- Validation support
## Reference
### Primitives
| Class | Location | Description |
|-------|----------|-------------|
| `CubeObject3D` | [DesignTools/Primitives/](MatterControlLib/DesignTools/Primitives/) | Box primitive |
| `CylinderObject3D` | [DesignTools/Primitives/](MatterControlLib/DesignTools/Primitives/) | Cylinder |
| `SphereObject3D` | [DesignTools/Primitives/](MatterControlLib/DesignTools/Primitives/) | Sphere |
| `TextObject3D` | [DesignTools/Primitives/](MatterControlLib/DesignTools/Primitives/) | 3D text |
### Operations
| Class | Location | Description |
|-------|----------|-------------|
| `ScaleObject3D` | [DesignTools/Operations/](MatterControlLib/DesignTools/Operations/) | Scale |
| `RotateObject3D` | [DesignTools/Operations/](MatterControlLib/DesignTools/Operations/) | Rotate |
| `AlignObject3D` | [DesignTools/Operations/](MatterControlLib/DesignTools/Operations/) | Align |
| `ArrayLinearObject3D` | [DesignTools/Operations/](MatterControlLib/DesignTools/Operations/) | Linear array |
### Boolean Operations
| Class | Location | Description |
|-------|----------|-------------|
| `CombineObject3D` | [DesignTools/](MatterControlLib/DesignTools/) | Union |
| `SubtractObject3D` | [DesignTools/](MatterControlLib/DesignTools/) | Subtraction |
| `IntersectObject3D` | [DesignTools/](MatterControlLib/DesignTools/) | Intersection |
### Editors
| Class | Location | Description |
|-------|----------|-------------|
| `PropertyEditor` | [DesignTools/EditorTools/](MatterControlLib/DesignTools/EditorTools/) | Property grid |
| `SheetEditor` | [DesignTools/Sheets/](MatterControlLib/DesignTools/Sheets/) | Spreadsheet editor |

View file

@ -0,0 +1,170 @@
# Print Queue & History
## Summary
MatterControl maintains print job history for tracking completed prints, managing queued items, and enabling print recovery after failures. The system stores print metadata, tracks progress, and provides analytics on print success rates.
## Technical Description
### Architecture
```
Print Management
├── Print Queue (FileSystemContainer)
│ └── Queued items for printing
├── Print History (PlatingHistoryContainer)
│ └── Completed/cancelled prints
└── PrintTask (database records)
└── Print job metadata
```
### PrintTask Entity
Database model for print jobs:
```csharp
public class PrintTask : Entity
{
public string PrintName { get; set; }
public DateTime PrintStart { get; set; }
public DateTime PrintEnd { get; set; }
public int PrintTimeSeconds { get; set; }
public double PercentDone { get; set; }
public bool PrintComplete { get; set; }
public string PrinterName { get; set; }
public string RecoveryJson { get; set; }
public int QualityWasSetByUser { get; set; }
}
```
### Print Queue
Legacy queue system using file system container:
| Class | Purpose |
|-------|---------|
| `LegacyQueueFiles` | Queue directory management |
| `FileSystemContainer` | Queue item storage |
Queue directory: `{ApplicationData}/Queue/`
### History Container
`PlatingHistoryContainer` provides access to print history:
| Feature | Description |
|---------|-------------|
| `NewBedPlate()` | Create new print session |
| Content storage | Save print bed state |
| History browsing | Access past prints |
### Print Tracking Flow
1. **Print Start:**
- Create `PrintTask` record
- Set `PrintStart` timestamp
- Initialize progress to 0%
2. **During Print:**
- Update `PercentDone`
- Save recovery data (`RecoveryJson`)
3. **Print Complete:**
- Set `PrintEnd` timestamp
- Calculate `PrintTimeSeconds`
- Set `PrintComplete` flag
4. **On Cancel:**
- Record partial completion
- Preserve recovery data
### Print Recovery
Recovery enables resuming failed prints:
```csharp
// PrintRecoveryStream handles recovery
public class PrintRecoveryStream : GCodeStream
{
// Track position and extrusion
// Resume from last known good position
}
```
**Recovery Data:**
- Last printed layer
- Current position (X, Y, Z)
- Extruded amount
- Temperature states
### History Display
`RootHistoryContainer` shows print history:
```
History
├── Printing History (PrintTask records)
│ ├── Print date/time
│ ├── Print duration
│ ├── Printer used
│ └── Completion status
└── Plating History
└── Saved bed configurations
```
### Statistics Tracking
| Metric | Storage |
|--------|---------|
| Total print count | `ApplicationSession.PrintCount` |
| Print duration | `PrintTask.PrintTimeSeconds` |
| Success rate | Calculated from `PrintComplete` |
### Events
| Event | Source | Description |
|-------|--------|-------------|
| `PrintStarted` | `PrinterConnection` | Print begins |
| `PrintFinished` | `PrinterConnection` | Print completes |
| `AnyPrintStarted` | `ApplicationController` | Global start event |
| `AnyPrintComplete` | `ApplicationController` | Global complete event |
### Design Rationale
**Database Storage**: Using SQLite for print tasks enables:
- Persistent history across sessions
- Query capabilities (by date, printer, etc.)
- Recovery data preservation
**File-Based Queue**: The queue uses file system for:
- Simple item management
- Visual thumbnails
- Easy user access to files
**Recovery System**: Saving print state allows:
- Resume after power failure
- Continue after software crash
- Re-slice and continue
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `PrintTask` | [DataStorage/Models.cs](MatterControlLib/DataStorage/Models.cs) | Print job record |
| `PrintHistory` | [PrintHistory/](MatterControlLib/PrintHistory/) | History UI |
| `LegacyQueueFiles` | [PrintQueue/LegacyQueueFiles.cs](MatterControlLib/PrintQueue/LegacyQueueFiles.cs) | Queue management |
### Library Containers
| Class | Location | Description |
|-------|----------|-------------|
| `PlatingHistoryContainer` | [Library/Providers/MatterControl/](MatterControlLib/Library/Providers/MatterControl/) | Print history |
| `RootHistoryContainer` | [Library/Providers/MatterControl/](MatterControlLib/Library/Providers/MatterControl/) | History root |
### Recovery
| Class | Location | Description |
|-------|----------|-------------|
| `PrintRecoveryStream` | [PrinterCommunication/Io/](MatterControlLib/PrinterCommunication/Io/) | Recovery stream |

View file

@ -0,0 +1,176 @@
# Plugin System
## Summary
MatterControl supports extensibility through plugin hooks, registered callbacks, and editor extensions. While not a traditional assembly-loading plugin system, it provides extension points for OEM customization, cloud services integration, and custom design tools.
## Technical Description
### Extension Points
The application provides several extension mechanisms:
```
ApplicationController
├── Plugin Delegates (cloud features)
├── Library.MenuExtensions (context menus)
├── EditorExtensions (property editors)
└── SceneOperations (design tools)
```
### Delegate-Based Plugins
`ApplicationController` exposes `Func`/`Action` delegates for plugin integration:
| Delegate | Type | Purpose |
|----------|------|---------|
| `GetPrinterProfileAsync` | `Func<PrinterInfo, string, Task<PrinterSettings>>` | Cloud profile retrieval |
| `SyncCloudProfiles` | `Func<string, Action<double,string>, Task>` | Profile sync |
| `GetPublicProfileList` | `Func<Task<OemProfileDictionary>>` | Public profile listing |
| `DownloadPublicProfileAsync` | `Func<string, Task<PrinterSettings>>` | Profile download |
| `GuestUserActive` | `Func<bool>` | Auth check |
| `GetAuthPage` | `Func<AuthenticationContext, DialogPage>` | Auth dialog |
| `UserHasPermission` | `Func<IObject3D, bool>` | Permission check |
| `UserHasPro` | `Func<bool>` | License validation |
| `PushPrintTaskToServer` | `Func<PrintTask, Task<Dictionary<string,string>>>` | Cloud tracking |
### Editor Extensions
Custom property editors registered via `EditorExtensionsConfig`:
```csharp
EditorExtensions.RegisterFactory((theme, undoBuffer) => new SheetEditor());
EditorExtensions.RegisterFactory((theme, undoBuffer) => new PropertyEditor(theme, undoBuffer));
```
**IObject3DEditor Interface:**
```csharp
public interface IObject3DEditor
{
string Name { get; }
bool Unlocked { get; }
GuiWidget Create(IObject3D item, UndoBuffer undoBuffer, ThemeConfig theme);
}
```
### Library Menu Extensions
Add custom actions to library context menus:
```csharp
Library.MenuExtensions.Add(new LibraryAction()
{
Title = "Custom Action",
Action = (items, library) => { /* implementation */ },
IsEnabled = (items, library) => true
});
```
### Scene Operations
Register custom design tools via `SceneOperations`:
```csharp
SceneOperations.RegisterOperation(
new SceneSelectionOperation()
{
Title = "Custom Operation",
Icon = iconImage,
Action = (sceneContext) => { /* implementation */ }
});
```
### OEM Customization
OEMs can customize via static data:
```
StaticData/
├── OEMSettings/
│ ├── OEMProfile.json (branding)
│ └── toc.json (help content)
├── Printers/
│ └── {OEM}/ (printer profiles)
└── Themes/
└── System/ (custom themes)
```
**OEMProfile.json:**
```json
{
"ShowHelpOption": true,
"ShowAuthenticationDialog": true,
"ShowGettingStarted": true,
"WindowTitleExtra": "OEM Edition"
}
```
### Content Providers
Register custom file format handlers:
```csharp
Library.ContentProviders.Add("custom", new CustomContentProvider());
```
**IContentProvider Interface:**
```csharp
public interface IContentProvider
{
Task<IObject3D> LoadAsync(Stream stream, CancellationToken cancellationToken);
Task SaveAsync(IObject3D object3D, Stream stream);
}
```
### Experimental Plugins
The `Plugins/Experimental` directory contains optional features:
| Plugin | Purpose |
|--------|---------|
| Part Sheet | Part information sheets |
| Custom experimental features | Beta functionality |
### Design Rationale
**Delegate Pattern**: Using function delegates instead of interfaces:
- Simplifies optional feature implementation
- No assembly scanning required
- Runtime flexibility
**Static Data Customization**: File-based OEM configuration:
- No code changes needed
- Easy deployment
- Clear separation of concerns
**Registration Patterns**: Factory/registration for extensions:
- Type-safe
- Discovery at startup
- Controlled lifecycle
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `ApplicationController` | [ApplicationView/ApplicationController.cs](MatterControlLib/ApplicationView/ApplicationController.cs) | Plugin delegates |
| `EditorExtensionsConfig` | [DesignTools/EditorExtensionsConfig.cs](MatterControlLib/DesignTools/EditorExtensionsConfig.cs) | Editor registry |
| `SceneOperations` | [ApplicationView/SceneOperations.cs](MatterControlLib/ApplicationView/SceneOperations.cs) | Operations registry |
| `OemSettings` | [SettingsManagement/OemSettings.cs](MatterControlLib/SettingsManagement/OemSettings.cs) | OEM configuration |
### Interfaces
| Interface | Purpose |
|-----------|---------|
| `IObject3DEditor` | Custom object editor |
| `IContentProvider` | File format handler |
| `INativePlatformFeatures` | Platform features |
### Extension Directories
| Directory | Purpose |
|-----------|---------|
| `Plugins/Experimental/` | Beta features |
| `StaticData/OEMSettings/` | OEM configuration |
| `StaticData/Themes/` | Custom themes |

View file

@ -0,0 +1,200 @@
# Mesh Operations
## Summary
MatterControl provides comprehensive mesh processing capabilities through the agg-sharp/PolygonMesh libraries, supporting import/export of various formats, mesh manipulation, boolean operations, repair, and optimization.
## Technical Description
### Mesh Architecture
```
Mesh (PolygonMesh)
├── Vertices (Vector3 positions)
├── Faces (triangles)
├── FaceBsp (spatial acceleration)
└── Properties
├── BoundingBox
└── Volume
```
### Supported Formats
**Import:**
| Format | Extension | Handler |
|--------|-----------|---------|
| STL | .stl | `StlProcessing` |
| OBJ | .obj | `ObjSupport` |
| AMF | .amf | `AmfDocument` |
| 3MF | .3mf | `Object3D.Load()` |
| MCX | .mcx | Native format |
**Export:**
| Format | Extension | Handler |
|--------|-----------|---------|
| STL (binary) | .stl | `MeshFileIo.Save()` |
| STL (ASCII) | .stl | `MeshFileIo.Save()` |
| AMF | .amf | `AmfDocument.Save()` |
| 3MF | .3mf | `Object3D.Save()` |
### Mesh Processing
Located in `Submodules/agg-sharp/PolygonMesh/Processors/`:
| Processor | Purpose |
|-----------|---------|
| `MeshHelper` | Common mesh operations |
| `StlProcessing` | STL import/export |
| `CsgOperations` | Boolean operations |
### Boolean Operations
CSG (Constructive Solid Geometry):
```csharp
// Union
Mesh result = CsgOperations.Union(meshA, meshB);
// Subtraction
Mesh result = CsgOperations.Subtract(meshA, meshB);
// Intersection
Mesh result = CsgOperations.Intersect(meshA, meshB);
```
**Implementation:**
- Uses BSP trees for spatial partitioning
- Handles coplanar faces
- Produces manifold output
### Mesh Repair
`RepairObject3D` fixes common mesh issues:
| Fix | Description |
|-----|-------------|
| Hole filling | Close open boundaries |
| Duplicate removal | Remove coincident vertices |
| Normal repair | Fix inverted normals |
| Non-manifold | Repair non-manifold edges |
### Mesh Decimation
`DecimateObject3D` reduces polygon count:
```csharp
public class DecimateObject3D : MeshWrapperObject3D
{
public double ReductionPercent { get; set; } = 50;
}
```
Uses edge collapse algorithm preserving shape.
### Mesh Transforms
| Operation | Method |
|-----------|--------|
| Translate | `mesh.Translate(offset)` |
| Rotate | `mesh.Transform(rotationMatrix)` |
| Scale | `mesh.Transform(scaleMatrix)` |
| Mirror | Transform with negative scale |
### Spatial Acceleration
`FaceBspTree` provides fast ray intersection:
```csharp
var bspTree = FaceBspTree.Create(mesh);
var hit = bspTree.GetClosestIntersection(ray);
```
Uses for:
- Object selection (picking)
- Collision detection
- Boolean operations
### MCX Format
Native scene format (JSON-based):
```
MCX file (ZIP archive)
├── manifest.json (metadata)
├── scene.json (scene graph)
└── Assets/
└── {guid}.stl (mesh files)
```
**Benefits:**
- Preserves scene hierarchy
- Stores parametric data
- Includes thumbnails
### Mesh Helpers
Utility methods in `MeshHelper`:
| Method | Purpose |
|--------|---------|
| `CreateCylinder()` | Generate cylinder mesh |
| `CreateCube()` | Generate box mesh |
| `CreateSphere()` | Generate sphere mesh |
| `CopyFaces()` | Duplicate face subset |
| `Split()` | Split mesh by plane |
### Volume Calculation
```csharp
double volume = mesh.GetVolume();
AxisAlignedBoundingBox bounds = mesh.GetAxisAlignedBoundingBox();
```
Used for:
- Material estimation
- Scale validation
- Build volume checking
### Design Rationale
**Custom Mesh Library**: Using PolygonMesh provides:
- Full control over algorithms
- Optimized for 3D printing use cases
- No external dependencies
**BSP Acceleration**: Spatial indexing enables:
- Fast ray casting for selection
- Efficient boolean operations
- Real-time collision checks
**MCX Format**: Custom format allows:
- Full scene preservation
- Parametric object storage
- Efficient streaming
## Reference
### Core Classes
| Class | Location | Description |
|-------|----------|-------------|
| `Mesh` | Submodules/agg-sharp/PolygonMesh | Mesh data structure |
| `Face` | Submodules/agg-sharp/PolygonMesh | Triangle face |
| `Vertex` | Submodules/agg-sharp/PolygonMesh | Vertex data |
### Processing
| Class | Location | Description |
|-------|----------|-------------|
| `StlProcessing` | Submodules/agg-sharp | STL I/O |
| `CsgOperations` | Submodules/agg-sharp | Boolean ops |
| `MeshHelper` | Submodules/agg-sharp | Utilities |
| `FaceBspTree` | Submodules/agg-sharp | Spatial index |
### MatterControl Classes
| Class | Location | Description |
|-------|----------|-------------|
| `RepairObject3D` | [DesignTools/Operations/](MatterControlLib/DesignTools/Operations/) | Mesh repair |
| `DecimateObject3D` | [DesignTools/Operations/](MatterControlLib/DesignTools/Operations/) | Decimation |
| `MeshContentProvider` | [Library/ContentProviders/](MatterControlLib/Library/ContentProviders/) | Mesh loading |

249
research/14-utilities.md Normal file
View file

@ -0,0 +1,249 @@
# Utilities & Helpers
## Summary
MatterControl includes various utility classes and helper systems supporting caching, localization, networking, thumbnail generation, and common operations used throughout the application.
## Technical Description
### Web Cache
`WebCache` provides cached HTTP requests:
```csharp
public static class WebCache
{
public static Task<string> RetrieveText(string url);
public static Task<ImageSequence> RetrieveImageSquenceAsync(string url);
public static void ClearCache();
}
```
**Features:**
- Local file caching
- Configurable expiration
- Network error handling
### Localization
The `Localizations` library handles internationalization:
```csharp
string localized = "Text to translate".Localize();
```
**Components:**
- `.po` file format
- Runtime language switching
- Fallback to English
### Thumbnail Generation
`ThumbnailsConfig` manages thumbnail creation:
```csharp
public class ThumbnailsConfig
{
public ImageBuffer LoadCachedThumbnail(ILibraryItem item, int width, int height);
public Task<ImageBuffer> GetThumbnail(ILibraryItem item, int width, int height);
public void Shutdown();
}
```
**Sources:**
1. Cached in database
2. Embedded in file (3MF, AMF)
3. Rendered from mesh
4. Default icon
### Threading Utilities
`UiThread` ensures UI thread execution:
```csharp
UiThread.RunOnIdle(() => {
// UI operations
});
UiThread.CurrentTimerMs; // High-resolution timer
```
### Safe Collections
Thread-safe collection wrappers:
```csharp
public class SafeList<T> : IEnumerable<T>
{
public void Add(T item);
public bool Remove(T item);
public void Clear();
}
```
### Running Tasks
`RunningTasksConfig` manages background operations:
```csharp
Tasks.Execute(
"Task Name",
owner,
async (reporter, cancellationToken) => {
reporter?.Invoke(0.5, "Progress message");
},
taskActions: new RunningTaskOptions()
{
PauseAction = () => { /* pause */ },
StopAction = (abort) => { /* stop */ }
});
```
### Help System
`HelpIndex` provides searchable help:
```csharp
public static class HelpIndex
{
public static bool IndexExists { get; }
public static Task RebuildIndex();
public static IEnumerable<SearchResult> Search(string query);
}
```
Uses Lucene.Net for full-text search.
### Markdown Support
`MarkdownWidget` renders markdown content:
```csharp
var markdown = new MarkdownWidget(theme, scrollable: true)
{
Markdown = "# Title\nContent here"
};
```
Uses Markdig parser with custom Agg renderer.
### Vector Math
`VectorMath` library provides:
| Type | Description |
|------|-------------|
| `Vector2` | 2D vector |
| `Vector3` | 3D vector |
| `Matrix4X4` | 4x4 transformation matrix |
| `Quaternion` | Rotation representation |
| `AxisAlignedBoundingBox` | AABB bounds |
| `Ray` | Ray for intersections |
### Color Utilities
Color manipulation helpers:
```csharp
Color.SetPreMultiply();
Color.GrayToColor(targetColor);
Color.AdjustLightness(factor);
```
### File Utilities
Common file operations:
| Class | Purpose |
|-------|---------|
| `AggContext.FileDialogs` | File open/save dialogs |
| `StaticData` | Resource file access |
| `ApplicationDataStorage` | App data paths |
### Extension Methods
Various extension helpers:
| Extension | Purpose |
|-----------|---------|
| `string.Localize()` | Translation |
| `GuiWidget.AnchorAll()` | Layout shortcut |
| `IEnumerable.IndexOf()` | Index finding |
| `Color.WithAlpha()` | Alpha adjustment |
### Clipboard Integration
System clipboard access:
```csharp
Clipboard.Instance.SetText(text);
string text = Clipboard.Instance.GetText();
bool hasImage = Clipboard.Instance.ContainsImage;
```
### Platform Abstraction
`INativePlatformFeatures` interface:
| Feature | Description |
|---------|-------------|
| `OpenUrlInBrowser()` | Launch browser |
| `IsNetworkConnected()` | Network check |
| `GetSystemFonts()` | Font enumeration |
| `GetSerialPorts()` | Serial port list |
### Design Rationale
**Static Utility Classes**: Common operations as static helpers:
- Easy access throughout codebase
- No instantiation overhead
- Clear naming conventions
**Thread-Safe Collections**: SafeList/SafeDictionary:
- Prevent race conditions
- Simple API
- Consistent behavior
**Caching**: WebCache and thumbnails:
- Improved performance
- Offline capability
- Reduced bandwidth
## Reference
### Core Utilities
| Class | Location | Description |
|-------|----------|-------------|
| `WebCache` | [Utilities/WebCache.cs](MatterControlLib/Utilities/WebCache.cs) | HTTP caching |
| `UiThread` | Submodules/agg-sharp | UI thread helper |
| `SafeList<T>` | Submodules/agg-sharp | Thread-safe list |
### Thumbnails
| Class | Location | Description |
|-------|----------|-------------|
| `ThumbnailsConfig` | [Library/ThumbnailsConfig.cs](MatterControlLib/Library/ThumbnailsConfig.cs) | Thumbnail manager |
| `MeshThumbnails` | Submodules/agg-sharp | Mesh rendering |
### Tasks
| Class | Location | Description |
|-------|----------|-------------|
| `RunningTasksConfig` | [PartPreviewWindow/RunningTasksConfig.cs](MatterControlLib/PartPreviewWindow/RunningTasksConfig.cs) | Task manager |
| `RunningTaskOptions` | [PartPreviewWindow/RunningTaskOptions.cs](MatterControlLib/PartPreviewWindow/RunningTaskOptions.cs) | Task options |
### Help
| Class | Location | Description |
|-------|----------|-------------|
| `HelpIndex` | [Library/HelpIndex.cs](MatterControlLib/Library/HelpIndex.cs) | Help search |
| `MarkdownWidget` | Submodules/agg-sharp/MarkdigAgg | Markdown display |
### Math
| Class | Location | Description |
|-------|----------|-------------|
| `Vector3` | Submodules/agg-sharp/VectorMath | 3D vector |
| `Matrix4X4` | Submodules/agg-sharp/VectorMath | Transform matrix |
| `AxisAlignedBoundingBox` | Submodules/agg-sharp/VectorMath | AABB |

View file

@ -1,58 +1,122 @@
# MatterControl Codebase Research Index
# MatterControl Codebase Documentation
This directory contains comprehensive documentation of the MatterControl 3D printing application codebase.
This directory contains comprehensive documentation of the MatterControl 3D printing software codebase.
## Project Overview
## Overview
**MatterControl** is a sophisticated 3D printing control application built in C# targeting .NET 6.0. It provides comprehensive 3D printing workflow management including model viewing, slicing, printer control, and print management.
MatterControl is a comprehensive 3D printing workflow application built by MatterHackers. It provides:
- 3D model viewing and manipulation
- Parametric design tools
- Integrated slicing (MatterSlice)
- Printer communication and control
- Library management
- Print history and recovery
### Technology Stack
- **Language:** C# (.NET 6.0)
- **UI Framework:** agg-sharp (custom 2D/3D rendering engine)
- **Database:** SQLite
- **3D Rendering:** OpenGL
- **Slicing Engine:** MatterSlice (internal)
**Technology Stack:**
- .NET 6.0 (C#)
- Custom UI framework (agg-sharp)
- OpenGL rendering
- SQLite database
- MatterSlice slicer engine
### Project Structure
- **Total C# Files:** ~965
- **Solution Projects:** 17
- **Printer Profiles:** 56+
## Documentation Index
---
| # | Document | Description |
|---|----------|-------------|
| 1 | [Core Architecture](01-core-architecture.md) | Application entry point, initialization, module organization |
| 2 | [Application Controller](02-application-controller.md) | Central singleton, workspaces, events, plugin registration |
| 3 | [UI & Rendering](03-ui-rendering.md) | Widget system, theming, tabs, popovers |
| 4 | [3D View & Part Preview](04-part-preview.md) | 3D viewport, scene context, camera, selection |
| 5 | [Printer Communication](05-printer-communication.md) | Serial communication, G-code streams, state machine |
| 6 | [Slicing System](06-slicing-system.md) | MatterSlice integration, settings mapping |
| 7 | [Library System](07-library-system.md) | Content management, containers, providers |
| 8 | [Data Storage](08-data-storage.md) | SQLite database, entities, application data |
| 9 | [Settings Management](09-settings-management.md) | Profiles, layers, presets, validation |
| 10 | [Design Tools](10-design-tools.md) | Primitives, operations, boolean, transforms |
| 11 | [Print Queue & History](11-print-queue-history.md) | Queue, history, recovery, tracking |
| 12 | [Plugin System](12-plugin-system.md) | Extension points, OEM customization |
| 13 | [Mesh Operations](13-mesh-operations.md) | Import/export, processing, CSG |
| 14 | [Utilities & Helpers](14-utilities.md) | Caching, localization, threading, math |
## Documentation Status
## Key Entry Points
| Document | Status | Last Updated |
|----------|--------|--------------|
| [Core Architecture](./01-core-architecture.md) | Pending | - |
| [Application Controller](./02-application-controller.md) | Pending | - |
| [UI & Rendering System](./03-ui-rendering.md) | Pending | - |
| [3D View & Part Preview](./04-part-preview.md) | Pending | - |
| [Printer Communication](./05-printer-communication.md) | Pending | - |
| [Slicing System](./06-slicing-system.md) | Pending | - |
| [Library & Content Management](./07-library-system.md) | Pending | - |
| [Data Storage & Persistence](./08-data-storage.md) | Pending | - |
| [Settings Management](./09-settings-management.md) | Pending | - |
| [Design Tools](./10-design-tools.md) | Pending | - |
| [Print Queue & History](./11-print-queue.md) | Pending | - |
| [Plugin System](./12-plugin-system.md) | Pending | - |
| [Mesh Operations](./13-mesh-operations.md) | Pending | - |
| [Utilities & Helpers](./14-utilities.md) | Pending | - |
| File | Purpose |
|------|---------|
| [Program.cs](../Program.cs) | Application entry point |
| [MatterControlApplication.cs](../MatterControlLib/MatterControlApplication.cs) | Static configuration |
| [RootSystemWindow.cs](../MatterControlLib/RootSystemWindow.cs) | Main window |
| [ApplicationController.cs](../MatterControlLib/ApplicationView/ApplicationController.cs) | Central controller |
---
## Project Structure
## Quick Reference
```
MatterControl/
├── MatterControl/ # Main executable
├── MatterControlLib/ # Core library
│ ├── ApplicationView/ # Application state, workspaces
│ ├── CustomWidgets/ # UI components
│ ├── DataStorage/ # Persistence layer
│ ├── DesignTools/ # Parametric design
│ ├── Library/ # Content management
│ ├── PartPreviewWindow/ # 3D view, tabs
│ ├── PrinterCommunication/# Printer connectivity
│ ├── PrintQueue/ # Queue management
│ ├── SettingsManagement/ # Application settings
│ └── SlicerConfiguration/ # Slicer settings
├── MatterControl.Printing/ # G-code, serial
├── MatterControl.OpenGL/ # OpenGL utilities
├── MatterControl.MeshOperations/ # Mesh editing
├── Plugins/ # Optional features
├── StaticData/ # Resources
└── Submodules/
├── agg-sharp/ # Rendering, UI, math
└── MatterSlice/ # Slicer engine
```
### Main Entry Points
- `Program.cs` - Application entry point
- `MatterControlLib/ApplicationView/ApplicationController.cs` - Central controller
- `MatterControlLib/ApplicationView/RootSystemWindow.cs` - Main window
## Key Namespaces
### Key Namespaces
- `MatterHackers.MatterControl` - Main application
- `MatterHackers.MatterControl.PrinterCommunication` - Printer drivers
- `MatterHackers.MatterControl.SlicerConfiguration` - Slicing settings
- `MatterHackers.MatterControl.PartPreviewWindow` - 3D visualization
- `MatterHackers.MatterControl.Library` - Content management
- `MatterHackers.MatterControl.DataStorage` - Database layer
- `MatterHackers.MatterControl.DesignTools` - 3D editing tools
| Namespace | Purpose |
|-----------|---------|
| `MatterHackers.MatterControl` | Main application |
| `MatterHackers.MatterControl.ApplicationView` | App controller, workspaces |
| `MatterHackers.MatterControl.PrinterCommunication` | Printer drivers |
| `MatterHackers.MatterControl.SlicerConfiguration` | Slicing settings |
| `MatterHackers.MatterControl.PartPreviewWindow` | 3D visualization |
| `MatterHackers.MatterControl.Library` | Content management |
| `MatterHackers.MatterControl.DataStorage` | Database layer |
| `MatterHackers.MatterControl.DesignTools` | 3D editing tools |
## Key Patterns
**Singleton Pattern:**
- `ApplicationController.Instance` - Central controller
- `Datastore.Instance` - Database access
- `ProfileManager.Instance` - Profile management
**Observer Pattern:**
- Events throughout for loose coupling
- `*Changed` events for state notifications
**Stream Pipeline:**
- G-code processing via chained streams
- Each stream transforms/filters commands
**Container Pattern:**
- Library uses hierarchical containers
- Uniform navigation across storage backends
## Dependencies
**Internal (Submodules):**
- agg-sharp - Graphics, UI, math
- MatterSlice - Slicing engine
- clipper_library - Polygon operations
- geometry3Sharp - Geometry algorithms
**External (NuGet):**
- Newtonsoft.Json - JSON serialization
- Markdig - Markdown parsing
- Lucene.Net - Full-text search
- AngleSharp - HTML parsing
- PDFsharp - PDF generation
- Zeroconf - Network discovery