-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_object.cpp
More file actions
577 lines (410 loc) · 13.2 KB
/
create_object.cpp
File metadata and controls
577 lines (410 loc) · 13.2 KB
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// -*- compile-command: "/usr/bin/g++ -std=c++11 -Wall -g create_object.cpp -o create_object " -*-
#include <vector>
#include <memory>
#include <map>
#include <sstream>
#include <functional>
#include <typeindex>
#include <iostream>
#include <typeinfo>
#include <iterator>
template<class T>
struct traits;
template<class T>
using sptr = std::shared_ptr<T>;
// type-safe attribute map
class attribs {
using items_type = std::map<std::string, std::function< void() > >;
items_type items;
// TODO: possible to throw directly?
template<class T> struct boxed {
const T value;
};
public:
template<class T>
attribs& operator()(const std::string& name, T value) {
items[name] = [value] {
// std::clog << "throwing as " << traits<T>::name() << std::endl;
throw boxed<T>{value};
};
return *this;
}
template<class T>
const T& get(const std::string& name) const {
// std::clog << "catching as " << traits<T>::name() << std::endl;
try {
items.at(name)();
} catch( const boxed<T>& payload ) {
// std::clog << "success" << std::endl;
return payload.value;
} catch( std::out_of_range ) {
throw;
} catch( ... ) {
throw std::bad_cast();
}
throw std::logic_error("should throw");
}
// convenience
template<class T>
attribs(const std::string& name, T value) { operator()(name, value); }
attribs() { }
};
struct node;
struct object;
namespace detail {
static std::string quote(const std::string& value, char q = '"') {
return q + value + q;
}
template<class T>
struct template_name {
static std::string get() { return {}; }
};
template<template<class ...> class T, class ... Args>
struct template_name< T<Args...> > {
static std::string get() {
std::stringstream ss;
// build template string
bool first = true;
(void) std::initializer_list<int> { ((first ? (first = false, ss) : ss << ',')
<< traits<Args>::name(), 0)... };
return ss.str();
}
};
};
// type info
struct info_type {
// constructor function
using ctor_type = std::shared_ptr<object>(*)( const node& ctx );
ctor_type ctor;
// data infos
struct data_type {
virtual ~data_type() { }
const std::string name;
const std::string doc;
data_type(const std::string& name, const std::string& doc)
: name(name), doc(doc) { }
// set data value from attributes
virtual void setup(object* obj, const attribs& attrs) const = 0;
// throw a pointer to value
virtual void get(object* obj) const = 0;
};
// data_name -> data
std::map<std::string, std::shared_ptr<data_type> > data;
// global tables
using table_type = std::map< std::type_index, info_type>;
static table_type table;
// class_name -> template_name -> type_index
using name_type = std::map< std::string, std::map<std::string, std::type_index> >;
static name_type name;
};
// class_name -> template_name -> info
info_type::table_type info_type::table;
info_type::name_type info_type::name;
// register type infos
template<class T, class ... Bases>
class declare : public info_type {
// inheritance
template<class U, typename = typename std::enable_if< std::is_base_of<U, T>::value >::type>
declare& inherit() {
info_type& base = info_type::table.at(typeid(U));
std::copy(base.data.begin(), base.data.end(), std::inserter(this->data, this->data.end()));
return *this;
}
const std::string name;
public:
declare(std::string name) : name(name) {
this->ctor = [](const node& ctx) -> std::shared_ptr<object> {
return std::make_shared<T>(ctx);
};
(void) std::initializer_list<int> { (inherit<Bases>(), 0)... };
}
~declare() {
// register ourselves to the global tables
info_type::name[name].emplace( detail::template_name<T>::get(), typeid(T));
info_type::table.emplace(typeid(T), *this);
}
// data declaration
template<class U, class V = U>
declare& operator()(U (T::*member), std::string name, std::string doc) {
// a typed data info
struct typed_data_type : info_type::data_type {
using member_type = U (T::*);
const member_type member;
typed_data_type(member_type member, const std::string& name, const std::string& doc) :
info_type::data_type(name, doc),
member(member) {
}
void get(object* obj) const {
U* data = &(static_cast<T*>(obj)->*member);
throw data; // TODO do we need rtti?
}
void setup(object* obj, const attribs& attrs) const {
U& data = (static_cast<T*>(obj)->*member);
try {
data = attrs.get<U>(name);
} catch(std::bad_cast) {
// wrong type: try deserialization from string
std::stringstream ss;
try{
ss << attrs.get<std::string>(name);
} catch(std::bad_cast) {
try {
ss << attrs.get<const char*>(name);
} catch(std::bad_cast) {
std::stringstream ss;
ss << "cannot init data " << detail::quote(name)
<< " from attributes (types don't match, deserialization failed)";
// TODO output value
throw std::runtime_error(ss.str());
}
}
data = traits<U>::parse(ss);
} catch(std::out_of_range ) {
// unspecified: keep it default-constructed
}
}
};
// insert data
if( !this->data.emplace(name, std::make_shared<typed_data_type>(member, name, doc) ).second ) {
throw std::logic_error("duplicate data: " + name);
}
return *this;
}
};
// an object may have data
struct object {
virtual ~object() { }
template<class T>
T* data(const std::string& name) {
try{
const info_type& info = info_type::table.at(typeid(*this));
try {
info.data.at(name)->get(this);
} catch(T* ptr) {
return ptr;
} catch( std::out_of_range ) {
throw std::runtime_error("unknown data: " + name);
} catch( ... ) {
throw std::bad_cast();
}
} catch( std::out_of_range ) {
throw std::runtime_error("unknown object type");
}
throw std::logic_error("should throw");
}
};
// scene graph node
struct node {
std::vector< std::shared_ptr<object> > objects;
virtual ~node() { }
std::shared_ptr<object> create(const std::string& class_name, const attribs& attrs);
};
// create object
std::shared_ptr<object> node::create(const std::string& class_name, const attribs& attrs) {
std::string template_name;
{
// fetch template name, if any
static const char* template_key = "template";
try {
template_name = attrs.get<std::string>(template_key);
} catch( std::bad_cast ) {
// retry
template_name = attrs.get<const char*>(template_key);
} catch( std::out_of_range ) {
// no template specified
}
}
try{
const auto& class_table = info_type::name.at(class_name);
try {
const info_type& info = info_type::table.at( class_table.at(template_name) );
// construct object
if( std::shared_ptr<object> res = info.ctor(*this) ) {
// setup object data
for(const auto& d : info.data) { d.second->setup(res.get(), attrs); }
// insert object
objects.emplace_back(res);
return res;
} else {
throw std::logic_error("ctor returned null object");
}
} catch( std::out_of_range ) {
std::stringstream ss;
ss << "unknown template: " << class_name << '<' << template_name << '>';
throw std::runtime_error(ss.str());
}
} catch( std::out_of_range ) {
std::stringstream ss;
ss << "unknown class: " << class_name;
throw std::runtime_error(ss.str());
}
};
// some math types + traits
using real = double;
struct vec3 {
real x, y, z;
friend std::ostream& operator<<(std::ostream& out, const vec3& self) {
return out << self.x << " " << self.y << " " << self.z;
}
};
template<>
struct traits<vec3> {
using scalar = real;
static const std::string name() { return "vec3"; }
static vec3 parse(std::istream& in) {
scalar x, y, z;
in >> x >> y >> z;
return {x, y, z};
}
};
template<>
struct traits<std::size_t> {
static const std::string name() { return "std::size_t"; }
static std::size_t parse(std::istream& in) {
std::size_t res;
in >> res;
return res;
}
};
// a component is an object in the scene graph
struct component : object {
component(const node& ) { }
};
// some component class
template<class T>
struct state : component {
using component::component;
T pos;
std::size_t foo;
static const info_type info;
};
template<class T>
const info_type state<T>::info = declare< state >("state")
(&state::pos, "pos", "position vector")
(&state::foo, "foo", "some data");
template<class T>
struct derived_state : state<T> {
using state<T>::state;
std::size_t bar;
static const info_type info;
};
template<class T>
const info_type derived_state<T>::info = declare< derived_state, state<T> >("derived_state")
(&derived_state::bar, "bar", "some other data");
// dependency graph
struct data_node {
std::shared_ptr<object> obj;
std::string name;
template<class T>
T* get() { return obj->data<T>(name); }
};
struct engine_base {
virtual ~engine_base() { }
virtual std::function< void() > update(data_node out, data_node* first, data_node* last) const = 0;
};
struct engine_node {
std::shared_ptr<engine_base> engine;
std::function< void() > push;
};
// engines
template<class T> struct engine;
template<class Ret, class ... Args>
struct engine< Ret(Args...) > : engine_base {
virtual void apply(Ret& out, const Args&... args) const = 0;
};
// some engine class
template<class T>
struct sum : engine< T(T, T) > {
void apply(T& out, const T& lhs, const T& rhs) const {
out = lhs + rhs;
}
std::function< void() > update(data_node out, data_node* first, data_node* last) const {
const T* lhs_buf = first[0].get<T>();
const T* rhs_buf = first[1].get<T>();
T* out_buf = out.get<T>();
return [lhs_buf, rhs_buf, out_buf, this] {
this->apply(*out_buf, *lhs_buf, *rhs_buf);
};
}
};
#include "graph.hpp"
struct vertex {
void* key;
enum kind_type { data, engine } kind;
vertex(void* key, kind_type kind) : key(key), kind(kind) { }
vertex* first = nullptr;
vertex* next = nullptr;
bool marked;
friend std::ostream& operator<<(std::ostream& out, const vertex& self) {
return out << (self.kind == data ? "data" : "engine") << ": " << self.key;
}
};
namespace graph {
template<class Key>
struct traits< std::map<Key, vertex> > {
using graph_type = std::map<Key, vertex>;
using ref_type = vertex*;
static ref_type& first(const graph_type& g, const ref_type& v) { return v->first; }
static ref_type& next(const graph_type& g, const ref_type& v) { return v->next; }
static bool marked(const graph_type& g, const ref_type& v) { return v->marked; }
static void marked(const graph_type& g, const ref_type& v, bool marked) { v->marked = marked; }
template<class F>
static void iter(graph_type& g, const F& f) { for(auto& it : g) { f(&it.second); } }
};
}
struct data_graph {
using graph_type = std::map<void*, vertex>;
graph_type graph;
// insert engine in dependency graph, given input and output data
void add(engine_base* engine, data_node out, data_node* first, data_node* last) {
using namespace graph;
auto insert = graph.emplace(engine, vertex(engine, vertex::engine));
// TODO setup vertex
if(!insert.second) {
throw std::runtime_error("engine already added");
}
vertex* e = &insert.first->second;
// input edges
for(data_node* it = first; it != last; ++it) {
void* ptr = it->get<void>();
vertex* v = &graph.emplace(ptr, vertex(ptr, vertex::data)).first->second;
graph::connect(graph, e, v);
}
{
// output edge
void* ptr = out.get<void>();
vertex* u = &graph.emplace(ptr, vertex(ptr, vertex::data)).first->second;
graph::connect(graph, u, e);
}
}
};
// template instantiations
template struct state<vec3>;
template struct derived_state<vec3>;
#include <iostream>
int main(int, char**) {
attribs attrs = attribs
("template", "vec3")
("pos", vec3{1, 2, 3} )
("foo", "14");
node root;
auto obj = root.create("derived_state", attrs);
if( auto ptr = std::dynamic_pointer_cast< state<vec3> >(obj) ) {
std::clog << ptr->pos << std::endl;
}
auto* data = obj->data<vec3>("pos");
std::clog << "pos: " << *data << std::endl;
// engine test
auto p1 = root.create("state", attribs("template", "vec3"));
auto p2 = root.create("state", attribs("template", "vec3"));
auto p3 = root.create("state", attribs("template", "vec3"));
engine_base* f = new sum<real>();
data_graph deps;
data_node out = {p1, "pos"};
data_node in[2] = {{p2, "pos"}, {p3, "pos"}};
deps.add(f, out, in, in + 2);
graph::dfs_postfix(deps.graph, [&](vertex* v) {
std::clog << *v << std::endl;
});
return 0;
}