multilinear 0.6.0

Interactive story simulation using constrained parallel aspects
Documentation
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
#![deny(missing_docs)]

//! A library for representing and simulating interactive stories using a multilinear system.

use bit_set::BitSet;
use derive_more::{From, Into};
use event_simulation::{BorrowedSimulation, MultiSimulation, OwnedSimulation, SimulationInfo};
use indexmap::{IndexMap, IndexSet};
use thiserror::Error;

use std::{convert::Infallible, fmt::Display};

mod edit;
mod streams;

pub use edit::EditMultilinearInfo;

/// Represents an event in the multilinear system.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Into, From)]
pub struct Event(pub usize);

impl Display for Event {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "E{}", self.0)
    }
}

/// Represents an aspect in the multilinear system.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Into, From)]
pub struct Aspect(pub usize);

impl Display for Aspect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "C{}", self.0)
    }
}

/// Represents a value transition of a change.
#[derive(Copy, Clone)]
pub struct Transition {
    /// The precondition.
    pub from: usize,
    /// The postcondition.
    pub to: usize,
}

trait TransitionGetter {
    type Opposite: TransitionGetter;

    fn get(transition: &Transition) -> usize;
}

struct From;
impl TransitionGetter for From {
    type Opposite = To;

    #[inline]
    fn get(transition: &Transition) -> usize {
        transition.from
    }
}

struct To;
impl TransitionGetter for To {
    type Opposite = From;

    #[inline]
    fn get(transition: &Transition) -> usize {
        transition.to
    }
}

impl Transition {
    #[inline]
    fn value(value: usize) -> Self {
        Self {
            from: value,
            to: value,
        }
    }

    #[inline]
    fn new(from: usize, to: usize) -> Self {
        Self { from, to }
    }

    #[inline]
    fn get<T: TransitionGetter>(&self) -> usize {
        T::get(self)
    }

    /// Checks if the transition actually changes anything.
    pub fn is_change(&self) -> bool {
        self.from != self.to
    }
}

/// Represents a change for an event in the multilinear system.
#[derive(Copy, Clone)]
pub struct Change {
    aspect: Aspect,
    transition: Transition,
}

impl Change {
    /// Creates a new condition change of the specified `aspect` with `value`.
    pub fn condition(aspect: Aspect, value: usize) -> Self {
        Self {
            aspect,
            transition: Transition::value(value),
        }
    }

    /// Creates a new transition change of the specified `aspect` changing the value from `from` to `to`.
    pub fn transition(aspect: Aspect, from: usize, to: usize) -> Self {
        Self {
            aspect,
            transition: Transition::new(from, to),
        }
    }
}

#[derive(Clone)]
struct AspectNode {
    dependent_events: IndexSet<Event>,
    changed_events: BitSet,
}

/// Represents an event.
///
/// Stores multiple changes. One of them has to be fulfilled to be true.
#[derive(Clone)]
pub struct EventNode {
    changes: Vec<IndexMap<Aspect, Transition>>,
    changed_events: BitSet,
}

impl EventNode {
    /// Returns an iterator over the aspect and transition for each of its changes.
    pub fn iter(&self) -> impl Iterator<Item = impl Iterator<Item = (Aspect, Transition)>> {
        self.changes.iter().map(|change| {
            change
                .iter()
                .map(|(&aspect, &transition)| (aspect, transition))
        })
    }
}

impl EventNode {
    #[inline]
    fn action_index<T: TransitionGetter>(&self, state: &[usize]) -> Option<usize> {
        fn check<T: TransitionGetter>(
            change: &IndexMap<Aspect, Transition>,
            state: &[usize],
        ) -> bool {
            for (&aspect, &transition) in change {
                if transition.get::<T>() != state[aspect.0] {
                    return false;
                }
            }

            true
        }

        for (i, change) in self.changes.iter().enumerate() {
            if check::<T>(change, state) {
                return Some(i);
            }
        }

        None
    }

    fn check_action<T: TransitionGetter>(&self, state: &[usize]) -> bool {
        self.action_index::<T>(state).is_some()
    }

    unsafe fn invoke_action<T: TransitionGetter>(&self, state: &mut [usize]) {
        let index = unsafe { self.action_index::<T>(state).unwrap_unchecked() };

        for (&aspect, &transition) in &self.changes[index] {
            state[aspect.0] = transition.get::<T::Opposite>();
        }
    }
}

/// Represents the information for a multilinear system.
#[derive(Default, Clone)]
pub struct MultilinearInfo {
    events: Vec<EventNode>,
    aspects: Vec<AspectNode>,
}

impl MultilinearInfo {
    /// Returns an iterator over the events and the event nodes containing the changes.
    pub fn iter(&self) -> impl Iterator<Item = (Event, &EventNode)> {
        self.events
            .iter()
            .enumerate()
            .map(|(i, event_node)| (Event(i), event_node))
    }
}

#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct AspectValue {
    aspect: Aspect,
    value: usize,
}

#[derive(Clone)]
struct ChangeSet {
    from: IndexSet<AspectValue>,
    to: IndexSet<AspectValue>,
}

impl ChangeSet {
    fn create(&mut self, map: &IndexMap<Aspect, Transition>) -> Self {
        let mut from = IndexSet::new();
        let mut to = IndexSet::new();

        for (&aspect, &transition) in map {
            let from_value = AspectValue {
                aspect,
                value: transition.from,
            };
            if !self.from.swap_remove(&from_value) {
                from.insert(from_value);
            }

            let to_value = AspectValue {
                aspect,
                value: transition.to,
            };
            if !self.to.swap_remove(&to_value) {
                to.insert(to_value);
            }
        }

        Self { from, to }
    }
}

/// Represents an error when adding an invalid change to an event.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Error)]
pub enum InvalidChangeError {
    /// Indicates that an aspect is being changed more than once in the same set of changes.
    #[error("Only one change per aspect is allowed for each event")]
    DuplicateAspect,
    /// Indicates that the sets of changes being added are conflicting because the unique part doesn't have a shared aspect.
    #[error("Conflicting changes might cause ambiguous behavior")]
    ConflictingChanges,
}

/// Represents information for adding changes to an event in a multilinear system.
pub struct EventEdit<'a> {
    index: usize,
    info: &'a mut MultilinearInfo,
}

impl EventEdit<'_> {
    /// Returns the event identifier, consuming the object.
    pub fn event(self) -> Event {
        Event(self.index)
    }

    /// Adds a change to the event.
    pub fn add_change(&mut self, changes: &[Change]) -> Result<(), InvalidChangeError> {
        let mut from = IndexSet::new();
        let mut to = IndexSet::new();
        let mut map = IndexMap::new();

        for &Change { aspect, transition } in changes {
            if map.insert(aspect, transition).is_some() {
                return Err(InvalidChangeError::DuplicateAspect);
            }
            from.insert(AspectValue {
                aspect,
                value: transition.from,
            });
            to.insert(AspectValue {
                aspect,
                value: transition.to,
            });
        }

        let new_changes = ChangeSet { from, to };

        let node = unsafe { self.info.events.get_unchecked(self.index) };

        for change in &node.changes {
            let mut new_changes = new_changes.clone();
            let changes = new_changes.create(change);

            if !changes.from.iter().any(|changed_value| {
                new_changes
                    .from
                    .iter()
                    .any(|new_value| changed_value.aspect == new_value.aspect)
            }) || !changes.to.iter().any(|changed_value| {
                new_changes
                    .to
                    .iter()
                    .any(|new_value| changed_value.aspect == new_value.aspect)
            }) {
                return Err(InvalidChangeError::ConflictingChanges);
            }
        }

        for &aspect in map.keys() {
            let aspect = &mut self.info.aspects[aspect.0];
            aspect.changed_events.insert(self.index);

            for &modify_event in &aspect.dependent_events {
                self.info.events[modify_event.0]
                    .changed_events
                    .insert(self.index);
            }
        }

        let node = unsafe { self.info.events.get_unchecked_mut(self.index) };

        for (&aspect, transition) in &map {
            let aspect = &mut self.info.aspects[aspect.0];
            if transition.is_change() {
                aspect.dependent_events.insert(Event(self.index));
            }
            node.changed_events.union_with(&aspect.changed_events);
        }

        node.changes.push(map);

        Ok(())
    }

    /// Creates a new instance of `EventInfo` with the given change.
    pub fn with_change(mut self, changes: &[Change]) -> Result<Self, InvalidChangeError> {
        self.add_change(changes)?;
        Ok(self)
    }
}

impl MultilinearInfo {
    /// Creates a new instance of `MultilinearInfo`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a new aspect to the multilinear system.
    pub fn add_aspect(&mut self) -> Aspect {
        let index = self.aspects.len();
        self.aspects.push(AspectNode {
            dependent_events: IndexSet::new(),
            changed_events: BitSet::new(),
        });
        Aspect(index)
    }

    /// Adds a new event to the multilinear system and returns an editalbe event info.
    pub fn add_event(&mut self) -> EventEdit<'_> {
        let index = self.events.len();

        self.events.push(EventNode {
            changes: Vec::new(),
            changed_events: BitSet::new(),
        });

        EventEdit { index, info: self }
    }

    /// Returns an editalbe event info if the event exists.
    #[inline]
    pub fn edit_event(&mut self, Event(index): Event) -> Option<EventEdit<'_>> {
        if index > self.events.len() {
            return None;
        }

        Some(unsafe { self.edit_event_unchecked(Event(index)) })
    }

    /// Returns an editalbe event info.
    ///
    /// # Safety
    ///
    /// Ensure that this event exists
    pub unsafe fn edit_event_unchecked(&mut self, Event(index): Event) -> EventEdit<'_> {
        EventEdit { index, info: self }
    }
}

/// Represents the state of a multilinear system.
#[derive(Clone)]
pub struct MultilinearState {
    values: Vec<usize>,
    callables: BitSet,
    revertables: BitSet,
}

impl MultilinearState {
    fn from_values(info: &MultilinearInfo, values: Vec<usize>) -> Self {
        let mut callables = BitSet::new();
        let mut revertables = BitSet::new();

        for (index, event) in info.events.iter().enumerate() {
            if event.check_action::<From>(&values) {
                callables.insert(index);
            }
            if event.check_action::<To>(&values) {
                revertables.insert(index);
            }
        }

        Self {
            values,
            callables,
            revertables,
        }
    }

    fn update_events(&mut self, event: &EventNode, info: &MultilinearInfo) {
        for event in &event.changed_events {
            let event_node = &info.events[event];
            if event_node.check_action::<From>(&self.values) {
                self.callables.insert(event);
            } else {
                self.callables.remove(event);
            }
            if event_node.check_action::<To>(&self.values) {
                self.revertables.insert(event);
            } else {
                self.revertables.remove(event);
            }
        }
    }
}

/// An iterator over the events of the callable or revertable events.
pub struct EventContainer<'a> {
    iter: bit_set::Iter<'a, u32>,
}

impl Iterator for EventContainer<'_> {
    type Item = Event;

    fn next(&mut self) -> Option<Event> {
        self.iter.next().map(Event)
    }
}

impl SimulationInfo for MultilinearInfo {
    type StateLoadingError = Infallible;
    type State = MultilinearState;
    type AccessData = [usize];
    type LoadData = Vec<usize>;
    type Event = Event;
    type EventContainer<'a>
        = EventContainer<'a>
    where
        Self: 'a;

    #[inline]
    fn default_state(&self) -> MultilinearState {
        MultilinearState::from_values(self, vec![0; self.aspects.len()])
    }

    #[inline]
    fn load_state(&self, data: Vec<usize>) -> Result<MultilinearState, Infallible> {
        Ok(MultilinearState::from_values(self, data))
    }

    #[inline]
    unsafe fn clone_state(&self, state: &MultilinearState) -> MultilinearState {
        state.clone()
    }

    #[inline]
    unsafe fn data<'a>(&self, state: &'a MultilinearState) -> &'a [usize] {
        &state.values
    }

    #[inline]
    fn callables(state: &MultilinearState) -> EventContainer<'_> {
        EventContainer {
            iter: state.callables.iter(),
        }
    }

    #[inline]
    fn callable(state: &MultilinearState, event: Event) -> bool {
        state.callables.contains(event.0)
    }

    unsafe fn call(&self, state: &mut MultilinearState, event: Event) {
        let event = &self.events[event.0];
        unsafe { event.invoke_action::<From>(&mut state.values) };
        state.update_events(event, self);
    }

    #[inline]
    fn revertables(state: &MultilinearState) -> EventContainer<'_> {
        EventContainer {
            iter: state.revertables.iter(),
        }
    }

    #[inline]
    fn revertable(state: &MultilinearState, event: Event) -> bool {
        state.revertables.contains(event.0)
    }

    unsafe fn revert(&self, state: &mut MultilinearState, event: Event) {
        let event = &self.events[event.0];
        unsafe { event.invoke_action::<To>(&mut state.values) };
        state.update_events(event, self);
    }
}

/// Represents an owned simulation for the multilinear system.
pub type MultilinearSimulation = OwnedSimulation<MultilinearInfo>;

/// Represents a borrowed simulation for the multilinear system.
pub type BorrowedMultilinearSimulation<'a> = BorrowedSimulation<'a, MultilinearInfo>;

/// Represents a multi simulation for the multilinear system.
pub type MultiMultilinearSimulation = MultiSimulation<MultilinearInfo>;