@mlightcad/mtext-renderer 0.6.5 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,524 @@
1
+ # MText Renderer for Three.js
2
+
3
+ A flexible and extensible AutoCAD MText renderer implementation using Three.js. This package provides a modular architecture to render AutoCAD MText content with different rendering engines, with a primary focus on Three.js rendering.
4
+
5
+ ## Features
6
+
7
+ - Render AutoCAD MText content using Three.js
8
+ - Modular font loading system
9
+ - Font management and dynamic font loading
10
+ - Cache parsed fonts to improve rendering performance
11
+
12
+ ## Core Components
13
+
14
+ ### FontManager
15
+
16
+ The central manager for font operations. It's a singleton class that handles font loading, caching, and text rendering.
17
+
18
+ **Public Properties:**
19
+ - `unsupportedChars`: Record of characters not supported by any loaded font
20
+ - `missedFonts`: Record of fonts that were requested but not found
21
+ - `enableFontCache`: Flag to enable/disable font caching. If it is true, parsed fonts
22
+ will be stored in local IndexedDB to improve performance. Default value is true.
23
+ - `defaultFont`: Default font to use when a requested font is not found
24
+ - `events`: Event managers for font-related events
25
+ - `fontNotFound`: Triggered when a font cannot be found
26
+ - `fontLoaded`: Triggered when a font is successfully loaded
27
+
28
+ **Public Methods:**
29
+ - `getAvailableFonts()`: Retrieve metadata of available fonts from the configured loader
30
+ - `loadFontsByNames(names)`: Loads fonts by logical names (e.g., 'simsun', 'arial')
31
+ - `getCharShape(char, fontName, size)`: Gets text shape for a character
32
+ - `getFontScaleFactor(fontName)`: Gets scale factor for a font
33
+ - `getNotFoundTextShape(size)`: Gets shape for not found indicator
34
+ - `getUnsupportedChar()`: Gets record of unsupported characters
35
+ - `release()`: Releases all loaded fonts
36
+
37
+ ### FontLoader & DefaultFontLoader
38
+
39
+ Interface for font loading operations. The default implementation [DefaultFontLoader](./src/font/defaultFontLoader.ts) uses [this font repository](https://mlightcad.gitlab.io/cad-data/fonts/). It loads font metadata from a JSON file and provides access to available fonts.
40
+
41
+ You do NOT need to create `DefaultFontLoader` yourself anymore. `FontManager` manages a loader instance internally. If you want to customize font loading, implement `FontLoader` and set it via `FontManager.instance.setFontLoader(customLoader)`.
42
+
43
+ **Public Methods:**
44
+ - `load(fontNames)`: Loads specified fonts into the system
45
+ - `getAvailableFonts()`: Retrieves information about available fonts
46
+
47
+ ### BaseFont
48
+
49
+ Abstract base class for font implementations. Provides common functionality for font handling.
50
+
51
+ **Public Properties:**
52
+ - `type`: Type of font ('shx' or 'mesh')
53
+ - `data`: Parsed font data
54
+ - `unsupportedChars`: Record of unsupported characters
55
+
56
+ **Public Methods:**
57
+ - `getCharShape(char, size)`: Gets shape for a character
58
+ - `getScaleFactor()`: Gets font scale factor
59
+ - `getNotFoundTextShape(size)`: Gets shape for not found indicator
60
+
61
+ ### BaseTextShape
62
+
63
+ Abstract base class for text shape implementations. Provides common functionality for text shape handling.
64
+
65
+ **Public Properties:**
66
+ - `char`: Character this shape represents
67
+ - `size`: Size of the text shape
68
+
69
+ **Public Methods:**
70
+ - `getWidth()`: Gets width of text shape
71
+ - `getHeight()`: Gets height of text shape
72
+ - `toGeometry()`: Converts shape to THREE.BufferGeometry
73
+
74
+ ### FontFactory
75
+
76
+ Singleton factory class for creating font instances. Handles creation of appropriate font objects based on type and data format.
77
+
78
+ **Public Methods:**
79
+ - `createFont(data)`: Creates font from font data
80
+ - `createFontFromBuffer(fileName, buffer)`: Creates font from file data
81
+
82
+ ### FontCacheManager
83
+ Manages font data caching using IndexedDB. Provides persistent storage for font data.
84
+
85
+ **Public Methods:**
86
+ - `get(fileName)`: Retrieves font data from cache
87
+ - `set(fileName, fontData)`: Stores font data in cache
88
+ - `getAll()`: Retrieves all cached font data
89
+ - `clear()`: Clears all cached font data
90
+
91
+ ## Worker-Based Rendering System
92
+
93
+ The package provides a sophisticated worker-based rendering system that allows MText rendering to be performed in Web Workers, preventing blocking of the main UI thread. This is particularly beneficial for rendering large amounts of text or complex MText content.
94
+
95
+ ### MTextBaseRenderer Interface
96
+
97
+ Defines the common rendering contract for producing Three.js objects from MText content. All renderer implementations must conform to this interface.
98
+
99
+ **Public Methods:**
100
+ - `asyncRenderMText(mtextContent, textStyle, colorSettings?)`: Asynchronously render MText into a Three.js object hierarchy
101
+ - `syncRenderMText(mtextContent, textStyle, colorSettings?)`: Synchronously render MText (not supported in worker mode)
102
+ - `destroy()`: Release any resources owned by the renderer
103
+
104
+ ### MTextObject Interface
105
+
106
+ Represents a rendered MText object that extends THREE.Object3D with additional MText-specific properties.
107
+
108
+ **Public Properties:**
109
+ - `box`: The bounding box of the MText object in local coordinates
110
+
111
+ ### MainThreadRenderer
112
+
113
+ Renders MText content directly in the main thread. This is the simplest renderer implementation that provides the same interface as worker-based renderers but runs synchronously in the main thread.
114
+
115
+ **Public Methods:**
116
+ - `asyncRenderMText(mtextContent, textStyle, colorSettings?)`: Render asynchronously in the main thread (loads fonts on demand)
117
+ - `syncRenderMText(mtextContent, textStyle, colorSettings?)`: Render synchronously in the main thread (fonts must already be loaded)
118
+ - `destroy()`: Cleanup resources
119
+
120
+ ### WebWorkerRenderer (MTextWorkerManager)
121
+
122
+ Manages communication with MText Web Workers for parallel text rendering. This renderer uses a pool of Web Workers to distribute rendering tasks, improving performance for large text content.
123
+
124
+ **Public Properties:**
125
+ - `poolSize`: Number of workers in the pool (defaults to optimal size based on hardware concurrency)
126
+
127
+ **Public Methods:**
128
+ - `asyncRenderMText(mtextContent, textStyle, colorSettings?)`: Render MText using worker pool asynchronously
129
+ - `terminate()`: Terminate all workers
130
+ - `destroy()`: Cleanup all resources
131
+
132
+ **Features:**
133
+ - Automatic worker pool management
134
+ - Load balancing across workers
135
+ - Efficient serialization/deserialization of Three.js objects
136
+ - Transferable object support for optimal performance
137
+ - Error handling and timeout management
138
+
139
+ ### UnifiedRenderer
140
+
141
+ A flexible renderer that can switch between main thread and Web Worker rendering modes at runtime. This allows applications to dynamically choose the best rendering strategy based on current conditions.
142
+
143
+ **Public Properties:**
144
+ - `defaultMode`: Default rendering mode ('main' or 'worker') used when no per-call override is provided
145
+
146
+ **Public Methods:**
147
+ - `setDefaultMode(mode)`: Set the default rendering mode
148
+ - `getDefaultMode()`: Get the default rendering mode
149
+ - `asyncRenderMText(mtextContent, textStyle, colorSettings?, mode?)`: Render asynchronously; pass `mode` to override the default for this call
150
+ - `syncRenderMText(mtextContent, textStyle, colorSettings?)`: Render synchronously; always uses the main thread internally
151
+ - `destroy()`: Clean up all resources
152
+
153
+ ### MTextWorker
154
+
155
+ The actual Web Worker implementation that handles MText rendering tasks. This worker contains its own FontManager, StyleManager, and FontLoader instances, allowing it to work independently from the main thread.
156
+
157
+ **Features:**
158
+ - Independent font and style management
159
+ - Can preload fonts on demand via a `loadFonts` message to avoid redundant concurrent loads
160
+ - Efficient object serialization for transfer to main thread
161
+ - Support for transferable objects to minimize memory copying
162
+ - Error handling and response management
163
+
164
+ ### MText
165
+ Main class for rendering AutoCAD MText content. Extends THREE.Object3D to integrate with Three.js scene graph.
166
+
167
+ **Public Properties:**
168
+ - `fontManager`: Reference to FontManager instance for font operations
169
+ - `styleManager`: Reference to StyleManager instance for style operations
170
+
171
+ **Public Methods:**
172
+ - `asyncDraw()`: Asynchronously builds geometry and loads required fonts on demand
173
+ - `syncDraw()`: Synchronously builds geometry (assumes required fonts are already loaded)
174
+
175
+ ## Class Diagram
176
+
177
+ ```mermaid
178
+ classDiagram
179
+ class MText {
180
+ +content: MTextContent
181
+ +style: MTextStyle
182
+ +fontManager: FontManager
183
+ +styleManager: StyleManager
184
+ +update()
185
+ +setContent(content)
186
+ +setStyle(style)
187
+ +dispose()
188
+ }
189
+
190
+ class FontManager {
191
+ -_instance: FontManager
192
+ +unsupportedChars: Record
193
+ +missedFonts: Record
194
+ +enableFontCache: boolean
195
+ +defaultFont: string
196
+ +events: EventManagers
197
+ +loadFonts(urls)
198
+ +getCharShape(char, fontName, size)
199
+ +getFontScaleFactor(fontName)
200
+ +getNotFoundTextShape(size)
201
+ +getUnsupportedChar()
202
+ +release()
203
+ }
204
+
205
+ class FontLoader {
206
+ <<interface>>
207
+ +load(fontNames)
208
+ +getAvailableFonts()
209
+ }
210
+
211
+ class DefaultFontLoader {
212
+ -_avaiableFonts: FontInfo[]
213
+ +load(fontNames)
214
+ +getAvailableFonts()
215
+ }
216
+
217
+ class BaseFont {
218
+ <<abstract>>
219
+ +type: FontType
220
+ +data: unknown
221
+ +unsupportedChars: Record
222
+ +getCharShape(char, size)
223
+ +getScaleFactor()
224
+ +getNotFoundTextShape(size)
225
+ }
226
+
227
+ class BaseTextShape {
228
+ <<abstract>>
229
+ +char: string
230
+ +size: number
231
+ +getWidth()
232
+ +getHeight()
233
+ +toGeometry()
234
+ }
235
+
236
+ class FontFactory {
237
+ -_instance: FontFactory
238
+ +createFont(data)
239
+ +createFontFromBuffer(fileName, buffer)
240
+ }
241
+
242
+ class FontCacheManager {
243
+ -_instance: FontCacheManager
244
+ +get(fileName)
245
+ +set(fileName, fontData)
246
+ +getAll()
247
+ +clear()
248
+ }
249
+
250
+ class MTextBaseRenderer {
251
+ <<interface>>
252
+ +asyncRenderMText(mtextContent, textStyle, colorSettings?)
253
+ +syncRenderMText(mtextContent, textStyle, colorSettings?)
254
+ +loadFonts(fonts)
255
+ +getAvailableFonts()
256
+ +destroy()
257
+ }
258
+
259
+ class MTextObject {
260
+ <<interface>>
261
+ +box: Box3
262
+ }
263
+
264
+ class MainThreadRenderer {
265
+ -fontManager: FontManager
266
+ -styleManager: StyleManager
267
+ -fontLoader: DefaultFontLoader
268
+ +asyncRenderMText(mtextContent, textStyle, colorSettings?)
269
+ +syncRenderMText(mtextContent, textStyle, colorSettings?)
270
+ +loadFonts(fonts)
271
+ +getAvailableFonts()
272
+ +destroy()
273
+ }
274
+
275
+ class WebWorkerRenderer {
276
+ -workers: Worker[]
277
+ -inFlightPerWorker: number[]
278
+ -pendingRequests: Map
279
+ -poolSize: number
280
+ +asyncRenderMText(mtextContent, textStyle, colorSettings?)
281
+ +loadFonts(fonts)
282
+ +getAvailableFonts()
283
+ +terminate()
284
+ +destroy()
285
+ }
286
+
287
+ class UnifiedRenderer {
288
+ -webWorkerRenderer: WebWorkerRenderer
289
+ -mainThreadRenderer: MainThreadRenderer
290
+ -renderer: MTextBaseRenderer
291
+ -defaultMode: RenderMode
292
+ +setDefaultMode(mode)
293
+ +getDefaultMode()
294
+ +asyncRenderMText(mtextContent, textStyle, colorSettings?, mode?)
295
+ +syncRenderMText(mtextContent, textStyle, colorSettings?)
296
+ +loadFonts(fonts)
297
+ +getAvailableFonts()
298
+ +destroy()
299
+ }
300
+
301
+ class MTextWorker {
302
+ +fontManager: FontManager
303
+ +styleManager: StyleManager
304
+ +fontLoader: DefaultFontLoader
305
+ +serializeMText(mtext)
306
+ +serializeChildren(mtext)
307
+ }
308
+
309
+ MText --> FontManager
310
+ MText --> StyleManager
311
+ FontManager --> FontFactory
312
+ FontManager --> FontCacheManager
313
+ FontManager --> BaseFont
314
+ DefaultFontLoader ..|> FontLoader
315
+ BaseFont <|-- MeshFont
316
+ BaseFont <|-- ShxFont
317
+ BaseTextShape <|-- MeshTextShape
318
+ BaseTextShape <|-- ShxTextShape
319
+ MainThreadRenderer ..|> MTextBaseRenderer
320
+ WebWorkerRenderer ..|> MTextBaseRenderer
321
+ UnifiedRenderer --> WebWorkerRenderer
322
+ UnifiedRenderer --> MainThreadRenderer
323
+ UnifiedRenderer ..|> MTextBaseRenderer
324
+ MTextWorker --> FontManager
325
+ MTextWorker --> StyleManager
326
+ MTextWorker --> DefaultFontLoader
327
+ WebWorkerRenderer --> MTextWorker
328
+ MTextBaseRenderer --> MTextObject
329
+ ```
330
+
331
+ ## Usage
332
+
333
+ ```typescript
334
+ import * as THREE from 'three';
335
+ import { FontManager, MText, StyleManager } from '@mlightcad/mtext-renderer';
336
+
337
+ // Initialize core components
338
+ const fontManager = FontManager.instance;
339
+ const styleManager = new StyleManager();
340
+
341
+ // Optionally preload a font (otherwise MText will load on demand in asyncDraw())
342
+ await fontManager.loadFontsByNames(['simsun']);
343
+
344
+ // Create MText content
345
+ const mtextContent = {
346
+ text: '{\\fArial|b0|i0|c0|p34;Hello World}',
347
+ height: 0.1,
348
+ width: 0,
349
+ position: new THREE.Vector3(0, 0, 0),
350
+ };
351
+
352
+ // Create MText instance with style
353
+ const mtext = new MText(
354
+ mtextContent,
355
+ {
356
+ name: 'Standard',
357
+ standardFlag: 0,
358
+ fixedTextHeight: 0.1,
359
+ widthFactor: 1,
360
+ obliqueAngle: 0,
361
+ textGenerationFlag: 0,
362
+ lastHeight: 0.1,
363
+ font: 'Standard',
364
+ bigFont: '',
365
+ color: 0xffffff,
366
+ },
367
+ styleManager,
368
+ fontManager
369
+ );
370
+
371
+ // Build geometry and load fonts on demand
372
+ await mtext.asyncDraw();
373
+
374
+ // Add to Three.js scene
375
+ scene.add(mtext);
376
+ ```
377
+
378
+ ### Synchronous usage (fonts must be preloaded)
379
+
380
+ ```typescript
381
+ // Ensure required fonts are loaded beforehand
382
+ await fontManager.loadFontsByNames(['simsun']);
383
+
384
+ const mtext = new MText(mtextContent, textStyle, styleManager, fontManager);
385
+
386
+ // Build geometry synchronously (no awaits here)
387
+ mtext.syncDraw();
388
+ scene.add(mtext);
389
+ ```
390
+
391
+ ## Worker-Based Rendering Usage
392
+
393
+ ### Using MainThreadRenderer
394
+
395
+ ```typescript
396
+ import { MainThreadRenderer } from '@mlightcad/mtext-renderer';
397
+
398
+ // Create main thread renderer
399
+ const renderer = new MainThreadRenderer();
400
+
401
+ // Render MText content asynchronously (fonts are loaded on demand)
402
+ const mtextObject = await renderer.asyncRenderMText(
403
+ mtextContent,
404
+ textStyle,
405
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
406
+ );
407
+
408
+ // Add to scene
409
+ scene.add(mtextObject);
410
+
411
+ // Or render synchronously (fonts must be preloaded)
412
+ // await renderer.loadFonts(['simsun']);
413
+ const syncObject = renderer.syncRenderMText(
414
+ mtextContent,
415
+ textStyle,
416
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
417
+ );
418
+ scene.add(syncObject);
419
+ ```
420
+
421
+ ### Using WebWorkerRenderer
422
+
423
+ ```typescript
424
+ import { WebWorkerRenderer } from '@mlightcad/mtext-renderer';
425
+
426
+ // Create worker renderer with custom pool size
427
+ const workerRenderer = new WebWorkerRenderer({ poolSize: 4 }); // 4 workers
428
+
429
+ // Optionally preload fonts once via a coordinator to avoid duplicate concurrent loads
430
+ // await workerRenderer.loadFonts(['simsun', 'arial']);
431
+
432
+ // Render MText content using workers asynchronously (fonts loaded on demand)
433
+ const mtextObject = await workerRenderer.asyncRenderMText(
434
+ mtextContent,
435
+ textStyle,
436
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
437
+ );
438
+
439
+ // Add to scene
440
+ scene.add(mtextObject);
441
+
442
+ // Clean up when done
443
+ workerRenderer.destroy();
444
+ ```
445
+
446
+ Note: Synchronous rendering is not supported in worker mode.
447
+
448
+ ### Using UnifiedRenderer
449
+
450
+ ```typescript
451
+ import { UnifiedRenderer } from '@mlightcad/mtext-renderer';
452
+
453
+ // Create unified renderer with default mode 'main' (optional worker config as second param)
454
+ const unifiedRenderer = new UnifiedRenderer('main');
455
+
456
+ // Render using default mode (main) asynchronously (fonts loaded on demand)
457
+ let mtextObject = await unifiedRenderer.asyncRenderMText(
458
+ mtextContent,
459
+ textStyle,
460
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff }
461
+ );
462
+
463
+ scene.add(mtextObject);
464
+
465
+ // Change default mode to worker for subsequent calls
466
+ unifiedRenderer.setDefaultMode('worker');
467
+
468
+ // Or override mode per call without changing the default
469
+ // e.g., render this heavy content in worker, regardless of default
470
+ mtextObject = await unifiedRenderer.asyncRenderMText(
471
+ heavyMtextContent,
472
+ textStyle,
473
+ { byLayerColor: 0xffffff, byBlockColor: 0xffffff },
474
+ 'worker'
475
+ );
476
+
477
+ scene.add(mtextObject);
478
+
479
+ // Clean up
480
+ unifiedRenderer.destroy();
481
+ ```
482
+
483
+ `syncRenderMText` always renders on the main thread (fonts must be preloaded). This method is not available in the worker renderer, so the unified renderer routes it to the main-thread implementation regardless of the current default mode.
484
+
485
+ ### Performance Considerations
486
+
487
+ **When to use MainThreadRenderer:**
488
+ - Simple MText content with few characters
489
+ - When you need immediate synchronous results (use `syncRenderMText`)
490
+ - When worker overhead would be greater than rendering time
491
+
492
+ **When to use WebWorkerRenderer:**
493
+ - Large amounts of MText content
494
+ - Complex text with many formatting codes
495
+ - When you want to keep the main thread responsive
496
+ - Batch processing of multiple MText objects
497
+ - Note: Only asynchronous rendering is supported in workers
498
+
499
+ **When to use UnifiedRenderer:**
500
+ - Applications that need to switch rendering strategies dynamically
501
+ - When rendering requirements vary based on content complexity
502
+ - Development environments where you want to test both approaches
503
+
504
+ If all of fonts or certain fonts are not needed any more after rendering, you can call method `release` of class `FontManager` to free memory occupied by them. Based on testing, one Chinese mesh font file may take 40M memory.
505
+
506
+ ```typescript
507
+ // ---
508
+ // FontManager: Releasing Fonts
509
+ // ---
510
+ // To release all loaded fonts and free memory:
511
+ fontManager.release();
512
+
513
+ // To release a specific font by name (e.g., 'simsun'):
514
+ fontManager.release('simsun');
515
+ // Returns true if the font was found and released, false otherwise.
516
+ ```
517
+
518
+ ## License
519
+
520
+ MIT
521
+
522
+ ## Contributing
523
+
524
+ Contributions are welcome! Please read our contributing guidelines for details.