l6t_symbolic/
value.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
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
use std::collections::HashMap;
use std::default;
use std::fmt::{Display, Formatter};
use file::model::{L6Patch, Model, ModelParam, Value as L6Value};
use crate::model::{DataModel, Param, ParamType, Slot};

#[derive(Clone)]
pub enum Value {
    Bool(bool),
    Int(u32),
    Float(f32),
    String(String)
}

impl Display for Value {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Bool(v) => v.fmt(f),
            Value::Int(v) => v.fmt(f),
            Value::Float(v) => v.fmt(f),
            Value::String(v) => v.fmt(f)
        }
    }
}

impl TryInto<u32> for &Value {
    type Error = String;

    fn try_into(self) -> Result<u32, Self::Error> {
        match self {
            Value::Bool(v) => Ok(if *v { 1 } else { 0 }),
            Value::Int(v) => Ok(*v),
            Value::Float(_) => Err("Value::Float cannot be converted to u32".into()),
            Value::String(_) => Err("Value::String cannot be converted to u32".into())
        }
    }
}

impl TryInto<bool> for &Value {
    type Error = String;

    fn try_into(self) -> Result<bool, Self::Error> {
        match self {
            Value::Bool(v) => Ok(*v),
            Value::Int(_) => Err("Value::Int cannot be converted to bool".into()),
            Value::Float(_) => Err("Value::Float cannot be converted to bool".into()),
            Value::String(_) => Err("Value::String cannot be converted to bool".into())
        }
    }
}

impl Value {
    pub fn to_bits(&self) -> Option<u32> {
        match self {
            Value::Bool(v) => Some(if *v { 1 } else { 0 }),
            Value::Int(v) => Some(*v),
            Value::Float(v) => Some(v.to_bits()),
            Value::String(_) => None
        }
    }
}

pub enum ValueType {
    Bool,
    Int,
    Float,
    String
}

impl Display for ValueType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let t = match self {
            ValueType::Bool => "bool",
            ValueType::Int => "int",
            ValueType::Float => "float",
            ValueType::String => "str"
        };
        t.fmt(f)
    }
}

impl Value {
    pub fn get_type(&self) -> ValueType {
        match self {
            Value::Bool(_) => ValueType::Bool,
            Value::Int(_) => ValueType::Int,
            Value::Float(_) => ValueType::Float,
            Value::String(_) => ValueType::String
        }
    }
}

pub type ValueMap = HashMap<String, Value>;

pub fn read_values(patch: &L6Patch, model: &DataModel) -> (ValueMap, Vec<String>) {
    let mut data: HashMap<String, Value> = HashMap::new();
    let mut processed_models = vec![];
    let mut errors = vec![];

    let slots = model.groups.iter().flat_map(|g| &g.slots);
    for slot in slots {
        let patch_model = patch.models.iter()
            .find(|m| model_matches_slot(m, slot));
        let Some(patch_model) = patch_model else {
            continue;
        };

        let mut missing_params = vec![];
        let mut processed_params = vec![];
        for param in &slot.params {
            let (name, value) = match param {
                Param::SlotModel { name } => {
                    (name, Value::Int(patch_model.model_id))
                },
                Param::SlotEnable { name } => {
                    (name, Value::Bool(patch_model.enabled))
                },
                Param::Param { name, param_id, param_type } => {
                    let patch_param = patch_model.params.iter()
                        .find(|p| p.param_id == *param_id);
                    let Some(patch_param) = patch_param else {
                        missing_params.push(*param_id);
                        continue;
                    };
                    processed_params.push(*param_id);
                    let value = value_from_l6(&patch_param.value, param_type, model.floats_as_ints);
                    (name, value)
                }
                Param::FixedParam { name, param_value, slot_id, .. } => {
                    match slot_id {
                        None => {
                            (name, Value::Int(*param_value))
                        }
                        Some(slot_id) if *slot_id == patch_model.slot_id => {
                            (name, Value::Int(*param_value))
                        }
                        _ => { continue; }
                    }
                }
                Param::IgnoreParam { param_id } => {
                    processed_params.push(*param_id);
                    continue;
                }
            };

            data.insert(name.clone(), value);
        }
        let unprocessed_params = patch_model.params.iter()
            .map(|p| p.param_id)
            .filter(|v| !processed_params.contains(v))
            .collect::<Vec<_>>();

        let model = patch_model; // for error reporting below
        processed_models.push(patch_model);
        if !missing_params.is_empty() {
            errors.push(
                format!("Slot {:#04x} model={:#08x} ordinal={} missing params: {}",
                        model.slot_id, model.model_id, model.ordinal,
                        missing_params.iter().map(|id| format!("{:#x}", id))
                            .collect::<Vec<_>>().join(", ")
                )
            )
        }
        if !unprocessed_params.is_empty() {
            errors.push(
                format!("Slot {:#04x} model={:#08x} ordinal={} unprocessed params: {}",
                        model.slot_id, model.model_id, model.ordinal,
                        unprocessed_params.iter().map(|id| format!("{:#x}", id))
                            .collect::<Vec<_>>().join(", ")
                )
            )
        }
    }

    let unprocessed_models = patch.models.iter().filter(|m| !processed_models.contains(m));
    for model in unprocessed_models {
        errors.push(
            format!("Slot {:#04x} model={:#08x} ordinal={} unprocessed",
                    model.slot_id, model.model_id, model.ordinal
            )
        )
    }

    (data, errors)
}

pub fn write_values(values: ValueMap, model: &DataModel) -> L6Patch {
    let floats_as_ints = model.floats_as_ints;
    let mut models: Vec<Model> = vec![];

    let slots = model.groups.iter().flat_map(|g| &g.slots);
    for slot in slots {
        let fixed_param = slot.params.iter().find(|p| match p {
                    Param::FixedParam { name, param_value, param_type, .. } => {
                        let Some(v) = values.get(name) else {
                            return false;
                        };
                        // TODO: dubious conversion to u32
                        if *param_type != ParamType::Int { todo!() }
                        let Ok(v): Result<u32, _> = v.try_into() else {
                            return false;
                        };

                        v == *param_value
                    }
                    _ => false
                });

        let slot_id = slot.fixed_slot.or(
            fixed_param.and_then(|p| match p {
                Param::FixedParam { slot_id, .. } => slot_id.clone(),
                _ => None
            })
        );
        let model = slot.fixed_model.or_else(|| {
           slot.params.iter().find_map(|p| {
               match p {
                   Param::SlotModel { name } => {
                       let Some(v) = values.get(name) else {
                           return None;
                       };
                       let v: Option<u32> = v.try_into().ok();
                       v
                   }
                   _ => None
               }
           })
        });
        let enable = slot.fixed_enable.or_else(|| {
            slot.params.iter().find_map(|p| {
                match p {
                    Param::SlotEnable { name } => {
                        let Some(v) = values.get(name) else {
                            return None;
                        };
                        let v: Option<bool> = v.try_into().ok();
                        v
                    }
                    _ => None
                }
            })
        });

        let found_by_fixed_int = fixed_param.is_some();
        let have_all = slot_id.is_some() && model.is_some() && enable.is_some();
        let slot_found = found_by_fixed_int || have_all;
        if !slot_found {
            continue;
        }
        if !have_all {
            panic!("Missing slot id, model or enable");
        }

        let mut params = vec![];
        for param in &slot.params {
            match param {
                Param::IgnoreParam { param_id } => {
                    // put a "0" for ignored parameters
                    params.push(
                        ModelParam { param_id: *param_id, value: L6Value::Int(0) }
                    )

                }
                Param::Param { name, param_id, param_type } => {
                    let Some(value) = values.get(name) else {
                        panic!("No value {:?} for param {:#x} for slot {:#x}", name, param_id, slot_id.unwrap());
                    };
                    let value = value_to_l6(value, param_type, floats_as_ints);
                    params.push(
                        ModelParam { param_id: *param_id, value }
                    )
                }
                _ => {}
            }
        }
        models.push(
            Model {
                model_id: model.unwrap(),
                slot_id: slot_id.unwrap(),
                enabled: enable.unwrap(),
                ordinal: 0,
                params,
            }
        );
    }

    L6Patch {
        models,
        ..default::Default::default()
    }
}

fn value_from_l6(value: &L6Value, param_type: &ParamType, floats_as_ints: bool) -> Value {
    match param_type {
        ParamType::Int => {
            match value {
                L6Value::Int(v) => { Value::Int(*v) }
                _ => {
                    panic!("Int value expected")
                }
            }
        }
        ParamType::Float => {
            match value {
                L6Value::Int(v) if floats_as_ints => {
                    Value::Float(f32::from_bits(*v))
                }
                // A special case for Int(0): sometimes L6E writes Int(0) for
                // unused float values, so we do a silent conversion to Float(0)
                L6Value::Int(v) if *v == 0 => {
                    Value::Float(0f32)
                }
                L6Value::Float(v) => {
                    Value::Float(*v)
                }
                _ => {
                    panic!("Float value expected, got {:?}", value)
                }
            }
        }
        ParamType::Bool => {
            match value {
                L6Value::Int(v) if *v == 0 => {
                    Value::Bool(false)
                }
                L6Value::Int(v) if *v == 1 => {
                    Value::Bool(true)
                }
                _ => {
                    panic!("Bool value expected")
                }
            }
        }
    }
}

fn value_to_l6(value: &Value, param_type: &ParamType, floats_as_ints: bool) -> L6Value {
    match param_type {
        ParamType::Int => {
            match value {
                Value::Int(v) => { L6Value::Int(*v) }
                _ => {
                    panic!("Int value expected")
                }
            }
        }
        ParamType::Float => {
            match value {
                Value::Float(v) if floats_as_ints => {
                    L6Value::Int(v.to_bits())
                }
                Value::Float(v) => {
                    L6Value::Float(*v)
                }
                _ => {
                    panic!("Float value expected")
                }
            }
        }
        ParamType::Bool => {
            match value {
                Value::Bool(v) if !v => {
                    L6Value::Int(0)
                }
                Value::Bool(v) if *v => {
                    L6Value::Int(1)
                }
                _ => {
                    panic!("Bool value expected")
                }
            }
        }
    }
}

//

pub struct ValueGroup {
    pub name: String,
    pub values: Vec<(String, Value)>
}

pub fn group_values(patch: &L6Patch, values: &ValueMap, model: &DataModel) -> Vec<ValueGroup> {
    let mut groups: Vec<ValueGroup> = vec![];

    for group in &model.groups {
        let mut group_values = vec![];
        let mut seen_names = vec![];

        for slot in &group.slots {
            let patch_model = patch.models.iter()
                .find(|m| model_matches_slot(m, slot));
            if patch_model.is_none() {
                continue;
            }

            for param in &slot.params {
                let name = match param {
                    Param::SlotModel { name, .. } => name,
                    Param::SlotEnable { name, .. } => name,
                    Param::Param { name, .. } => name,
                    Param::FixedParam { name, .. } => name,
                    Param::IgnoreParam { .. } => { continue }
                };
                if seen_names.contains(name) { continue }
                // We allow values to contain only a portion of props defined in
                // the slot. "read_values" would have reported missing props errors,
                // but the app may have chosen to ignore them.
                if let Some(value) = values.get(name) {
                    group_values.push((name.clone(), value.clone()));
                }
                seen_names.push(name.clone());
            }
        }

        if !group_values.is_empty() {
            let group = ValueGroup {
                name: group.name.clone(),
                values: group_values
            };
            groups.push(group)
        }
    }

    groups
}

fn model_matches_slot(model: &Model, slot: &Slot) -> bool {
    let mut possible_slot_ids = slot.params.iter().flat_map(|p| match p {
        Param::FixedParam { slot_id, .. } => slot_id.clone(),
        _ => None
    });

    let slot_matched = slot.fixed_slot.map(|v| model.slot_id == v)
        .unwrap_or_else(|| possible_slot_ids.find(|v| model.slot_id == *v).is_some());
    let model_matched = slot.fixed_model.map_or(true, |v| model.model_id == v);
    let enable_matched = slot.fixed_enable.map_or(true, |v| model.enabled == v);

    slot_matched && model_matched && enable_matched
}