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
|
use std::collections::HashMap;
use specs::{Builder, EntityBuilder};
use serde_json::Value;
use crate::components::{Visible, Blocking, Played};
use crate::pos::Pos;
use crate::hashmap;
#[derive(Clone)]
pub enum CompWrapper{
Visible(Visible),
Blocking(Blocking),
Player(Played)
}
impl CompWrapper {
pub fn build<'a>(&self, builder: specs::EntityBuilder<'a>) -> specs::EntityBuilder<'a> {
match self.clone() {
Self::Visible(c) => builder.with(c),
Self::Blocking(c) => builder.with(c),
Self::Player(c) => builder.with(c)
}
}
// pub fn parse_component(data: Value) -> Option<CompWrapper> {
// let a = data.as_array()?;
// if a.len() != 2 {
// return None
// }
// let typename = a[0].as_str()?;
// let params: HashMap<&str, &Parameter> = a[1].as_object()?.into_iter().map(|(key, val)| (key.as_str(), val)).collect();
// Self::load_component(typename, params)
// }
pub fn load_component(comptype: ComponentType, mut parameters: HashMap<&str, &Parameter>) -> Option<CompWrapper> {
match comptype {
ComponentType::Visible => Some(CompWrapper::Visible(Visible{
sprite: parameters.remove("sprite")?.as_str()?.to_string(),
height: parameters.remove("height")?.as_f64()?
})),
ComponentType::Blocking => Some(CompWrapper::Blocking(Blocking)),
ComponentType::Player => Some(CompWrapper::Player(Played::new(
parameters.remove("name")?.as_str()?.to_string()
)))
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ComponentType {
Visible,
Blocking,
Player
}
impl ComponentType {
pub fn from_str(typename: &str) -> Option<ComponentType>{
match typename {
"Visible" => Some(ComponentType::Visible),
"Blocking" => Some(ComponentType::Blocking),
"Player" => Some(ComponentType::Player),
_ => None
}
}
pub fn parameters(&self) -> HashMap<&str, ParamType> {
match self {
ComponentType::Visible => hashmap!("sprite" => ParamType::String, "height" => ParamType::Float),
ComponentType::Blocking => HashMap::new(),
ComponentType::Player => hashmap!("name" => ParamType::String)
}
}
}
#[derive(Debug, PartialEq)]
pub enum Parameter {
String(String),
Int(i64),
// Pos(Pos),
Float(f64)
}
impl Parameter {
pub fn from_typed_json(typ: ParamType, val: &Value) -> Option<Parameter>{
match typ {
ParamType::String => Some(Parameter::String(val.as_str()?.to_string())),
ParamType::Int => Some(Parameter::Int(val.as_i64()?)),
ParamType::Float => Some(Parameter::Float(val.as_f64()?))
}
}
pub fn paramtype(&self) -> ParamType {
match self {
Parameter::String(_) => ParamType::String,
Parameter::Int(_) => ParamType::Int,
Parameter::Float(_) => ParamType::Float
}
}
pub fn from_json(val: &Value) -> Option<Parameter> {
Parameter::from_typed_json(ParamType::from_str(val.get(0)?.as_str()?)?, val.get(1)?)
}
pub fn as_str(&self) -> Option<&str> {
if let Parameter::String(str) = self {
Some(str)
} else {
None
}
}
pub fn as_string(&self) -> Option<String> {
Some(self.as_str()?.to_string())
}
pub fn as_i64(&self) -> Option<i64> {
if let Parameter::Int(num) = self {
Some(*num)
} else {
None
}
}
pub fn as_f64(&self) -> Option<f64> {
if let Parameter::Float(num) = self {
Some(*num)
} else {
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParamType {
String,
// Pos,
Int,
Float
}
impl ParamType {
pub fn from_str(typename: &str) -> Option<ParamType>{
match typename {
"string" => Some(ParamType::String),
"int" => Some(ParamType::Int),
"float" => Some(ParamType::Float),
_ => None
}
}
}
#[derive(Debug, PartialEq)]
pub struct Template {
pub arguments: Vec<(String, ParamType, Option<Parameter>)>,
pub components: Vec<(ComponentType, HashMap<String, CompParam>)>
}
impl Template {
pub fn from_json(val: Value) -> Result<Template, &'static str>{
let mut arguments: Vec<(String, ParamType, Option<Parameter>)> = Vec::new();
for arg in val.get("arguments").ok_or("property 'arguments' not found")?.as_array().ok_or("arguments is not an array")? {
let tup = arg.as_array().ok_or("argument is not an array")?;
let key = tup.get(0).ok_or("argument has no name")?.as_str().ok_or("argument name is not a string")?.to_string();
let typ = ParamType::from_str(tup.get(1).ok_or("argument has no type")?.as_str().ok_or("argument type not a string")?).ok_or("failed to parse argument type")?;
let def = tup.get(2).ok_or("argument has no default")?;
if def.is_null() {
arguments.push((key.clone(), typ, None));
} else {
arguments.push((key.clone(), typ, Some(Parameter::from_typed_json(typ, def).ok_or("invalid argument default")?)));
}
}
let mut components = Vec::new();
for tup in val.get("components").ok_or("property 'arguments' not found")?.as_array().ok_or("arguments is not a json object")? {
let comptype = ComponentType::from_str(tup
.get(0).ok_or("index 0 not in component")?
.as_str().ok_or("component name not a string")?
).ok_or("not a valid componenttype")?;
let mut parameters: HashMap<String, CompParam> = HashMap::new();
for (key, value) in tup.get(1).ok_or("index 1 not in component")?.as_object().ok_or("component parameters not a json object")? {
let paramtype: ParamType = comptype.parameters().remove(key.as_str()).ok_or("unknown parameter name")?;
let paramvalue = value.get(1).ok_or("index 0 not in component parameter")?;
let param = match value.get(0).ok_or("index 0 not in component parameter")?.as_str().ok_or("compparam type not a string")? {
"C" => Ok(CompParam::Constant(
Parameter::from_typed_json(paramtype, paramvalue).ok_or("failed to parse parameter constant")?
)),
"A" => {
let argname = paramvalue.as_str().ok_or("argument parameter not a string")?.to_string();
let arg = arguments.iter().find(|(a, t, d)| a == &argname).ok_or("unknown argument name")?;
if arg.1 == paramtype {
Ok(CompParam::Argument(argname))
} else {
Err("wrong argument type")
}
},
_ => Err("unknown compparam type")
};
parameters.insert(key.clone(), param?);
}
components.push((comptype, parameters));
}
Ok(Template {
arguments,
components
})
}
pub fn instantiate(&self, args: Vec<Parameter>, kwargs: HashMap<String, Parameter>) -> Result<Vec<CompWrapper>, &str>{
let mut components: Vec<CompWrapper> = Vec::new();
for (comptype, compparams) in &self.components {
let mut compargs: HashMap<&str, &Parameter> = HashMap::new();
for (name, param) in compparams {
match param {
CompParam::Constant(val) => {compargs.insert(name.as_str(), &val); Ok(())},
CompParam::Argument(argname) => {
if let Some(argval) = kwargs.get(argname.as_str()) {
compargs.insert(name.as_str(), argval);
Ok(())
} else if let Some(idx) = self.arguments.iter().position(|(x, t, d)| x == name){
if idx < args.len() {
compargs.insert(name.as_str(), &args[idx]);
Ok(())
} else {
Err("positional argument out of range")
}
} else {
Err("can't find parameter value")
}
}
}?;
}
components.push(CompWrapper::load_component(*comptype, compargs).ok_or("failed to load component")?);
}
Ok(components)
}
}
#[derive(Debug, PartialEq)]
pub enum CompParam {
Constant(Parameter),
Argument(String)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use std::collections::HashMap;
#[test]
fn empty_template_from_json() {
assert_eq!(
Template::from_json(json!({
"arguments": [],
"components": []
})).unwrap(),
Template{
arguments: vec![],
components: vec![]
}
);
}
#[test]
fn grass_from_json(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "string", "grass1"]
],
"components": [
["Visible", {
"sprite": ["A", "sprite"],
"height": ["C", 0.1]
}]
]
})).unwrap();
let constructed = Template{
arguments: vec![("sprite".to_string(), ParamType::String, Some(Parameter::String("grass1".to_string())))],
components: vec![
(ComponentType::Visible, hashmap!(
"sprite".to_string() => CompParam::Argument("sprite".to_string()),
"height".to_string() => CompParam::Constant(Parameter::Float(0.1))
))
]
};
assert_eq!(result, constructed);
}
#[test]
fn invalid_component_name(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "string", null]
],
"components": [
["visible", { // no capital so invalid
"sprite": ["A", "sprite"],
"height": ["C", 0.1]
}]
]
})).unwrap_err();
assert_eq!(result, "not a valid componenttype");
}
#[test]
fn invalid_parameter_type(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "string", "grass1"]
],
"components": [
["Visible", {
"sprite": ["A", "sprite"],
"height": ["C", "0.1"]
}]
]
})).unwrap_err();
assert_eq!(result, "failed to parse parameter constant");
}
#[test]
fn unknown_argument_name(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "string", "grass1"]
],
"components": [
["Visible", {
"sprite": ["A", "sprits"],
"height": ["C", 0.1]
}]
]
})).unwrap_err();
assert_eq!(result, "unknown argument name");
}
#[test]
fn wrong_argument_type(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "int", 1]
],
"components": [
["Visible", {
"sprite": ["A", "sprite"],
"height": ["C", 0.1]
}]
]
})).unwrap_err();
assert_eq!(result, "wrong argument type");
}
#[test]
fn wrong_argument_default(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "string", 1]
],
"components": [
["Visible", {
"sprite": ["A", "sprits"],
"height": ["C", 0.1]
}]
]
})).unwrap_err();
assert_eq!(result, "invalid argument default");
}
#[test]
fn null_argument(){
let result = Template::from_json(json!({
"arguments": [
["sprite", "string", null]
],
"components": [
["Visible", {
"sprite": ["A", "sprite"],
"height": ["C", 0.1]
}]
]
})).unwrap();
let constructed = Template{
arguments: vec![("sprite".to_string(), ParamType::String, None)],
components: vec![
(ComponentType::Visible, hashmap!(
"sprite".to_string() => CompParam::Argument("sprite".to_string()),
"height".to_string() => CompParam::Constant(Parameter::Float(0.1))
))
]
};
assert_eq!(result, constructed);
}
}
|