nx_metadata_sdk 1.0 Metadata SDK

random.h
1 // Copyright 2018-present Network Optix, Inc. Licensed under MPL 2.0: www.mozilla.org/MPL/2.0/
2
3 #pragma once
4
5 #include <algorithm>
6 #include <memory>
7 #include <mutex>
8 #include <vector>
9 #include <typeindex>
10
11 #include <nx/vms_server_plugins/analytics/stub/objects/vector2d.h>
12 #include <nx/vms_server_plugins/analytics/stub/objects/abstract_object.h>
13
14 namespace nx {
15 namespace vms_server_plugins {
16 namespace analytics {
17 namespace stub {
18
19 class AbstractObject;
20
21 float randomFloat(float min = 0, float max = 1);
22
23 Vector2D randomTrajectory();
24
25 class RandomObjectGenerator
26 {
27 public:
28 using ObjectFactory = std::function<std::unique_ptr<AbstractObject>()>;
29
30 private:
31 struct ObjectFactoryContext
32 {
33 ObjectFactoryContext(std::type_index key, ObjectFactory factory):
34 key(std::move(key)),
35 factory(std::move(factory))
36 {
37 };
38
39 std::type_index key;
40 ObjectFactory factory;
41 };
42
43 public:
44 template<typename ObjectType>
45 void registerObjectFactory(ObjectFactory objectFactory)
46 {
47 std::lock_guard<std::mutex> lock(m_mutex);
48
49 auto it = std::find_if(
50 m_registry.begin(),
51 m_registry.end(),
52 [](const ObjectFactoryContext& value)
53 {
54 return std::type_index(typeid(ObjectType)) == value.key;
55 });
56
57 if (it == m_registry.cend())
58 m_registry.emplace_back(typeid(ObjectType), objectFactory);
59 else
60 *it = ObjectFactoryContext{std::type_index(typeid(ObjectType)), objectFactory};
61 }
62
63 template<typename ObjectType>
64 void unregisterObjectFactory()
65 {
66 std::lock_guard<std::mutex> lock(m_mutex);
67
68 auto it = std::find_if(
69 m_registry.cbegin(),
70 m_registry.cend(),
71 [](const ObjectFactoryContext& value)
72 {
73 return std::type_index(typeid(ObjectType)) == value.key;
74 });
75
76 if (it == m_registry.cend())
77 return;
78
79 m_registry.erase(it);
80 }
81
82 std::unique_ptr<AbstractObject> generate() const;
83
84 private:
85 mutable std::mutex m_mutex;
86 std::vector<ObjectFactoryContext> m_registry;
87 };
88
89 } // namespace stub
90 } // namespace analytics
91 } // namespace vms_server_plugins
92 } // namespace nx
nx::vms_server_plugins::analytics::stub::RandomObjectGenerator
Definition: random.h:25
nx
Definition: apple_utils.h:6