-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbuild.rs
239 lines (228 loc) · 8.44 KB
/
build.rs
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
use std::cell::RefCell;
use std::collections::HashMap;
use std::env::var;
use std::path::PathBuf;
use bindgen::callbacks::{EnumVariantValue, ParseCallbacks};
use once_cell::sync::Lazy;
#[derive(Debug, Copy, Clone)]
pub enum StripMode {
/// Strip N items at front, e.g N=1: FOO_BAR_ZOO => BAR_ZOO
StripFront(u8),
/// Keeps N items at tail, e.g N=1: FOO_BAR_ZOO => ZOO
KeepTail(u8),
}
impl StripMode {
pub fn new(m: i32) -> Self {
if m < 0 {
StripMode::KeepTail(m.abs() as u8)
} else {
StripMode::StripFront(m as u8)
}
}
pub fn strip_long_name<'a>(&self, name: &'a str) -> &'a str {
let mut iter = name.match_indices('_');
let elem = match self {
StripMode::KeepTail(i) => iter.nth_back((i - 1) as usize),
StripMode::StripFront(i) => iter.nth((i - 1) as usize),
};
let new_name = match elem {
Some((idx, _)) => &name[idx + 1..name.len()],
None => {
eprintln!("{} Not enough length: {}", line!(), name);
name
}
};
match new_name.chars().take(1).next() {
None => {
eprintln!("{} Empty string {}", line!(), name);
name
}
// If after first pass the name starts with a digit (illegal name) do another pass
Some(c) if c.is_digit(10) => match self {
StripMode::StripFront(v) => StripMode::StripFront(v + 1),
StripMode::KeepTail(v) => StripMode::KeepTail(v + 1),
}
.strip_long_name(name),
Some(_) => new_name,
}
}
}
static ENUMS: Lazy<HashMap<&str, (&str, i32)>> = Lazy::new(|| {
// -N translates to StripMode::StripFront(N)
// N translates to StripMode::KeepFront(N)
let mut map = HashMap::new();
map.insert("HAPI_License", ("auto", -2));
map.insert("HAPI_Result", ("HapiResult", 2));
map.insert("HAPI_StatusType", ("auto", -2));
map.insert("HAPI_State", ("auto", 2));
map.insert("HAPI_PDG_WorkItemState", ("PdgWorkItemState", -1));
map.insert("HAPI_PDG_EventType", ("PdgEventType", -3));
map.insert("HAPI_PDG_State", ("PdgState", -1));
map.insert("HAPI_CacheProperty", ("auto", -2));
map.insert("HAPI_EnvIntType", ("auto", -2));
map.insert("HAPI_PrmScriptType", ("auto", -2));
map.insert("HAPI_Permissions", ("auto", -2));
map.insert("HAPI_ParmType", ("auto", 2));
map.insert("HAPI_PartType", ("auto", -1));
map.insert("HAPI_StatusVerbosity", ("auto", -1));
map.insert("HAPI_SessionType", ("auto", -1));
map.insert("HAPI_PackedPrimInstancingMode", ("auto", -1));
map.insert("HAPI_RampType", ("auto", -1));
map.insert("HAPI_ErrorCode", ("auto", -1));
map.insert("HAPI_NodeFlags", ("auto", -1));
map.insert("HAPI_NodeType", ("auto", -1));
map.insert("HAPI_HeightFieldSampling", ("auto", -1));
map.insert("HAPI_SessionEnvIntType", ("auto", -1));
map.insert("HAPI_ImagePacking", ("auto", -1));
map.insert("HAPI_ImageDataFormat", ("auto", -1));
map.insert("HAPI_XYZOrder", ("auto", -1));
map.insert("HAPI_RSTOrder", ("auto", -1));
map.insert("HAPI_TransformComponent", ("auto", -1));
map.insert("HAPI_CurveOrders", ("auto", -1));
map.insert("HAPI_InputType", ("auto", -1));
map.insert("HAPI_GeoType", ("auto", -1));
map.insert("HAPI_AttributeTypeInfo", ("auto", -1));
map.insert("HAPI_StorageType", ("auto", -1));
map.insert("HAPI_VolumeVisualType", ("auto", -1));
map.insert("HAPI_VolumeType", ("auto", -1));
map.insert("HAPI_CurveType", ("auto", -1));
map.insert("HAPI_AttributeOwner", ("auto", -1));
map.insert("HAPI_GroupType", ("auto", -1));
map.insert("HAPI_PresetType", ("auto", -1));
map.insert("HAPI_ChoiceListType", ("auto", -1));
map.insert("HAPI_InputCurveMethod", ("auto", -1));
map.insert("HAPI_InputCurveParameterization", ("auto", -1));
map
});
#[derive(Debug)]
struct Rustifier {
visited: RefCell<HashMap<String, Vec<String>>>,
}
impl ParseCallbacks for Rustifier {
fn enum_variant_name(
&self,
_enum_name: Option<&str>,
_variant_name: &str,
_variant_value: EnumVariantValue,
) -> Option<String> {
if _enum_name.is_none() {
return None;
};
let name = _enum_name
.unwrap()
.strip_prefix("enum ")
.expect("Not enum?");
self.visited
.borrow_mut()
.entry(name.to_string())
.and_modify(|variants| variants.push(_variant_name.to_string()))
.or_default();
let (_, _mode) = ENUMS.get(name).expect(&format!("Missing enum: {}", name));
let mode = StripMode::new(*_mode);
let mut striped = mode.strip_long_name(_variant_name);
// Two stripped variant names can collide with each other. We take a dumb approach by
// attempting to strip one more time with increased step
if let Some(vars) = self.visited.borrow_mut().get_mut(name) {
let _stripped = striped.to_string();
if vars.contains(&_stripped) {
let mode = StripMode::new(*_mode - 1);
striped = mode.strip_long_name(_variant_name);
} else {
vars.push(_stripped);
}
}
Some(heck::AsUpperCamelCase(striped).to_string())
}
fn item_name(&self, _item_name: &str) -> Option<String> {
if let Some((rename, _)) = ENUMS.get(_item_name) {
let new_name = match *rename {
"auto" => _item_name
.strip_prefix("HAPI_")
.expect(&format!("{} - not a HAPI enum?", rename)),
n => n,
};
return Some(new_name.to_string());
}
None
}
}
fn main() {
let hfs = PathBuf::from(&var("HFS").expect("HFS variable is not set"));
let include_dir = hfs.join("toolkit/include/HAPI");
println!("cargo:rerun-if-changed=build.rs");
if cfg!(target_os = "macos") {
let lib_dir = hfs.parent().unwrap().join("Libraries");
println!(
"cargo:rustc-link-search=native={}",
lib_dir.to_string_lossy()
);
println!("cargo:rustc-link-lib=dylib=HAPIL");
} else if cfg!(target_os = "windows") {
let lib_dir = hfs.join("custom/houdini/dsolib");
println!(
"cargo:rustc-link-search=native={}",
lib_dir.to_string_lossy()
);
println!("cargo:rustc-link-lib=dylib=libHAPIL");
} else {
println!("cargo:rustc-link-lib=dylib=HAPIL");
println!(
"cargo:rustc-link-search=native={}/dsolib",
hfs.to_string_lossy()
);
}
let out_path = PathBuf::from(var("OUT_DIR").unwrap()).join("bindings.rs");
let builder = bindgen::Builder::default()
.header("wrapper.h")
.clang_arg(format!("-I{}", include_dir.to_string_lossy()))
.detect_include_paths(true)
.default_enum_style("rust_non_exhaustive".parse().unwrap())
.bitfield_enum("NodeType")
.bitfield_enum("NodeFlags")
.bitfield_enum("ErrorCode")
.prepend_enum_name(false)
.generate_comments(false)
.derive_copy(true)
.derive_debug(true)
.derive_hash(false)
.derive_eq(false)
.derive_partialeq(false)
.disable_name_namespacing()
.rustfmt_bindings(true)
.layout_tests(false)
.raw_line(format!(
"// Houdini version {}",
hfs.file_name().unwrap().to_string_lossy()
))
.raw_line(format!(
"// hapi-sys version {}",
var("CARGO_PKG_VERSION").unwrap()
));
let builder = if cfg!(feature = "rustify") {
let callbacks = Box::new(Rustifier {
visited: Default::default(),
});
builder.parse_callbacks(callbacks)
} else {
builder
};
builder
.generate()
.expect("bindgen failed")
.write_to_file(out_path.clone())
.expect("Could not write bindings to file");
let link = out_path
.parent()
.unwrap()
.parent()
.unwrap()
.parent()
.unwrap()
.join("bindings.rs");
if let Err(e) = std::fs::hard_link(&out_path, &link) {
if e.kind() != std::io::ErrorKind::AlreadyExists {
panic!("Could not create link: {}", &link.to_string_lossy());
}
}
println!("cargo:warning=Output: {}", &link.to_string_lossy());
}