Skip to main content

sb3_decoder/model/code/
blocks.rs

1use crate::{macros::string_id, model::sprite::RotationStyle, prelude::*};
2
3/// The representation of a Scratch script with maybe one hat block and many action blocks.
4#[derive(Debug, Clone)]
5#[non_exhaustive]
6pub struct Script {
7    pub hat: Option<Hat>,
8    pub actions: Vec<Action>,
9}
10
11/// The representation of a Scratch hat block.
12#[derive(Debug, Clone)]
13#[non_exhaustive]
14pub enum Hat {
15    // Events
16    WhenFlagClicked,
17    WhenKeyPressed { key: KeyField },
18    WhenThisSpriteClicked,
19    WhenStageClicked,
20    WhenBackdropSwitchesTo { backdrop: String },
21
22    WhenGreaterThan { loudness_timer: LoudnessTimerField, val: Reporter },
23
24    WhenIReceive { broadcast: code::BroadcastId },
25
26    // Control
27    WhenIStartAsAClone,
28
29    // Procedures
30    DefineProcedure { prototype: ProcPrototype },
31}
32
33/// The representation of a Scratch action block.
34#[derive(Debug, Clone)]
35#[non_exhaustive]
36pub enum Action {
37    // Motion
38    MoveSteps { steps: Reporter },
39    TurnRight { deg: Reporter },
40    TurnLeft { deg: Reporter },
41
42    GoTo { loc: Reporter },
43    GoToXY { x: Reporter, y: Reporter },
44    GlideSecsTo { secs: Reporter, loc: Reporter },
45    GlideSecsToXY { secs: Reporter, x: Reporter, y: Reporter },
46
47    PointInDirection { dir: Reporter },
48    PointTowards { loc: Reporter },
49
50    ChangeXBy { inc: Reporter },
51    SetXTo { x: Reporter },
52    ChangeYBy { inc: Reporter },
53    SetYTo { y: Reporter },
54
55    IfOnEdgeBounce,
56
57    SetRotationStyle { style: RotationStyle },
58
59    // Looks
60    SayForSeconds { content: Reporter, secs: Reporter },
61    Say { content: Reporter },
62    ThinkForSeconds { content: Reporter, secs: Reporter },
63    Think { content: Reporter },
64
65    SwitchCostumeTo { costume: Reporter },
66    NextCostume,
67    SwitchBackdropTo { backdrop: Reporter },
68    SwitchBackdropToAndWait { backdrop: Reporter },
69    NextBackdrop,
70
71    ChangeSizeBy { inc: Reporter },
72    SetSizeTo { size: Reporter },
73
74    ChangeGraphicEffectBy { effect: GraphicEffectField, inc: Reporter },
75    SetGraphicEffectTo { effect: GraphicEffectField, val: Reporter },
76    ClearGraphicEffects,
77
78    Show,
79    Hide,
80
81    GoToLayer { front_back: FrontBackField },
82    GoLayers { forward_backward: ForwardBackwardField, num: Reporter },
83
84    // Sound
85    PlaySoundUntilDone { sound: Reporter },
86    PlaySound { sound: Reporter },
87    StopAllSounds,
88
89    ChangeSoundEffectBy { effect: SoundEffectField, inc: Reporter },
90    SetSoundEffectTo { effect: SoundEffectField, val: Reporter },
91    ClearSoundEffects,
92
93    ChangeVolumeBy { inc: Reporter },
94    SetVolumeTo { volume: Reporter },
95
96    // Events
97    Broadcast { broadcast: Reporter },
98    BroadcastAndWait { broadcast: Reporter },
99
100    // Control
101    WaitSecs { secs: Reporter },
102
103    Repeat { times: Reporter, body: Vec<Action> },
104    Forever { body: Vec<Action> },
105
106    If { cond: Reporter, then: Vec<Action> },
107    IfElse { cond: Reporter, then: Vec<Action>, otherwise: Vec<Action> },
108    WaitUntil { cond: Reporter },
109    RepeatUntil { cond: Reporter, body: Vec<Action> },
110    While { cond: Reporter, body: Vec<Action> },
111
112    Stop { stop: StopField },
113
114    CreateCloneOf { menu: Reporter },
115    DeleteThisClone,
116
117    // Sensing
118    AskAndWait { content: Reporter },
119
120    SetDragMode { draggable: bool },
121
122    ResetTimer,
123
124    // Data
125    SetVariableTo { var: code::VarId, val: Reporter },
126    ChangeVariableBy { var: code::VarId, inc: Reporter },
127    ShowVariable { var: code::VarId },
128    HideVariable { var: code::VarId },
129
130    AddToList { list: code::ListId, val: Reporter },
131
132    DeleteOfList { list: code::ListId, index: Reporter },
133    DeleteAllOfList { list: code::ListId },
134    InsertAtOfList { list: code::ListId, val: Reporter, index: Reporter },
135    ReplaceItemOfListWith { list: code::ListId, index: Reporter, val: Reporter },
136
137    ShowList { list: code::ListId },
138    HideList { list: code::ListId },
139
140    // Procedures
141    CallProcedure { proccode: String, args: Vec<Reporter> },
142
143    // Unknown
144    Unknown(UnknownBlock),
145}
146
147/// The representation of a Scratch reporter block.
148#[derive(Debug, Clone)]
149#[non_exhaustive]
150pub enum Reporter {
151    // Primitives and Empty
152    Number { num: f64 },                        // 4
153    PosNumber { num: f64 },                     // 5
154    PosInteger { num: u64 },                    // 6
155    Integer { num: i64 },                       // 7
156    Angle { num: f64 },                         // 8
157    Color { r: u8, g: u8, b: u8 },              // 9
158    Text { text: String },                      // 10
159    Broadcast { broadcast: code::BroadcastId }, // 11
160    Variable { var: code::VarId },              // 12
161    List { list: code::ListId },                // 13
162    Empty,
163
164    // Motion
165    LocationMenu { menu: LocationMenu },
166
167    XPosition,
168    YPosition,
169    Direction,
170
171    // Looks
172    CostumeMenu { costume: String },
173    BackdropMenu { backdrop: String },
174
175    CurrentCostume { number_name: NumberNameField },
176    CurrentBackdrop { number_name: NumberNameField },
177    Size,
178
179    // Sound
180    SoundMenu { sound: String },
181
182    Volume,
183
184    // Control
185    CloneOfMenu { menu: CloneOfMenu },
186
187    // Sensing
188    KeyMenu { menu: KeyField },
189    TouchingObjectMenu { menu: TouchingObjectMenu },
190    DistanceToMenu { menu: DistanceToMenu },
191    OfObjectMenu { menu: OfObjectMenu },
192
193    TouchingObject { object: Box<Reporter> },
194    TouchingColor { color: Box<Reporter> },
195    ColorTouchingColor { a: Box<Reporter>, b: Box<Reporter> },
196    DistanceToObject { object: Box<Reporter> },
197
198    Answer,
199    KeyPressed { key: Box<Reporter> },
200    MouseDown,
201    MouseX,
202    MouseY,
203
204    Loudness,
205    Timer,
206
207    PropertyOfObject { property: PropertyField, object: Box<Reporter> },
208
209    Current { current: CurrentField },
210    DaysSince2000,
211
212    Username,
213
214    // Operators
215    Add { a: Box<Reporter>, b: Box<Reporter> },
216    Sub { a: Box<Reporter>, b: Box<Reporter> },
217    Mul { a: Box<Reporter>, b: Box<Reporter> },
218    Div { a: Box<Reporter>, b: Box<Reporter> },
219
220    PickRandom { min: Box<Reporter>, max: Box<Reporter> },
221
222    Gt { a: Box<Reporter>, b: Box<Reporter> },
223    Lt { a: Box<Reporter>, b: Box<Reporter> },
224    Eq { a: Box<Reporter>, b: Box<Reporter> },
225
226    And { a: Box<Reporter>, b: Box<Reporter> },
227    Or { a: Box<Reporter>, b: Box<Reporter> },
228    Not { x: Box<Reporter> },
229
230    Join { a: Box<Reporter>, b: Box<Reporter> },
231    LetterOf { index: Box<Reporter>, text: Box<Reporter> },
232    LengthOfText { text: Box<Reporter> },
233
234    TextContains { haystack: Box<Reporter>, needle: Box<Reporter> },
235
236    Mod { a: Box<Reporter>, b: Box<Reporter> },
237    Round { x: Box<Reporter> },
238
239    MathFunc { func: MathFuncField, x: Box<Reporter> },
240
241    // Data
242    ItemOfList { list: code::ListId, index: Box<Reporter> },
243    ItemNumOfItemInList { list: code::ListId, val: Box<Reporter> },
244    LengthOfList { list: code::ListId },
245    ListContains { haystack: code::ListId, needle: Box<Reporter> },
246
247    // Procedures
248    Argument { name: String },
249
250    // Unknown
251    Unknown(UnknownBlock),
252}
253
254#[derive(Debug, Clone)]
255#[non_exhaustive]
256pub struct ProcPrototype {
257    pub proccode: String,
258    pub params: Vec<Param>,
259    pub warp: bool,
260}
261
262#[derive(Debug, Clone)]
263#[non_exhaustive]
264pub struct Param {
265    pub id: ArgId,
266    pub name: String,
267    pub kind: ParamKind,
268    pub default: code::Value,
269}
270
271string_id! {
272    /// The ID of a procedure parameter.
273    ArgId
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum ParamKind {
278    StringNumber,
279    Boolean,
280}
281
282/// A block this crate doesn't understand, kept in a lowered but uninterpreted form. If you think
283/// this block should be added, create an issue on the repository. If you don't want to allow
284/// unknown blocks, use [`Decoder::allow_unknown_blocks`].
285#[derive(Debug, Clone)]
286#[non_exhaustive]
287pub struct UnknownBlock {
288    pub opcode: String,
289    pub inputs: Vec<(String, UnknownInput)>,
290    pub fields: Vec<(String, UnknownField)>,
291}
292
293#[derive(Debug, Clone)]
294#[non_exhaustive]
295pub enum UnknownInput {
296    /// A literal or reference, already lowered.
297    Reporter(Reporter),
298    /// A C-block substack.
299    Stack(Vec<Action>),
300}
301
302#[derive(Debug, Clone)]
303#[non_exhaustive]
304pub struct UnknownField {
305    pub value: String,
306    pub id: Option<String>,
307}
308
309/// The location menu used by some motion blocks.
310///
311/// Specifically:
312/// - `go to (menu)`
313/// - `glide (secs) secs to (menu)`
314/// - `point towards (menu)`
315#[derive(Debug, Clone, PartialEq, Eq, Hash)]
316#[non_exhaustive]
317pub enum LocationMenu {
318    Random,
319    MousePointer,
320    Sprite(String),
321}
322
323/// The effect field used by some looks blocks.
324///
325/// Specifically:
326/// - `change [graphic effect] effect by (inc)`
327/// - `set [graphic effect] effect to (value)`
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
329pub enum GraphicEffectField {
330    Color,
331    Fisheye,
332    Whirl,
333    Pixelate,
334    Mosaic,
335    Brightness,
336    Ghost,
337}
338
339/// The front-back field used by `go to [front-back] layer`.
340#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
341pub enum FrontBackField {
342    Front,
343    Back,
344}
345
346/// The forward-backward field used by `go [forward-backward] (num) layers`.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
348pub enum ForwardBackwardField {
349    Forward,
350    Backward,
351}
352
353/// The number-name field used by some looks blocks.
354///
355/// Specifically:
356/// - `(costume [number-name])`
357/// - `(backdrop [number-name])`
358#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
359pub enum NumberNameField {
360    Number,
361    Name,
362}
363
364/// The effect field used by some sound blocks.
365///
366/// Specifically:
367/// - `change [sound effect] effect by (inc)`
368/// - `set [sound effect] effect to (value)`
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
370#[non_exhaustive]
371pub enum SoundEffectField {
372    Pitch,
373    PanLeftRight,
374}
375
376/// The key field used by `when [key] key pressed`. Additionally, [`Reporter::KeyMenu`] also uses
377/// this enum.
378#[derive(Debug, Clone, PartialEq, Eq, Hash)]
379#[non_exhaustive]
380pub enum KeyField {
381    Space,
382    UpArrow,
383    DownArrow,
384    LeftArrow,
385    RightArrow,
386    Any,
387    Letter(char),
388    Digit(u8),
389    Other(String),
390}
391
392/// The loudness-timer field used by `when [loudness-timer] > (val)`.
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
394#[non_exhaustive]
395pub enum LoudnessTimerField {
396    Loudness,
397    Timer,
398}
399
400/// The stop field used by `stop [stop]`.
401#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
402pub enum StopField {
403    All,
404    ThisScript,
405    OtherScriptsInSprite,
406}
407
408/// The object menu used by `<touching (menu)?>`.
409#[derive(Debug, Clone, PartialEq, Eq, Hash)]
410#[non_exhaustive]
411pub enum TouchingObjectMenu {
412    MousePointer,
413    Edge,
414    Sprite(String),
415}
416
417/// The object menu used by `(distance to (menu))`.
418#[derive(Debug, Clone, PartialEq, Eq, Hash)]
419#[non_exhaustive]
420pub enum DistanceToMenu {
421    MousePointer,
422    Sprite(String),
423}
424
425/// The object menu used by `([property] of (object))`.
426#[derive(Debug, Clone, PartialEq, Eq, Hash)]
427#[non_exhaustive]
428pub enum OfObjectMenu {
429    Stage,
430    Sprite(String),
431}
432
433/// The property field used by `([property] of (object))`.
434///
435/// Not every property is meaningful for every object (for example,
436/// `BackdropNumber` only applies to the stage); Scratch itself does not enforce this.
437#[derive(Debug, Clone, PartialEq, Eq, Hash)]
438#[non_exhaustive]
439pub enum PropertyField {
440    // Sprite properties
441    XPosition,
442    YPosition,
443    Direction,
444    CostumeNumber,
445    CostumeName,
446    Size,
447
448    // Stage properties
449    BackdropNumber,
450    BackdropName,
451
452    // Both
453    Volume,
454
455    /// Any other string is a variable name on the target.
456    Variable(String),
457}
458
459/// The current field used by `(current [current])`.
460#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
461pub enum CurrentField {
462    Year,
463    Month,
464    Date,
465    DayOfWeek,
466    Hour,
467    Minute,
468    Second,
469}
470
471/// The clone of menu used by `create clone of [menu]`.
472#[derive(Debug, Clone, PartialEq, Eq, Hash)]
473pub enum CloneOfMenu {
474    Myself,
475    Sprite(String),
476}
477
478/// The math function field used by `([math-func] of (x))`
479#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
480pub enum MathFuncField {
481    Abs,
482    Floor,
483    Ceiling,
484    Sqrt,
485    Sin,
486    Cos,
487    Tan,
488    Asin,
489    Acos,
490    Atan,
491    Ln,
492    Log,
493    EToPower,
494    TenToPower,
495}