-
Notifications
You must be signed in to change notification settings - Fork 41
/
PicoGK_Library.cs
579 lines (493 loc) · 20.9 KB
/
PicoGK_Library.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//
// SPDX-License-Identifier: Apache-2.0
//
// PicoGK ("peacock") is a compact software kernel for computational geometry,
// specifically for use in Computational Engineering Models (CEM).
//
// For more information, please visit https://picogk.org
//
// PicoGK is developed and maintained by LEAP 71 - © 2023-2025 by LEAP 71
// https://leap71.com
//
// Computational Engineering will profoundly change our physical world in the
// years ahead. Thank you for being part of the journey.
//
// We have developed this library to be used widely, for both commercial and
// non-commercial projects alike. Therefore, we have released it under a
// permissive open-source license.
//
// The foundation of PicoGK is a thin layer on top of the powerful open-source
// OpenVDB project, which in turn uses many other Free and Open Source Software
// libraries. We are grateful to be able to stand on the shoulders of giants.
//
// LEAP 71 licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, THE SOFTWARE IS
// PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;
namespace PicoGK
{
public partial class Library : IDisposable
{
/// <summary>
/// Returns the library name (from the C++ side)
/// </summary>
/// <returns>The name of the dynamically loaded C++ library</returns>
public static string strName()
{
StringBuilder oBuilder = new StringBuilder(Library.nStringLength);
_GetName(oBuilder);
return oBuilder.ToString();
}
/// <summary>
/// Returns the library version (from the C++ side)
/// </summary>
/// <returns>The library version of the C++ library</returns>
public static string strVersion()
{
StringBuilder oBuilder = new StringBuilder(Library.nStringLength);
_GetVersion(oBuilder);
return oBuilder.ToString();
}
/// <summary>
/// Returns internal build info, such as build date/time
/// of the C++ library
/// </summary>
/// <returns>Internal build info of the C++ library</returns>
public static string strBuildInfo()
{
StringBuilder oBuilder = new StringBuilder(Library.nStringLength);
_GetBuildInfo(oBuilder);
return oBuilder.ToString();
}
/// <summary>
/// This is the one library function that you call to run your code
/// it sets up the PicoGK library, with the specified voxel size and
/// builds the PicoGK environment with viewer, log and other internals
/// The fnTask you pass is called after everything is set up correctly
/// inside of fnTask, you do your processing, displaying it in
/// Library::oTheViewer and logging info with Library::Log()
/// </summary>
/// <param name="_fVoxelSizeMM">
/// The global voxel size in MM, for example 0.1
/// </param>
/// <param name="fnTask">
/// The task to be executed (it will run in a separate thread)
/// </param>
/// <param name="strLogFolder">
/// The folder where you want the log file (defaults to your
/// documents folder
/// </param>
/// <param name="strLogFileName">
/// The file name for your log. Defaults to PicoGK_ with date and time
/// appended. If your specify the same log file name here, it prevents
/// PicoGK from creating a new log file name everytime.
/// </param>
/// <param name="strSrcFolder">
/// This is purely a helper for you, it's not used internally. But you
/// can access this folder name throug Library::strSrcFolder, which is
/// convenient.
/// </param>
/// <exception cref="Exception">
/// Throws an exception, for a number of scenarios, for example, if the
/// library cannot be found, folders, etc. cannot be created, etc.
/// Always handle the exception to understand what's going on.
/// </exception>
public static void Go( float _fVoxelSizeMM,
ThreadStart fnTask,
string strLogFolder = "",
string strLogFileName = "",
string strSrcFolder = "",
string strLightsFile = "")
{
lock(mtxRunOnce)
{
if (bRunning)
throw new Exception("PicoGK only supports running one library config at one time");
bRunning = true;
}
Debug.Assert(_fVoxelSizeMM > 0.0f);
fVoxelSizeMM = _fVoxelSizeMM;
TestAssumptions();
if (strLogFolder == "")
strLogFolder = Utils.strDocumentsFolder();
if (strLogFileName == "")
strLogFileName = "PicoGK.log";
string strLog = Path.Combine( strLogFolder,
strLogFileName);
using (LogFile oLog = new LogFile(strLog))
{
lock (oMtxLog)
{
if (oTheLog is not null)
throw new Exception("You cannot call PicoGK.Library.Go() more than once per app (1)");
if (oTheViewer is not null)
throw new Exception("You cannot call PicoGK.Library.Go() more than once per app (2)");
oTheLog = oLog;
Library.strLogFolder = strLogFolder;
Library.strSrcFolder = strSrcFolder;
}
Log("Welcome to PicoGK");
try
{
// Create a config using physical coordinates
_Init(fVoxelSizeMM);
// Done creating C++ Library
}
catch (Exception e)
{
Log($"-----------------------------------------");
Log($"-- Could not initialize PicoGK Library --");
Log($"-----------------------------------------");
Log($"Most likely cause is that the PicoGK runtime library wasn't found");
Log($"Make sure {Config.strPicoGKLib}.dylib/.dll is accessible and has execution rights.");
Log($"See PicoGK documentation on GitHub for troubleshooting info");
Log($"Terribly long error string follows (usually devoid of real information):");
Log($"--------------------------------");
Log($"-");
Log($"{e}\n");
Log($"-");
Log($"--------------------------------");
throw new Exception("Failed to load PicoGK Library");
}
string strSearched = "";
if (strLightsFile == "")
strLightsFile = strFindLightSetupFile( strSrcFolder,
out strSearched);
if (!File.Exists(strLightsFile))
{
strSearched += strLightsFile + "\n";
Log($"Could not find a lights file - your viewer will look quite dark.");
Log($"Searched in:");
Log($"{strSearched}");
Log("You can fix this by placing the file PicoGKLights.zip into one of these folders");
Log("or providing the file as a parameter at Library.Go()");
}
Log("Creating Viewer");
Viewer? oViewer = null;
try
{
oViewer = new Viewer( "PicoGK",
new Vector2(2048f, 1024f),
oLog);
}
catch (Exception e)
{
Log("Failed to create viewer");
Log(e.ToString());
throw new Exception("Failed to create all necessary objects");
}
using (oViewer)
{
if (!bSetup())
{
Log("!! Failed to initialize !!");
return;
}
try
{
oViewer.LoadLightSetup(strLightsFile);
oViewer.SetBackgroundColor("FF");
}
catch (Exception e)
{
Log($"Failed to load Light Setup - your viewer will look dark\n{e.Message}");
}
lock (oMtxViewer)
{
oTheViewer = oViewer;
}
Thread oThread = new Thread(fnTask);
Log("Starting tasks.\n");
oThread.Start();
while (oViewer.bPoll())
{
Thread.Sleep(5); // 200 Hz is plenty
}
m_bAppExit = true;
Log("Viewer Window Closed");
}
}
lock(mtxRunOnce)
{
Debug.Assert(bRunning);
bRunning = false;
}
}
/// <summary>
/// Checks whether the task started using Go() should continue, and returns true if that's the case or false otherwise.
/// If your task can take a non-trivial amount of time, check this function periodically.
/// If it returns false, exit the task function as soon as possible.
/// </summary>
/// <param name="bAppExitOnly">If true, the bContinueTask function will only take into consideration if the application is about to exit. Any pending EndTask() requests will be ignored.</param>
/// <returns></returns>
public static bool bContinueTask(bool bAppExitOnly = false)
{
return !m_bAppExit && (bAppExitOnly || m_bContinueTask);
}
/// <summary>
/// Requests the task started by the Go() function to end.
/// Note that it's the responsability of the task to call the bContinueTask() function periodically and to honor these requests.
/// </summary>
public static void EndTask()
{
m_bContinueTask = false;
}
/// <summary>
/// Cancels any pending request to end the task.
/// </summary>
public static void CancelEndTaskRequest()
{
m_bContinueTask = true;
}
static bool m_bAppExit = false;
static bool m_bContinueTask = true;
/// <summary>
/// Thread-safe loging function
/// </summary>
/// <param name="strFormat">
/// Use like Console.Write and others, so you can do Library.Log($"My variable {fVariable}") etc.
/// </param>
/// <exception cref="Exception">
/// Will throw an exception if called before you call Library::Go, which shouldn't happen
/// </exception>
public static void Log(in string strFormat, params object[] args)
{
lock (oMtxLog)
{
if (oTheLog == null)
throw new Exception("Trying to access Log before Library::Go() was called");
oTheLog.Log(strFormat, args);
}
}
/// <summary>
/// Thread-safe access to the viewer
/// </summary>
/// <returns>The viewer object</returns>
/// <exception cref="Exception">
/// Only throws an exception if called before you call Library::Go, which shouldn't happen
/// </exception>
public static Viewer oViewer()
{
lock (oMtxViewer)
{
if (oTheViewer is null)
throw new Exception("Trying to access Viewer before Library::Go() was called");
return oTheViewer;
}
}
/// <summary>
/// This is an alternate way to run the library, instead of using "Go"
/// if you use this, you cannot invoke the viewer and the log file functions
/// You also cannot use this in a thread
///
/// Use this in headless mode
///
/// Example:
/// using (PicoGK.Library oLibrary = new(0.1f))
/// {
/// PicoGK.Voxels vox = new(PicoGK.Utils.mshCreateCube());
/// vox.mshAsMesh().SaveToStlFile(Path.Combine(PicoGK.Utils.strDocumentsFolder(), "PicoGK.stl"));
/// }
///
/// </summary>
/// <param name="fVoxelSizeMM">Voxel size in mm</param>
/// <exception cref="Exception">Throws an exception if library cannot be initialized</exception>
///
public Library(float _fVoxelSizeMM)
{
lock(mtxRunOnce)
{
if (bRunning)
throw new Exception("PicoGK only supports running one library config at one time");
bRunning = true;
}
TestAssumptions();
Debug.Assert(_fVoxelSizeMM > 0f);
fVoxelSizeMM = _fVoxelSizeMM;
try
{
// Create a config using physical coordinates
_Init(fVoxelSizeMM);
// Done creating C++ Library
}
catch (Exception)
{
throw new Exception($"Failed to load PicoGK Runtime. Make sure the PicoGK Runtime is installed and {Config.strPicoGKLib}.dylib/.dll is accessible and has execution rights.\n");
}
}
/// <summary>
/// This is an internal helper that tests if the data types have the
/// memory layout that we assume, so we don't run into interoperability issues
/// with the C++ side
/// </summary>
private static void TestAssumptions()
{
// Test a few assumptions
// Built in data type Vector3 is implicit,
// so should be compatible with our own
// structs, but let's be sure
Vector3 vec3 = new();
Vector2 vec2 = new();
Matrix4x4 mat4 = new();
Coord xyz = new(0, 0, 0);
Triangle tri = new(0, 0, 0);
ColorFloat clr = new(0f);
BBox2 oBB2 = new();
BBox3 oBB3 = new();
Debug.Assert(sizeof(bool) == 1); // 8 bit for bool assumed
Debug.Assert(Marshal.SizeOf(vec3) == ((32 * 3) / 8)); // 3 x 32 bit float
Debug.Assert(Marshal.SizeOf(vec2) == ((32 * 2) / 8)); // 2 x 32 bit float
Debug.Assert(Marshal.SizeOf(mat4) == ((32 * 16) / 8)); // 4 x 4 x 32 bit float
Debug.Assert(Marshal.SizeOf(xyz) == ((32 * 3) / 8)); // 3 x 32 bit integer
Debug.Assert(Marshal.SizeOf(tri) == ((32 * 3) / 8)); // 3 x 32 bit integer
Debug.Assert(Marshal.SizeOf(clr) == ((32 * 4) / 8)); // 4 x 32 bit float
Debug.Assert(Marshal.SizeOf(oBB2) == ((32 * 2 * 2) / 8)); // 2 x vec2
Debug.Assert(Marshal.SizeOf(oBB3) == ((32 * 3 * 2) / 8)); // 2 x vec3
// If any of these assert, then something is wrong with the
// memory layout, and the interface to compatible C libraries
// will fail - this should never happen, as all these types
// are well-defined
}
/// <summary>
/// Logs the information from the library, usually the first line of
/// defence, if something is misconfigured, for example the library path
/// Also attempts to create all data types - if this blows up, then
/// something is wrong with the C++/C# interplay
/// </summary>
/// <returns></returns>
private static bool bSetup()
{
try
{
Log($"PicoGK: {Library.strName()}");
Log($" {Library.strVersion()}");
Log($" {Library.strBuildInfo()}\n");
Log($"VoxelSize: {Library.fVoxelSizeMM} (mm)");
Log("Happy Computational Engineering!\n\n");
}
catch (Exception e)
{
Log("Failed to get PicoGK library info:\n\n{0}", e.Message);
return false;
}
try
{
Lattice lat = new();
Voxels vox = new();
Mesh msh = new();
Voxels voxM = new(msh);
Voxels voxL = new(lat);
PolyLine oPoly = new("FF0000");
}
catch (Exception e)
{
Log("Failed to instantiate basic PicoGK types:\n\n{0}", e.Message);
return false;
}
return true;
}
public static Vector3 vecVoxelsToMm( int x,
int y,
int z)
{
Vector3 vecMm = new();
Vector3 vecVoxels = new Vector3( (float) x,
(float) y,
(float) z);
_VoxelsToMm( in vecVoxels,
ref vecMm);
return vecMm;
}
public static void MmToVoxels( Vector3 vecMm,
out int x,
out int y,
out int z)
{
Vector3 vecResult = Vector3.Zero;
_VoxelsToMm( in vecMm,
ref vecResult);
x = (int) (vecResult.X + 0.5f);
y = (int) (vecResult.Y + 0.5f);
z = (int) (vecResult.Z + 0.5f);
}
public static float fVoxelSizeMM = 0.0f;
public static string strLogFolder = "";
public static string strSrcFolder = "";
private static object oMtxLog = new object();
private static object oMtxViewer = new object();
private static LogFile? oTheLog = null;
private static Viewer? oTheViewer = null;
private static object mtxRunOnce = new object();
private static bool bRunning = false;
~Library()
{
Dispose(false);
}
public static string strFindLightSetupFile( string strInputFolder,
out string strSearched)
{
strSearched = "";
string strLightsFile = Path.Combine( Utils.strPicoGKSourceCodeFolder(),
"ViewerEnvironment/PicoGKDefaultEnv.zip");
if (File.Exists(strLightsFile))
return strLightsFile;
strSearched += strLightsFile + "\n";
if (strInputFolder == "")
{
strLightsFile = Path.Combine( Utils.strDocumentsFolder(),
"PicoGKDefaultEnv.zip");
strSearched += strLightsFile + "\n";
}
else
{
strLightsFile = Path.Combine( strInputFolder,
"PicoGKDefaultEnv.zip");
strSearched += strLightsFile + "\n";
}
if (!File.Exists(strLightsFile))
{
strLightsFile = Path.Combine( Utils.strExecutableFolder(),
"ViewerEnvironment.zip");
strSearched += strLightsFile + "\n";
}
return strLightsFile;
}
public void Dispose()
{
// Dispose of unmanaged resources.
Dispose(true);
// Suppress finalization.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool bDisposing)
{
if (m_bDisposed)
{
return;
}
if (bDisposing)
{
_Destroy();
}
lock(mtxRunOnce)
{
Debug.Assert(bRunning);
bRunning = false;
}
m_bDisposed = true;
}
bool m_bDisposed = false;
}
}