LoadEnv.cs 17.1 KB
Newer Older
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
/* Crowd Simulator Engine
** Copyright (C) 2018 - Inria Rennes - Rainbow - Julien Pettre
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**
** Authors: Julien Bruneau, Fabrice Atrévi
**
** Contact: crowd_group@inria.fr
*/

using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;

/// <summary>
/// Main manager: Load the scene, create all the agents and manage users input
/// </summary>
public class LoadEnv : MonoBehaviour
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
32
33
{

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#region attributes
    List<GameObject> avatars;                               // List of agents
    public GameObject cam;                                  // Scene camera
    private CamRecorder cam_Rec;                            // Control scene recording
    private CamMvt cam_Movement;                            // Control camera movement behavior
    private FiltersControl cam_fc;                          // Control camera filters
    private MenuManager menuM;								// Control the starting menu
    //private float rotSpeed = 5;                             

    // --------------------------
    // CAMERA MOVEMENT PARAMETERS
    const float camTranslationSpeed = 25.0f;                // Camera translation speed
    const float camShiftPower = 250.0f;                     // Shift effect on camera speed
    const float camMaxShiftPower = 1000.0f;                 // Maximun shift effect on camera speed
    const float camRotationSpeed = 0.25f;                   // Rotation speed
    Vector3 lastMouse = new Vector3(255, 255, 255);         // Last mouse position to check its movement
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
50
    float camShiftHold = 1.0f;                              // Control the effect of shift with holding time      
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#endregion


    /// <summary>
    /// Scene and agents initialization
    /// </summary>
    void Start()
    {
        avatars = new List<GameObject>();
        cam_Rec = cam.GetComponent<CamRecorder>();
        cam_Movement = cam.GetComponent<CamMvt>();
        cam_fc = cam.GetComponent<FiltersControl>();

        cam_Rec.enabled = false;
        cam_Movement.enabled = false;

        menuM = gameObject.GetComponent<MenuManager>();
        menuM.CheckCommandLine(); // The Command Line Checker works when it's called here not in MenuManager Start()
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
69
70
71
72
73
    }

    /// <summary>
    /// Load a scenario: create stage and spawn agents
    /// </summary>
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    /// <param name="trajDir">The path to the scenario file</param>
    public void loadScenario(string trajDir)
    {
        // --------------------------------------------------
        // SET RANDOM SEED TO HAVE SAME RESULTS AT EVERY RUNS
        Random.InitState(75482);

        // ---------------------------------
        // INITIALIZE SCENE FROM CONFIG FILE

        // -------------
        // CAMERA CONFIG
        cam_Rec.enabled = true;
        cam_Movement.enabled = true;
JOVANE Alberto's avatar
JOVANE Alberto committed
88
        cam_Movement._camera_type = (CamMvt.CameraType)ConfigReader.camType;
89
90
91
92
93
94
        cam.transform.position = ConfigReader.camPosition;
        cam.transform.rotation = Quaternion.Euler(ConfigReader.camRotation);
        cam_Movement.lookAt_Id = ConfigReader.camLookAtTarget;
        cam_Movement.follow_Id = ConfigReader.camFollowTarget;
        cam_Movement.follow_LockX = !ConfigReader.camFollowOnX;
        cam_Movement.follow_LockZ = !ConfigReader.camFollowOnY;
95
96
97
        cam_Movement.lockFirstPersonView = ConfigReader.camLockFirstPerson;


98
99
100
101
102
103
104
105
        // -------------
        // RECORD CONFIG
        cam_Rec.record = ConfigReader.recording;
        cam_Rec.timeToStart = ConfigReader.recordingStart;
        cam_Rec.timeToStop = ConfigReader.recordingEnd;
        cam_Rec.framerate = ConfigReader.recordingFramerate;
        cam_fc.init();

106
        //FB don't know why there this check
BRUNEAU Julien's avatar
BRUNEAU Julien committed
107
        //JB to see if it is a relative path or full one
108
109
        //FA don't work on my computer. Got trouble to save images. I change little bit to make it works. Have to check on windows
        if (ConfigReader.recordingSaveDir[0] == '.')
110
111
            cam_Rec.saveDir = Directory.GetCurrentDirectory().Replace("\\", "/") + "/" + ConfigReader.recordingSaveDir;
        else
112
113
114
115
116
117
118
119
120
121
            cam_Rec.saveDir = ConfigReader.recordingSaveDir;
        Camera.main.GetComponent<CamRecorder>().Init();
        InitDeepRecorders();

        // ---------------------
        // CLEAR PREVIOUS AGENTS
        foreach (GameObject a in avatars)
        {
            Destroy(a);
        }
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
122
123
124
125
        avatars.Clear();

        // -------------
        // CREATE AGENTS
126
127
128
129
130
131
132
133
134
135
136
        DirectoryInfo dir = new DirectoryInfo(trajDir);
        FileInfo[] info = dir.GetFiles("*.csv");
        if (info.Length == 0)
            info = dir.GetFiles("*.txt");

        var crowdParentObject = new GameObject("Crowd");
        FollowTrajectory tmpFollower;
        int i = 0;
        object testRocketMan = Resources.Load("Prefabs/RocketBox/male/prefab_light/LS_m001_light");
        foreach (FileInfo f in info)
        {
137
138
139
140
            // ------------------------------------------------------------
            // IF NO ROCKETMAN (PROPRIETARY ASSETS), USE PLASTICMAN INSTEAD
            GameObject character = (testRocketMan!=null) ? CreateAgent_RocketBox(i) : CreateAgent_PlasticMan(i);
            character.transform.parent = crowdParentObject.transform;
141
142
            avatars.Add(character);

143
144
            // ---------------------
            // SET NAME, TAG, AND ID
145
            character.name = i.ToString("D4");
146
            character.tag = "Player";
147
148
149
150
151
152
153
154
            character.GetComponent<GetMemberPosition>().ID = i;

            // ----------------------------------
            // FOLLOWTRAJECTORY SCRIPT MANAGEMENT
            // Setup of the CSV filename and disable the start synchro
            tmpFollower = character.GetComponent<FollowTrajectory>();
            tmpFollower.SetCsvFilename(f.FullName);
            tmpFollower._SyncLaunchWithTrajectory = true; // start the character at the csv time
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
155

156
157
158

            // -------------------------------
            // Load animation controller from ressources
159
160
161
162
            //string PathAnimeController = "PlasticMan/Animation/LocomotionFinal";
            //Animator Anime = character.GetComponent<Animator>();
            //Anime.runtimeAnimatorController = Resources.Load(PathAnimeController) as RuntimeAnimatorController;
            //Anime.applyRootMotion = false;
163
164
165
            // make sure that object on the floor (height 0)
            character.transform.position = new Vector3(character.transform.position.x, 0.0f, character.transform.position.z);

166
            i++;
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
167
168
        }

JOVANE Alberto's avatar
JOVANE Alberto committed
169
        cam_Movement.initializeTargetObjects();
170
171
172
173
174
175
176
177
        cam_fc.OnSceneChange();

    }

    /// <summary>
    /// Manage which deep recorder is used and initialize it
    /// </summary>
    private void InitDeepRecorders()
178
    {
179
        GameObject DeepRecorders = GameObject.FindGameObjectWithTag("DeepRecorders");
180
        if (ConfigReader.bboxeBody.record)
181
182
        {
            DeepRecorders.AddComponent<BodyBoundingBoxRecorder>();
183
            DeepRecorders.GetComponent<BodyBoundingBoxRecorder>().Init(ConfigReader.recordingSaveDir);
184
        }
185

186
        if (ConfigReader.bboxeHead.record)
187
188
        {
            DeepRecorders.AddComponent<HeadBoundingBoxRecorder>();
189
            DeepRecorders.GetComponent<HeadBoundingBoxRecorder>().Init(ConfigReader.recordingSaveDir);
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
    }

    Color? GetColorForAgentId(int id)
    {
        if (ConfigReader.agentsColor != null && ConfigReader.agentsColor.Count > 0)
        {
            foreach (ConfigAgentColor c in ConfigReader.agentsColor)
            {
                if (id > c.firstAgent - 1 && id < c.lastAgent + 1 && (id - c.firstAgent) % c.step == 0)
                    return new Color(c.red, c.green, c.blue, 1);
            }
        }
        return null;
    }

    Material CreateMaterialWithColor(Color color)
    {
        var tmpMaterial = new Material(Shader.Find("Legacy Shaders/Diffuse"));
        tmpMaterial.color = color;
        return tmpMaterial;
    }

    string GetModelName_RocketBox(int id)
    {
        string path;
        int modelId;
        if (id % 2 == 0)
        {
219
            path = "male/prefab_light/LS_m";
220
221
222
223
            modelId = id / 2;
        }
        else
        {
224
            path = "female/prefab_light/LS_f";
225
226
227
            modelId = (id - 1) / 2;
        }
        modelId = (modelId % 20) + 1;
228
        return "Prefabs/RocketBox/" + path + modelId.ToString("D3") + "_light";
229
230
231
232
233
234
    }

    GameObject CreateAgent_RocketBox(int id)
    {
        // -------------------
        // LOAD AGENT IN UNITY
235
        GameObject rb = Instantiate(Resources.Load<GameObject>(GetModelName_RocketBox(id)));
236
237
238

        // -------------------
        // SET BOUNDING BOXES ITEM
239
        rb.AddComponent<GetMemberPositionRocketBox>();
240
        //gameObject.AddComponent<FollowTrajectory>();
241
        GameObject headBoundingBox = Instantiate(Resources.Load<GameObject>("HeadBoundingBoxes/Hbb_RocketBox"));
242
        Transform Head = rb.transform.Find("Bip01/Bip01 Pelvis/Bip01 Spine/Bip01 Spine1/Bip01 Spine2/Bip01 Neck/Bip01 Head");
243
        headBoundingBox.transform.parent = Head;
244
245
246
247
248
249
250
251
252

        // ---------------------------------------------
        // SET AGENT'S COLOR WHEN SPECIFY IN CONFIG FILE
        var tmpColor = GetColorForAgentId(id);
        if (tmpColor.HasValue)
        {
            var tmpMaterial = CreateMaterialWithColor(tmpColor.Value);
            Material[] mats = new Material[] { tmpMaterial, tmpMaterial, tmpMaterial };

253
            SkinnedMeshRenderer[] rendererList = rb.GetComponentsInChildren<SkinnedMeshRenderer>();
254
255
256
257
            foreach (SkinnedMeshRenderer renderer in rendererList)
                renderer.materials = mats;
        }

258
        return rb;
259
260
261
262
263
264
265
    }

    GameObject CreateAgent_PlasticMan(int id)
    {
        // -------------------
        // LOAD AGENT IN UNITY
        GameObject gameObject = Instantiate(Resources.Load<GameObject>("PlasticMan/plasticman"));
266
267
268

        // -------------------
        // SET BOUNDING BOXES ITEM
269
        gameObject.AddComponent<GetMemberPositionPlasticMan>();
270
        GameObject headBoundingBox = Instantiate(Resources.Load<GameObject>("HeadBoundingBoxes/Hbb_PlasticMan"));
271
272
        Transform Head = gameObject.transform.Find("Plasticman:Reference/Plasticman:Hips/Plasticman:Spine/Plasticman:Spine1/Plasticman:Spine2/Plasticman:Spine3/Plasticman:Neck/Plasticman:Head");
        headBoundingBox.transform.parent = Head;
273
274
275
276
277
278
279
280
281
282
283
284
285

        // -----------------
        // SET AGENT'S COLOR
        var tmpColor = GetColorForAgentId(id);
        if (!tmpColor.HasValue)
            tmpColor = new Color(Random.value, Random.value, Random.value, 1);

        var tmpRenderer = gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
        tmpRenderer.material = CreateMaterialWithColor(tmpColor.Value);

        return gameObject;
    }

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
    /// <summary>
    /// Update camera state
    /// </summary>
    private void Update()
    {
        ConfigReader.camPosition = cam.transform.position;
        ConfigReader.camRotation = cam.transform.rotation.eulerAngles;
    }

    /// <summary>
    /// Manage users Input
    /// </summary>
    void LateUpdate()
    {
        // -------------------
        // ESCAPE => EXIT APPS
        if (Input.GetKeyDown(KeyCode.Escape) == true)
        {
            menuM.toogleMenu();
        }

        // -------------------------------
        // MOUSE + RCLICK => ROTATE CAMERA
        if (Input.GetMouseButton(1))
        {
            lastMouse = Input.mousePosition - lastMouse;
            lastMouse = new Vector3(-lastMouse.y * camRotationSpeed, lastMouse.x * camRotationSpeed, 0);
            lastMouse = new Vector3(cam.transform.eulerAngles.x + lastMouse.x, cam.transform.eulerAngles.y + lastMouse.y, 0);

            // Block all the way up or down to prevent glitches
            if (lastMouse.x > 180 && lastMouse.x < 270)
                lastMouse.x = 270;
            else if (lastMouse.x > 90 && lastMouse.x < 180)
                lastMouse.x = 90;

            cam.transform.eulerAngles = lastMouse;
        }
        lastMouse = Input.mousePosition;

        // -----------------------------------------
        // ARROWS, SHIFT, CTRL => CAMERA TRANSLATION
        Vector3 p = new Vector3();
        if (Input.GetKey(KeyCode.UpArrow))
        {
            p += new Vector3(0, 0, 1);
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            p += new Vector3(0, 0, -1);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            p += new Vector3(-1, 0, 0);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            p += new Vector3(1, 0, 0);
        }
        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
        {
            camShiftHold += Time.fixedUnscaledDeltaTime;
            p = p * Mathf.Max(camShiftHold * camShiftPower, camMaxShiftPower);
        }
        else
        {
            camShiftHold = Mathf.Clamp(camShiftHold * 0.5f, 1f, 1000f);
            p = p * camTranslationSpeed;
        }

        p = p * Time.fixedUnscaledDeltaTime;
        Vector3 newPosition = cam.transform.position;
        if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
        { //If player wants to move on X and Z axis only
            cam.transform.Translate(p);
            newPosition.x = cam.transform.position.x;
            newPosition.z = cam.transform.position.z;
            cam.transform.position = newPosition;
        }
        else
        {
            cam.transform.Translate(p);
        }

        // --------------------------
        // F5 => SAVE CAMERA POSITION
        if (Input.GetKeyDown(KeyCode.F5))
        {
            menuM.saveConfig();
        }

        // ----------------------------
        // Cycle through filters F9 F10
        if (Input.GetKeyDown(KeyCode.F11))
        {
            cam_fc.cycleReset();
        }
        if (Input.GetKeyDown(KeyCode.F10))
        {
            cam_fc.cycleForward();
        }
        if (Input.GetKeyDown(KeyCode.F9))
        {
            cam_fc.cycleBackward();
        }

        // ----------------------
        // SPACE => PAUSE UNPAUSE
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (Time.timeScale == 0)
ATREVI Dieudonne's avatar
ATREVI Dieudonne committed
396
                menuM.Play();
397
            else
ATREVI Dieudonne's avatar
ATREVI Dieudonne committed
398
                menuM.Pause();
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
        }

        // --------------------------
        // p or P => Load the param setting panel
        if (Input.GetKeyDown("p"))
        {
            if((menuM.panel.activeSelf==false)&&(menuM.configPanel.activeSelf==false))
            {
                menuM.configParams();
            }
        }
    }

    /// <summary>
    /// Update the current scenario without destroy the previous one
    /// </summary>
    /// <param name="trajDir">The path to the scenario file</param>
    public void updateScenario(string trajDir)
    {
        // ---------------------------------
        // update SCENE FROM CONFIG FILE

        // -------------
        // CAMERA CONFIG
        cam_Rec.enabled = true;
        cam_Movement.enabled = true;
425
        cam_Movement._camera_type = (CamMvt.CameraType)ConfigReader.camType;
426
427
428
429
430
431
        cam.transform.position = ConfigReader.camPosition;
        cam.transform.rotation = Quaternion.Euler(ConfigReader.camRotation);
        cam_Movement.lookAt_Id = ConfigReader.camLookAtTarget;
        cam_Movement.follow_Id = ConfigReader.camFollowTarget;
        cam_Movement.follow_LockX = !ConfigReader.camFollowOnX;
        cam_Movement.follow_LockZ = !ConfigReader.camFollowOnY;
432
433
        cam_Movement.lockFirstPersonView = ConfigReader.camLockFirstPerson;

434
435
436
437
438
439
        // -------------
        // RECORD CONFIG
        cam_Rec.record = ConfigReader.recording;
        cam_Rec.timeToStart = ConfigReader.recordingStart;
        cam_Rec.timeToStop = ConfigReader.recordingEnd;
        cam_Rec.framerate = ConfigReader.recordingFramerate;
BRUNEAU Julien's avatar
BRUNEAU Julien committed
440
        cam_fc.init();
441
442
443
444
445
446
447
448

        if (ConfigReader.recordingSaveDir[0] == '.')
            cam_Rec.saveDir = Directory.GetCurrentDirectory().Replace("\\", "/") + "/" + ConfigReader.recordingSaveDir;
        else
            cam_Rec.saveDir = ConfigReader.recordingSaveDir;
        Camera.main.GetComponent<CamRecorder>().Init();
        InitDeepRecorders();

JOVANE Alberto's avatar
JOVANE Alberto committed
449
        cam_Movement.initializeTargetObjects();
450
451
452
453
        cam_fc.OnSceneChange();

    }

BRUNEAU Julien's avatar
BRUNEAU Julien committed
454
}