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
use crate::ffi;
use crate::ffi::{
    raw::{PdgEventType, PdgState},
    PDGEventInfo, PDGWorkItemInfo, PDGWorkItemOutputFile,
};
use crate::node::{HoudiniNode, NodeHandle};
use crate::Result;
use std::fmt::Formatter;
use std::ops::ControlFlow;

/// Represents a single work item.
pub struct PDGWorkItem<'node> {
    pub id: WorkItemId,
    pub context_id: i32,
    pub node: &'node HoudiniNode,
}

#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct WorkItemId(pub(crate) i32);

impl std::fmt::Debug for PDGWorkItem<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PDGWorkItem")
            .field("id", &self.id)
            .field("context", &self.context_id)
            .finish()
    }
}

impl From<TopNode> for NodeHandle {
    fn from(value: TopNode) -> Self {
        value.node.handle
    }
}

impl<'session> PDGWorkItem<'session> {
    pub fn get_info(&self) -> Result<PDGWorkItemInfo> {
        ffi::get_workitem_info(&self.node.session, self.context_id, self.id.0)
            .map(|inner| PDGWorkItemInfo { inner })
    }
    /// Retrieve the results of work, if the work item has any.
    pub fn get_results(&self) -> Result<Vec<PDGWorkItemOutputFile<'session>>> {
        match self.get_info()?.output_file_count() {
            0 => Ok(Vec::new()),
            count => {
                let results = ffi::get_workitem_result(
                    &self.node.session,
                    self.node.handle,
                    self.id.0,
                    count,
                )?;
                let results = results
                    .into_iter()
                    .map(|inner| PDGWorkItemOutputFile {
                        inner,
                        session: (&self.node.session).into(),
                    })
                    .collect();

                Ok(results)
            }
        }
    }

    pub fn get_data_length(&self, data_name: &str) -> Result<i32> {
        let data_name = std::ffi::CString::new(data_name)?;
        ffi::get_workitem_data_length(&self.node.session, self.node.handle, self.id.0, &data_name)
    }

    pub fn set_int_data(&self, data_name: &str, data: &[i32]) -> Result<()> {
        let data_name = std::ffi::CString::new(data_name)?;
        ffi::set_workitem_int_data(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &data_name,
            data,
        )
    }

    pub fn get_int_data(&self, data_name: &str) -> Result<Vec<i32>> {
        let data_name = std::ffi::CString::new(data_name)?;
        let data_size = ffi::get_workitem_data_length(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &data_name,
        )?;
        let mut buffer = Vec::new();
        buffer.resize(data_size as usize, 0);
        ffi::get_workitem_int_data(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &data_name,
            buffer.as_mut_slice(),
        )?;
        Ok(buffer)
    }

    pub fn set_float_data(&self, data_name: &str, data: &[f32]) -> Result<()> {
        let data_name = std::ffi::CString::new(data_name)?;
        ffi::set_workitem_float_data(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &data_name,
            data,
        )
    }

    pub fn get_float_data(&self, data_name: &str) -> Result<Vec<f32>> {
        let data_name = std::ffi::CString::new(data_name)?;
        let data_size = ffi::get_workitem_data_length(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &data_name,
        )?;
        let mut buffer = Vec::new();
        buffer.resize(data_size as usize, 0.0);
        ffi::get_workitem_float_data(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &data_name,
            buffer.as_mut_slice(),
        )?;
        Ok(buffer)
    }

    pub fn set_int_attribute(&self, attrib_name: &str, value: &[i32]) -> Result<()> {
        let attrib_name = std::ffi::CString::new(attrib_name)?;
        ffi::set_workitem_int_attribute(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &attrib_name,
            value,
        )
    }
    pub fn get_int_attribute(&self, attr_name: &str) -> Result<Vec<i32>> {
        let attr_name = std::ffi::CString::new(attr_name)?;
        let attr_size = ffi::get_workitem_attribute_size(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &attr_name,
        )?;
        let mut buffer = Vec::new();
        buffer.resize(attr_size as usize, 0);
        ffi::get_workitem_int_attribute(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &attr_name,
            &mut buffer,
        )?;
        Ok(buffer)
    }

    pub fn set_float_attribute(&self, attrib_name: &str, value: &[f32]) -> Result<()> {
        let attrib_name = std::ffi::CString::new(attrib_name)?;
        ffi::set_workitem_float_attribute(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &attrib_name,
            value,
        )
    }

    pub fn get_float_attribute(&self, attr_name: &str) -> Result<Vec<f32>> {
        let attr_name = std::ffi::CString::new(attr_name)?;
        let attr_size = ffi::get_workitem_attribute_size(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &attr_name,
        )?;
        let mut buffer = Vec::new();
        buffer.resize(attr_size as usize, 0.0);
        ffi::get_workitem_float_attribute(
            &self.node.session,
            self.node.handle,
            self.id.0,
            &attr_name,
            &mut buffer,
        )?;
        Ok(buffer)
    }
}

#[derive(Debug, Clone)]
/// A wrapper for [`HoudiniNode`] with methods for cooking PDG.
pub struct TopNode {
    pub node: HoudiniNode,
}

/// A convenient wrapper for a single event generated by PDG.
#[derive(Debug, Copy, Clone)]
pub struct CookStep {
    pub event: PDGEventInfo,
    pub graph_id: i32,
    pub graph_name: i32,
}

// Helper to create a vec of events. No Default impl for it.
fn create_events() -> Vec<ffi::raw::HAPI_PDG_EventInfo> {
    const NUM: usize = 32;
    vec![
        ffi::raw::HAPI_PDG_EventInfo {
            nodeId: -1,
            workItemId: -1,
            dependencyId: -1,
            currentState: -1,
            lastState: -1,
            eventType: -1,
            msgSH: -1,
        };
        NUM
    ]
}

impl TopNode {
    /// Start cooking a TOP node asynchronously.
    /// For each generated event, a user closure will be called with a [`CookStep`] argument.
    ///
    /// The closure returns [`Result<ControlFlow<bool>>`] which is handled like this:
    ///
    /// If its an `Err(_)` - bubble up the error.
    /// If it's [`ControlFlow::Break(bool)`] then the `bool` is either to cancel the cooking
    /// or just break the loop and return.
    /// In case of [`ControlFlow::Continue(_)`] run until completion.
    ///
    /// See the `pdg_cook` example in the `/examples` folder.
    pub fn cook_async<F>(&self, all_outputs: bool, mut func: F) -> Result<()>
    where
        F: FnMut(CookStep) -> Result<ControlFlow<bool>>,
    {
        let session = &self.node.session;
        log::debug!("Start cooking PDG node: {}", self.node.path()?);
        debug_assert!(session.is_valid());
        ffi::cook_pdg(session, self.node.handle, false, false, all_outputs)?;
        let mut events = create_events();
        'main: loop {
            let (graph_ids, graph_names) = ffi::get_pdg_contexts(session)?;
            debug_assert_eq!(graph_ids.len(), graph_names.len());
            for (graph_id, graph_name) in graph_ids.into_iter().zip(graph_names) {
                for event in ffi::get_pdg_events(session, graph_id, &mut events)? {
                    let event = PDGEventInfo { inner: *event };
                    match event.event_type() {
                        PdgEventType::EventCookComplete => break 'main,
                        _ => {
                            match func(CookStep {
                                event,
                                graph_id,
                                graph_name,
                            }) {
                                Err(e) => return Err(e),
                                Ok(ControlFlow::Continue(_)) => {}
                                Ok(ControlFlow::Break(stop_cooking)) => {
                                    if stop_cooking {
                                        // TODO: Should we call this for all graph ids?
                                        ffi::cancel_pdg_cook(session, graph_id)?;
                                    }
                                    break 'main;
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    pub fn cook_pdg_blocking(&self) -> Result<()> {
        ffi::cook_pdg(&self.node.session, self.node.handle, false, true, false)
    }

    // FIXME. Observing some weird behaviour. The output files are intermixed with tags
    #[allow(dead_code)]
    #[allow(unreachable_code)]
    fn cook_blocking_with_results(
        &self,
        _all_outputs: bool,
    ) -> Result<Vec<PDGWorkItemOutputFile<'_>>> {
        unimplemented!();
        ffi::cook_pdg(
            &self.node.session,
            self.node.handle,
            false,
            true,
            _all_outputs,
        )?;
        let workitems: Vec<PDGWorkItem> = {
            let context_id = self.get_context_id()?;
            ffi::get_pdg_workitems(&self.node.session, self.node.handle)?
                .into_iter()
                .map(|workitem_id| {
                    Ok(PDGWorkItem {
                        id: WorkItemId(workitem_id),
                        context_id,
                        node: &self.node,
                    })
                })
                .collect::<Result<Vec<_>>>()?
        };
        let mut all_results = Vec::new();
        for wi in workitems {
            all_results.extend(wi.get_results()?)
        }
        Ok(all_results)
    }

    /// Get the graph(context) id of this node in PDG.
    pub fn get_context_id(&self) -> Result<i32> {
        ffi::get_pdg_context_id(&self.node.session, self.node.handle)
    }

    /// Cancel cooking.
    pub fn cancel_cooking(&self) -> Result<()> {
        log::debug!("Cancel PDG cooking {}", self.node.path()?);
        let context = self.get_context_id()?;
        ffi::cancel_pdg_cook(&self.node.session, context)
    }

    /// Pause cooking process
    pub fn pause_cooking(&self) -> Result<()> {
        log::debug!("Pause PDG cooking {}", self.node.path()?);
        let context = self.get_context_id()?;
        ffi::pause_pdg_cook(&self.node.session, context)
    }

    /// Dirty the node, forcing the work items to regenerate.
    pub fn dirty_node(&self, clean_results: bool) -> Result<()> {
        log::debug!("Set PDG node dirty {}", self.node.path()?);
        ffi::dirty_pdg_node(&self.node.session, self.node.handle, clean_results)
    }

    /// Which this node current [`PdgState`]
    pub fn get_current_state(&self, context_id: Option<i32>) -> Result<PdgState> {
        let context = match context_id {
            Some(c) => c,
            None => self.get_context_id()?,
        };
        ffi::get_pdg_state(&self.node.session, context)
    }

    /// Get the work item by id and graph(context) id.
    pub fn get_workitem(&self, workitem_id: WorkItemId) -> Result<PDGWorkItem<'_>> {
        let context_id = self.get_context_id()?;
        ffi::get_workitem_info(&self.node.session, context_id, workitem_id.0).map(|_| PDGWorkItem {
            id: workitem_id,
            context_id,
            node: &self.node,
        })
    }

    pub fn get_all_workitems(&self) -> Result<Vec<PDGWorkItem<'_>>> {
        let context_id = self.get_context_id()?;
        ffi::get_pdg_workitems(&self.node.session, self.node.handle).map(|vec| {
            vec.into_iter()
                .map(|id| PDGWorkItem {
                    id: WorkItemId(id),
                    context_id,
                    node: &self.node,
                })
                .collect()
        })
    }

    pub fn create_workitem(
        &self,
        name: &str,
        index: i32,
        context_id: Option<i32>,
    ) -> Result<PDGWorkItem> {
        let name = std::ffi::CString::new(name)?;
        let context_id = match context_id {
            Some(c) => c,
            None => self.get_context_id()?,
        };
        let id = ffi::create_pdg_workitem(&self.node.session, self.node.handle, &name, index)?;
        Ok(PDGWorkItem {
            id: WorkItemId(id),
            context_id,
            node: &self.node,
        })
    }

    pub fn commit_workitems(&self) -> Result<()> {
        ffi::commit_pdg_workitems(&self.node.session, self.node.handle)
    }
}