chijin 0.3.3

Minimal Rust bindings for OpenCASCADE (OCC 7.9)
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
use std::env;
use std::io::Read;
use std::path::{Path, PathBuf};

fn main() {
	if env::var("DOCS_RS").is_ok() {
		return;
	}

	let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
	let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

	let (occt_include, occt_lib_dir) = if cfg!(feature = "bundled") {
		build_occt_from_source(&out_dir, &manifest_dir)
	} else if cfg!(feature = "prebuilt") {
		use_system_occt()
	} else {
		panic!("Either 'bundled' or 'prebuilt' feature must be enabled");
	};

	link_occt_libraries(&occt_include, &occt_lib_dir, cfg!(feature = "color"));
}

fn link_occt_libraries(occt_include: &Path, occt_lib_dir: &Path, color: bool) {
	// Required OCC toolkit libraries to link against (OCCT 7.8+ / 7.9.x naming).
	// In OCCT 7.8+: TKSTEP*/TKBinTools/TKShapeUpgrade were reorganized into
	// TKDESTEP/TKBin/TKShHealing respectively.
	let occ_libs = &[
		"TKernel",
		"TKMath",
		"TKBRep",
		"TKTopAlgo",
		"TKPrim",
		"TKBO",
		"TKBool",
		"TKShHealing", // includes former TKShapeUpgrade
		"TKMesh",
		"TKGeomBase",
		"TKGeomAlgo",
		"TKG3d",
		"TKG2d",
		"TKBin",       // was TKBinTools
		"TKXSBase",
		"TKDE",        // DE framework base (OCCT 7.8+)
		"TKDECascade", // DE cascade bridge (OCCT 7.8+)
		"TKDESTEP",    // was TKSTEP + TKSTEP209 + TKSTEPAttr + TKSTEPBase
		// TKService is NOT linked here: it contains Image_AlienPixMap (WIC image I/O)
		// which pulls in ole32/windowscodecs on Windows, but image I/O is unused in
		// the base API.  TKService is added below only when "color" is enabled because
		// TKXCAF references Graphic3d_* symbols that live in TKService.
	];

	// Link OCC libraries
	println!("cargo:rustc-link-search=native={}", occt_lib_dir.display());
	for lib in occ_libs {
		println!("cargo:rustc-link-lib=static={}", lib);
	}

	// XDE (XDE-based STEP with color) requires ApplicationFramework libs.
	// In OCCT 7.9.3, library layout (verified by nm):
	//   TKLCAF   — TDocStd_Document, TDocStd_Application (NewDocument / Close)
	//   TKXCAF   — XCAFApp_Application, XCAFDoc_ColorTool, XCAFDoc_ShapeTool,
	//              XCAFDoc_DocumentTool
	//   TKCAF    — TNaming_NamedShape, TNaming_Builder (needed by TKXCAF's XCAFDoc)
	//   TKCDF    — CDM_Document, CDM_Application (needed by TKLCAF's TDocStd_Document)
	//   TKDESTEP — STEPCAFControl_Reader / Writer (already in OCC_LIBS above)
	//   TKService — Graphic3d_* symbols referenced by TKXCAF (XCAFDoc_VisMaterial etc.)
	if color {
		for lib in &["TKLCAF", "TKXCAF", "TKCAF", "TKCDF"] {
			println!("cargo:rustc-link-lib=static={}", lib);
		}
	}

	// Safety-net: suppress any residual duplicate-symbol errors when linking
	// against OCCT static libraries on MinGW.  The primary fix is the
	// OCC_CONVERT_SIGNALS define added below to the cxx_build step.
	println!("cargo:rustc-link-arg=-Wl,--allow-multiple-definition");

	// TKernel's OSD_WNT.cxx registers a static initialiser (Init_OSD_WNT) that
	// calls advapi32 functions (AllocateAndInitializeSid etc.) at program startup.
	// Standard_Macro.hxx forcibly undefs OCCT_UWP unless WINAPI_FAMILY_APP is set,
	// so the dependency cannot be removed via compiler flags alone.
	// Rust passes -nodefaultlibs, bypassing GCC's spec that normally adds -ladvapi32.
	//
	// Additional Windows system libs required by OCCT static libs (color feature only):
	//   ole32         — Image_AlienPixMap uses CoInitializeEx / CoCreateInstance /
	//                   CreateStreamOnHGlobal / GetHGlobalFromStream (WIC image I/O)
	//   windowscodecs — GUID_WICPixelFormat* / CLSID_WICImagingFactory data symbols
	//                   (pulled in transitively via TKService → Image_AlienPixMap)
	if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
		println!("cargo:rustc-link-arg=-ladvapi32");
	}

	// Build cxx bridge + C++ wrapper
	let mut build = cxx_build::bridge("src/ffi.rs");
	build
		.file("cpp/wrapper.cpp")
		.include(occt_include)
		.std("c++17")
		.define("_USE_MATH_DEFINES", None);

	// Define CHIJIN_COLOR for C++ when the "color" feature is enabled.
	if color {
		build.define("CHIJIN_COLOR", None);
	}

	// On MinGW (Windows GNU toolchain), GCC at -O0 emits inline C++ methods
	// (from Standard_ErrorHandler.hxx) as strong (non-COMDAT) symbols in wrapper.o.
	// TKernel.a unconditionally defines the same methods in Standard_ErrorHandler.cxx.obj.
	// This causes "multiple definition" link errors.
	//
	// Standard_ErrorHandler.hxx only generates the inline stubs when OCC_CONVERT_SIGNALS
	// is NOT defined (via `#if !defined(OCC_CONVERT_SIGNALS)`).  Defining it here
	// suppresses those stubs in wrapper.o so only TKernel.a's implementation is linked.
	if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
		&& env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("gnu")
	{
		build.define("OCC_CONVERT_SIGNALS", None);
	}

	build.compile("chijin_cpp");

	println!("cargo:rerun-if-changed=src/ffi.rs");
	println!("cargo:rerun-if-changed=cpp/wrapper.h");
	println!("cargo:rerun-if-changed=cpp/wrapper.cpp");
}

/// Feature "bundled": Download OCCT 7.9.3 source and build with CMake.
fn build_occt_from_source(out_dir: &Path, manifest_dir: &Path) -> (PathBuf, PathBuf) {
	let occt_version = "V7_9_3";
	let occt_url = format!(
		"https://github.com/Open-Cascade-SAS/OCCT/archive/refs/tags/{}.tar.gz",
		occt_version
	);

	let download_dir = out_dir.join("occt-source");

	// Use a sentinel file to track successful extraction.
	let extraction_sentinel = download_dir.join(".extraction_done");

	if !extraction_sentinel.exists() {
		std::fs::create_dir_all(&download_dir).unwrap();

		// Clean up any partial extraction from a previous failed attempt
		if let Ok(entries) = std::fs::read_dir(&download_dir) {
			for entry in entries.flatten() {
				let name = entry.file_name();
				if name.to_string_lossy().starts_with("OCCT") && entry.path().is_dir() {
					eprintln!("Removing partial OCCT extraction: {:?}", name);
					let _ = std::fs::remove_dir_all(entry.path());
				}
			}
		}

		eprintln!("Downloading OCCT {} ...", occt_version);

		// Download using ureq (pure Rust HTTP client)
		let response = ureq::get(&occt_url)
			.call()
			.expect("Failed to download OCCT source tarball");

		let mut body = Vec::new();
		response
			.into_body()
			.into_reader()
			.read_to_end(&mut body)
			.expect("Failed to read OCCT download response body");

		eprintln!("Downloaded {} bytes. Extracting...", body.len());

		// Extract using libflate + tar (pure Rust)
		let gz_decoder =
			libflate::gzip::Decoder::new(&body[..]).expect("Failed to initialize gzip decoder");
		let mut archive = tar::Archive::new(gz_decoder);
		archive
			.unpack(&download_dir)
			.expect("Failed to extract OCCT source tarball");

		// Write sentinel to mark successful extraction
		std::fs::write(&extraction_sentinel, "done").unwrap();
		eprintln!("OCCT source extracted successfully.");
	}

	// Auto-detect the extracted OCCT directory name
	// (GitHub archives may name it OCCT-V7_9_3 or OCCT-7_9_3 depending on the tag)
	let source_dir = std::fs::read_dir(&download_dir)
		.expect("Failed to read occt-source directory")
		.flatten()
		.find(|e| e.file_name().to_string_lossy().starts_with("OCCT") && e.path().is_dir())
		.map(|e| e.path())
		.expect("OCCT source directory not found after extraction");

	// Patch OCCT sources to remove TKService (Visualization) dependencies.
	// XCAFDoc_VisMaterial.cxx and XCAFPrs_Texture.cxx reference Graphic3d_* symbols
	// that live in TKService, which we don't build (BUILD_MODULE_Visualization=OFF).
	// The non-visualization TDF_Attribute methods (GetID, Restore, Paste, …) are
	// kept intact; only FillMaterialAspect / FillAspect are emptied.
	patch_occt_sources(&source_dir);

	// Install into target/occt for a stable, predictable location
	let occt_root = manifest_dir.join("target").join("occt");

	// Determine lib path (CMake on Windows/MinGW installs to win64/gcc/lib)
	let lib_dir = find_occt_lib_dir(&occt_root);

	// Build with CMake only if not already installed
	if !lib_dir.exists() {
		eprintln!("Building OCCT with CMake (this may take a while)...");

		let built = cmake::Config::new(&source_dir)
			.define("BUILD_LIBRARY_TYPE", "Static")
			.define("CMAKE_INSTALL_PREFIX", occt_root.to_str().unwrap())
			// Disable optional dependencies we don't need
			.define("USE_FREETYPE", "OFF")
			.define("USE_FREEIMAGE", "OFF")
			.define("USE_OPENVR", "OFF")
			.define("USE_FFMPEG", "OFF")
			.define("USE_TBB", "OFF")
			.define("USE_VTK", "OFF")
			.define("USE_RAPIDJSON", "OFF")
			.define("USE_DRACO", "OFF")
			.define("USE_TK", "OFF")
			.define("USE_TCL", "OFF")                                                                                                   
			.define("USE_XLIB", "OFF")
			.define("USE_OPENGL", "OFF")
			.define("USE_GLES2", "OFF")
			.define("USE_EGL", "OFF")
			.define("USE_D3D", "OFF")
			// Only build the modules we need
			.define("BUILD_MODULE_FoundationClasses", "ON")
			.define("BUILD_MODULE_ModelingData", "ON")
			.define("BUILD_MODULE_ModelingAlgorithms", "ON")
			.define("BUILD_MODULE_DataExchange", "ON")
			.define("BUILD_MODULE_Visualization", "OFF")
			.define("BUILD_MODULE_ApplicationFramework", "OFF")
			.define("BUILD_MODULE_Draw", "OFF")
			.define("BUILD_DOC_Overview", "OFF")
			.define("BUILD_DOC_RefMan", "OFF")
			.define("BUILD_YACCLEX", "OFF")
			.define("BUILD_RESOURCES", "OFF")
			.define("BUILD_SAMPLES_MFC", "OFF")
			.define("BUILD_SAMPLES_QT", "OFF")
			.define("BUILD_Inspector", "OFF")
			.define("BUILD_ENABLE_FPE_SIGNAL_HANDLER", "OFF")
			.build();

		eprintln!("OCCT built at: {}", built.display());
	}

	// Re-resolve lib dir after build (in case it was just created)
	let lib_dir = find_occt_lib_dir(&occt_root);
	let include_dir = find_occt_include_dir(&occt_root);

	(include_dir, lib_dir)
}

/// Find the OCCT include directory, checking common install layouts.
fn find_occt_include_dir(occt_root: &Path) -> PathBuf {
	let candidates = [
		occt_root.join("include").join("opencascade"),
		occt_root.join("inc"),
		occt_root.join("include"),
	];
	for dir in &candidates {
		if dir.exists() {
			return dir.clone();
		}
	}
	// Default fallback
	occt_root.join("include")
}

/// Find the OCCT lib directory, checking common install layouts.
/// CMake on Windows/MinGW installs to win64/gcc/lib; on Linux to lib.
fn find_occt_lib_dir(occt_root: &Path) -> PathBuf {
	let candidates = [
		occt_root.join("lib"),
		occt_root.join("win64").join("gcc").join("lib"),
		occt_root.join("win64").join("vc14").join("lib"),
	];
	for dir in &candidates {
		if dir.exists() {
			return dir.clone();
		}
	}
	// Default fallback
	occt_root.join("lib")
}

/// Feature "prebuilt": Use system-installed OCCT.
fn use_system_occt() -> (PathBuf, PathBuf) {
	let occt_root = env::var("OCCT_ROOT")
		.or_else(|_| env::var("CASROOT"))
		.expect(
			"OCCT_ROOT or CASROOT environment variable must be set \
             when using the 'prebuilt' feature",
		);

	let occt_root = PathBuf::from(occt_root);

	let include_dir = find_occt_include_dir(&occt_root);
	let lib_dir = find_occt_lib_dir(&occt_root);

	assert!(
		include_dir.exists(),
		"OCCT include directory not found at {}",
		include_dir.display()
	);
	assert!(
		lib_dir.exists(),
		"OCCT lib directory not found at {}",
		lib_dir.display()
	);

	(include_dir, lib_dir)
}

/// Patch two OCCT source files that pull in Graphic3d_* (TKService) symbols even
/// when BUILD_MODULE_Visualization=OFF:
///
///  - XCAFDoc/XCAFDoc_VisMaterial.cxx: remove #include lines for Graphic3d_Aspects,
///    Graphic3d_MaterialAspect and XCAFPrs_Texture, then empty the bodies of
///    FillMaterialAspect() and FillAspect() — the only methods that use those types.
///    All TDF_Attribute interface methods (GetID, Restore, Paste, …) are left intact.
///
///  - XCAFPrs/XCAFPrs_Texture.cxx: replaced with an empty file because it defines
///    XCAFPrs_Texture which inherits from Graphic3d_Texture2D (TKService).
///    The only caller was FillAspect(), which is now empty.
fn patch_occt_sources(source_dir: &Path) {
	patch_remove_includes_and_stub_methods(
		&source_dir.join("src/XCAFDoc/XCAFDoc_VisMaterial.cxx"),
		&[
			"Graphic3d_Aspects.hxx",
			"Graphic3d_MaterialAspect.hxx",
			"XCAFPrs_Texture.hxx",
		],
		&[
			"XCAFDoc_VisMaterial::FillMaterialAspect",
			"XCAFDoc_VisMaterial::FillAspect",
			// ConvertToPbrMaterial / ConvertToCommonMaterial use Graphic3d_PBRMaterial
			// (defined in Graphic3d_MaterialAspect.hxx which we removed above).
			"XCAFDoc_VisMaterial::ConvertToPbrMaterial",
			"XCAFDoc_VisMaterial::ConvertToCommonMaterial",
		],
	);

	let texture_cxx = source_dir.join("src/XCAFPrs/XCAFPrs_Texture.cxx");
	if texture_cxx.exists() {
		std::fs::write(&texture_cxx, "// Stubbed: TKService not built\n")
			.expect("Failed to patch XCAFPrs_Texture.cxx");
		eprintln!("Patched XCAFPrs_Texture.cxx");
	}
}

/// Read `path`, strip #include lines whose filename matches any entry in
/// `includes_to_remove`, empty the bodies of functions whose qualified name
/// matches any entry in `methods_to_stub`, then write back.
fn patch_remove_includes_and_stub_methods(
	path: &Path,
	includes_to_remove: &[&str],
	methods_to_stub: &[&str],
) {
	if !path.exists() {
		return;
	}
	let content = std::fs::read_to_string(path).expect("Failed to read file for patching");

	// Remove matching #include lines.
	let patched: String = content
		.lines()
		.filter(|line| {
			let t = line.trim();
			if !t.starts_with("#include") {
				return true;
			}
			!includes_to_remove.iter().any(|pat| t.contains(pat))
		})
		.collect::<Vec<_>>()
		.join("\n") + "\n";

	// Empty bodies of each listed method.
	let patched = methods_to_stub
		.iter()
		.fold(patched, |s, m| empty_method_body(&s, m));

	std::fs::write(path, patched).expect("Failed to write patched file");
	eprintln!("Patched {}", path.file_name().unwrap().to_string_lossy());
}

/// Find the first definition of `method_name` in `content` and replace its
/// brace-delimited body `{ … }` with `{}`.  Returns the (possibly unchanged)
/// string.  Uses brace counting so nested braces inside the body are handled
/// correctly; string/character literals are intentionally ignored because OCCT
/// source doesn't embed `{`/`}` inside string literals in these methods.
fn empty_method_body(content: &str, method_name: &str) -> String {
	let Some(name_pos) = content.find(method_name) else {
		return content.to_string();
	};

	// Detect return type: look at the text between the nearest preceding newline
	// and the method name.  If "void" appears there, an empty body `{}` is valid;
	// otherwise use `{ return {}; }` to value-initialise the return type.
	let sig_start = content[..name_pos].rfind('\n').map(|p| p + 1).unwrap_or(0);
	let stub_body = if content[sig_start..name_pos].contains("void") {
		"{}"
	} else {
		"{ return {}; }"
	};

	let after_name = &content[name_pos..];
	let Some(brace_offset) = after_name.find('{') else {
		return content.to_string();
	};
	let brace_start = name_pos + brace_offset;

	let bytes = content.as_bytes();
	let mut depth = 0usize;
	let mut i = brace_start;
	while i < bytes.len() {
		match bytes[i] {
			b'{' => depth += 1,
			b'}' => {
				depth -= 1;
				if depth == 0 {
					return format!("{}{}{}",
						&content[..brace_start],
						stub_body,
						&content[i + 1..]);
				}
			}
			_ => {}
		}
		i += 1;
	}
	content.to_string()
}