Skip to content

Commit 46fd471

Browse files
Merge pull request #4 from Unity-Technologies/develop-minor-cleanups
Develop minor cleanups
2 parents 1090e80 + 94bfd98 commit 46fd471

File tree

4 files changed

+65
-137
lines changed

4 files changed

+65
-137
lines changed

Assets/ECSEnvironment.py

Lines changed: 1 addition & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
import struct
33
import numpy as np
44

5+
from python_communication import UnityCommunication
56
from .brain import BrainInfo, BrainParameters
67

7-
88
class ECSEnvironment(object):
99
VEC_SIZE = 8
1010
ACT_SIZE = 3
@@ -90,76 +90,6 @@ def external_brain_names(self):
9090

9191

9292

93-
94-
95-
class UnityCommunication:
96-
FILE_CAPACITY = 200000
97-
NUMBER_AGENTS_POSITION = 0
98-
SENSOR_SIZE_POSITION = 4
99-
ACTUATOR_SIZE_POSITION = 8
100-
UNITY_READY_POSITION = 12
101-
SENSOR_DATA_POSITION = 13
102-
103-
PYTHON_READY_POSITION = 100000
104-
ACTUATOR_DATA_POSITION = 100001
105-
106-
# FILE_NAME = "../../../ml-agents-ecs/Assets/shared_communication_file.txt"
107-
FILE_NAME = "shared_communication_file.txt" # This is relative to where the script is called
108-
109-
def __init__(self):
110-
with open(self.FILE_NAME, "r+b") as f:
111-
# memory-map the file, size 0 means whole file
112-
self.accessor = mmap.mmap(f.fileno(), 0)
113-
114-
def get_int(self, position : int) -> int:
115-
return struct.unpack("i", self.accessor[position:position + 4])[0]
116-
117-
def read_sensor(self) -> np.ndarray:
118-
sensor_size = self.get_int(self.SENSOR_SIZE_POSITION)
119-
number_agents = self.get_int(self.NUMBER_AGENTS_POSITION)
120-
121-
sensor = np.frombuffer(
122-
buffer=self.accessor[self.SENSOR_DATA_POSITION: self.SENSOR_DATA_POSITION + 4*sensor_size*number_agents],
123-
dtype=np.float32,
124-
count=sensor_size * number_agents,
125-
offset=0
126-
)
127-
return np.reshape(sensor, (number_agents, sensor_size))
128-
129-
def get_parameters(self) -> (int, int, int):
130-
return self.get_int(self.NUMBER_AGENTS_POSITION), \
131-
self.get_int(self.SENSOR_SIZE_POSITION), \
132-
self.get_int(self.ACTUATOR_SIZE_POSITION)
133-
134-
def write_actuator(self, actuator: np.ndarray):
135-
actuator_size = self.get_int(self.ACTUATOR_SIZE_POSITION)
136-
number_agents = self.get_int(self.NUMBER_AGENTS_POSITION)
137-
138-
# TODO : Support more types ?
139-
if actuator.dtype != np.float32:
140-
actuator = actuator.astype(np.float32)
141-
142-
try:
143-
assert(actuator.shape == (number_agents, actuator_size))
144-
except:
145-
print("_________")
146-
print(actuator.shape)
147-
print((number_agents, actuator_size))
148-
149-
self.accessor[self.ACTUATOR_DATA_POSITION: self.ACTUATOR_DATA_POSITION + 4*actuator_size*number_agents] = \
150-
actuator.tobytes()
151-
152-
def set_ready(self):
153-
self.accessor[self.UNITY_READY_POSITION: self.UNITY_READY_POSITION+1] = bytearray(struct.pack("b", False))
154-
self.accessor[self.PYTHON_READY_POSITION: self.PYTHON_READY_POSITION+1] = bytearray(struct.pack("b", True))
155-
156-
def unity_ready(self) -> bool:
157-
return self.accessor[self.UNITY_READY_POSITION]
158-
159-
def close(self):
160-
self.accessor.close()
161-
162-
16393
# if __name__ == "__main__":
16494
# comm = UnityCommunication()
16595
#

Assets/ECS_MLAgents_v0/Example/SpaceMagic/Scripts/Manager.cs

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ namespace ECS_MLAgents_v0.Example.SpaceMagic.Scripts
1212
public class SpaceSystemA : AgentSystem<Position, Acceleration>{ }
1313
public class SpaceSystemB : AgentSystem<Position, Acceleration>{ }
1414
public class SpaceSystemC : AgentSystem<Position, Acceleration>{ }
15-
15+
1616
/// <summary>
1717
/// Manager is responsible for instantiation the spheres and the IAgentSystem that will make
1818
/// them move.
@@ -32,20 +32,21 @@ public class SpaceSystemC : AgentSystem<Position, Acceleration>{ }
3232
///
3333
/// N : Give a Heuristic to the third IAgentSystem
3434
/// M : Give a NNModel to the third IAgentSystem
35-
///
35+
///
3636
/// </summary>
3737
public class Manager : MonoBehaviour
3838
{
3939
/// <summary>
40-
/// The distance at which the spheres are instantiated from the center
40+
/// The distance at which the spheres are instantiated from the center
4141
/// </summary>
4242
public float maxDistance;
43+
4344
private EntityManager manager;
4445

4546
private SpaceSystemA sA;
4647
private SpaceSystemB sB;
4748
private SpaceSystemC sC;
48-
49+
4950
/// <summary>
5051
/// The sphere prefab
5152
/// </summary>
@@ -57,34 +58,34 @@ public class Manager : MonoBehaviour
5758
public NNModel modelA;
5859
public NNModel modelB;
5960
public NNModel modelC;
60-
61-
61+
62+
6263
void Start()
6364
{
6465
manager = World.Active.GetOrCreateManager<EntityManager>();
65-
6666

67-
sA= World.Active.GetExistingManager<SpaceSystemA>();
67+
68+
sA= World.Active.GetExistingManager<SpaceSystemA>();
6869
sB= World.Active.GetExistingManager<SpaceSystemB>();
6970
sC= World.Active.GetExistingManager<SpaceSystemC>();
70-
71+
7172
// sA.Enabled = false;
7273
// sB.Enabled = false;
7374
// sC.Enabled = false;
7475

7576
sA.SetNewComponentGroup(typeof(SphereGroup));
7677
sB.SetNewComponentGroup(typeof(SphereGroup));
7778
sC.SetNewComponentGroup(typeof(SphereGroup));
78-
79+
7980
sA.SetFilter<SphereGroup>(new SphereGroup{Group = 0});
8081
sB.SetFilter<SphereGroup>(new SphereGroup{Group = 1});
8182
sC.SetFilter<SphereGroup>(new SphereGroup{Group = 2});
8283

8384
sA.Decision = new NNDecision<Position, Acceleration>(modelA);
8485
sB.Decision = new NNDecision<Position, Acceleration>(modelB);
8586
sC.Decision = new NNDecision<Position, Acceleration>(modelC);
86-
87-
87+
88+
8889
Spawn(1);
8990
}
9091

Assets/ECS_MLAgents_v0/Example/SpaceWars/Scripts/Manager.cs

Lines changed: 47 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,25 @@
1010

1111
namespace ECS_MLAgents_v0.Example.SpaceWars.Scripts
1212
{
13-
14-
public class SmartShipSystem : AgentSystem<ShipSensor, Steering> {}
15-
public class PlayerShipSystem : AgentSystem<ShipSensor, Steering> {}
13+
14+
public class SmartShipSystem : AgentSystem<ShipSensor, Steering> { }
15+
public class PlayerShipSystem : AgentSystem<ShipSensor, Steering> { }
1616

1717

1818
public class Manager : MonoBehaviour
1919
{
20-
21-
2220
public float TargetAngle;
2321
public GameObject target;
2422
public GameObject Camera;
2523

24+
public enum DecisionSelector { NeuralNetwork, ExternalDecision };
25+
public DecisionSelector shipDecisionSelector;
26+
public DecisionSelector playerDecisionSelector;
27+
2628
private EntityManager manager;
2729
public GameObject prefab;
28-
29-
30+
31+
3032
private SmartShipSystem _shipSystemA;
3133
private PlayerShipSystem _playerSystem;
3234

@@ -39,43 +41,36 @@ public class Manager : MonoBehaviour
3941

4042
void Start()
4143
{
42-
43-
44-
45-
46-
47-
48-
49-
50-
51-
52-
53-
54-
55-
5644
Time.captureFramerate = 60;
5745
QualitySettings.vSyncCount = 0;
5846
Application.targetFrameRate = -1;
59-
60-
61-
6247
manager = World.Active.GetOrCreateManager<EntityManager>();
63-
6448
_sensorSystem = World.Active.GetOrCreateManager<SensorPopulate>();
6549
_impactSystem = World.Active.GetOrCreateManager<ImpactSystem>();
6650
_impactSystem.Radius = 20;
6751

6852
_shipSystemA = World.Active.GetExistingManager<SmartShipSystem>();
69-
// _shipSystemA.Decision = new NNDecision<ShipSensor, Steering>(model);
70-
_shipSystemA.Decision =new NNDecision<ShipSensor, Steering>(model);
71-
// _shipSystemA.Decision = new ExternalDecision();
53+
if (shipDecisionSelector == DecisionSelector.ExternalDecision)
54+
{
55+
_shipSystemA.Decision = new ExternalDecision<ShipSensor, Steering>();
56+
}
57+
else
58+
{
59+
_shipSystemA.Decision = new NNDecision<ShipSensor, Steering>(model);
60+
}
7261
_playerSystem = World.Active.GetExistingManager<PlayerShipSystem>();
73-
// _playerSystem.Decision = new NNDecision<ShipSensor, Steering>(model);
74-
_playerSystem.Decision = new HumanDecision<ShipSensor>();
62+
if (playerDecisionSelector == DecisionSelector.ExternalDecision)
63+
{
64+
_playerSystem.Decision = new HumanDecision<ShipSensor>();
65+
}
66+
else
67+
{
68+
_playerSystem.Decision = new NNDecision<ShipSensor, Steering>(model);
69+
}
7570
_playerSystem.SetNewComponentGroup(typeof(PlayerFlag));
7671
_shipSystemA.DecisionRequester = new FixedTimeRequester(0.1f);
7772

78-
_playerEntity = manager.Instantiate(prefab);
73+
_playerEntity = manager.Instantiate(prefab);
7974
MakeSpaceShip(_playerEntity);
8075
manager.AddComponentData(_playerEntity, new PlayerFlag());
8176
manager.SetComponentData(_playerEntity, new Ship
@@ -85,36 +80,37 @@ void Start()
8580
MaxReloadTime = 1f
8681
});
8782

88-
83+
8984
Spawn(10);
90-
91-
// Debug.Log(typeof(ShipSensor).GetCustomAttributes(typeof(SerializableAttribute), true)[0]);
92-
AttributeUtility.GetSensorMetaData(typeof(ShipSensor));
85+
86+
// Debug.Log(typeof(ShipSensor).GetCustomAttributes(typeof(SerializableAttribute), true)[0]);
87+
AttributeUtility.GetSensorMetaData(typeof(ShipSensor));
9388
}
9489

9590

96-
void FixedUpdate(){
91+
void FixedUpdate()
92+
{
9793
// World.Active.GetOrCreateManager<SimulationSystemGroup>();
9894
}
9995

10096
void Update()
10197
{
10298

103-
99+
104100

105101
// for (var i = 0; i < 10; i++){
106102
// foreach(var behavior in World.Active.BehaviourManagers)
107103
// {
108104
// behavior.Update();
109105
// }
110106
// }
111-
// Debug.Log(Application.targetFrameRate);
107+
// Debug.Log(Application.targetFrameRate);
112108
float3 targetPos = 100 * new float3(math.cos(TargetAngle), 0, math.sin(TargetAngle));
113109
_sensorSystem.Center = targetPos;
114110
_impactSystem.Center = targetPos;
115111
target.transform.position = targetPos;
116112

117-
TargetAngle += Time.deltaTime/ 20f;
113+
TargetAngle += Time.deltaTime / 20f;
118114
if (Input.GetKeyDown(KeyCode.A))
119115
{
120116
Spawn(1);
@@ -133,8 +129,8 @@ void Update()
133129
var camPosition = manager.GetComponentData<Position>(_playerEntity).Value;
134130
var camRotation = manager.GetComponentData<Rotation>(_playerEntity).Value;
135131
camPosition += math.mul(camRotation, new float3(0, 0, 5));
136-
Camera.transform.position = Vector3.Lerp(Camera.transform.position,camPosition,0.1f);
137-
Camera.transform.rotation = Quaternion.Lerp(Camera.transform.rotation,camRotation,0.1f);
132+
Camera.transform.position = Vector3.Lerp(Camera.transform.position, camPosition, 0.1f);
133+
Camera.transform.rotation = Quaternion.Lerp(Camera.transform.rotation, camRotation, 0.1f);
138134

139135
}
140136

@@ -146,18 +142,19 @@ void Spawn(int amount)
146142
for (int i = 0; i < amount; i++)
147143
{
148144
MakeSpaceShip(entities[i]);
149-
145+
150146
}
151147
entities.Dispose();
152148
}
153-
154-
private void MakeSpaceShip(Entity ent){
149+
150+
private void MakeSpaceShip(Entity ent)
151+
{
155152
float valX = Random.Range(-1f, 1f);
156153
float valY = Random.Range(-1f, 1f);
157154
float valZ = Random.Range(-1f, 1f);
158155
float valD = Random.Range(0f, 1f);
159-
160-
156+
157+
161158

162159
float3 SpawnOffset = valD *
163160
Globals.SPAWN_DISTANCE *
@@ -167,15 +164,15 @@ private void MakeSpaceShip(Entity ent){
167164
manager.SetComponentData(ent,
168165
new Position
169166
{
170-
Value = SpawnOffset
167+
Value = SpawnOffset
171168
});
172169
manager.SetComponentData(ent,
173170
new Rotation
174171
{
175172
Value = quaternion.EulerXYZ(
176173
math.normalize(new float3(
177-
Random.Range(-1f, 1f),
178-
Random.Range(-1f, 1f),
174+
Random.Range(-1f, 1f),
175+
Random.Range(-1f, 1f),
179176
Random.Range(-1f, 1f)))
180177
)
181178
});
@@ -198,7 +195,7 @@ private void MakeSpaceShip(Entity ent){
198195
}
199196

200197
}
201-
198+
202199

203200
}
204201

0 commit comments

Comments
 (0)