LoadEnv.cs 17.3 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    /// <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;
        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;
        
        // -------------
        // 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();

103
        //FB don't know why there this check
BRUNEAU Julien's avatar
BRUNEAU Julien committed
104
        //JB to see if it is a relative path or full one
105
106
        //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] == '.')
107
108
            cam_Rec.saveDir = Directory.GetCurrentDirectory().Replace("\\", "/") + "/" + ConfigReader.recordingSaveDir;
        else
109
110
111
112
113
114
115
116
117
118
            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
119
120
121
122
        avatars.Clear();

        // -------------
        // CREATE AGENTS
123
124
125
126
127
128
129
130
131
132
133
        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)
        {
134
135
136
137
            // ------------------------------------------------------------
            // IF NO ROCKETMAN (PROPRIETARY ASSETS), USE PLASTICMAN INSTEAD
            GameObject character = (testRocketMan!=null) ? CreateAgent_RocketBox(i) : CreateAgent_PlasticMan(i);
            character.transform.parent = crowdParentObject.transform;
138
139
            avatars.Add(character);

140
141
142
143
            // ---------------------
            // SET NAME, TAG, AND ID
            character.name += i.ToString("D4");
            character.tag = "Player";
144
145
146
147
148
149
150
151
            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
152

153
154
155

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

163
            i++;
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
164
165
        }

166
167
168
169
170
171
172
173
174
        cam_Movement.updateTargetedObject();
        cam_fc.OnSceneChange();

    }

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

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

    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)
        {
216
            path = "male/prefab_light/LS_m";
217
218
219
220
            modelId = id / 2;
        }
        else
        {
221
            path = "female/prefab_light/LS_f";
222
223
224
            modelId = (id - 1) / 2;
        }
        modelId = (modelId % 20) + 1;
225
        return "Prefabs/RocketBox/" + path + modelId.ToString("D3") + "_light";
226
227
228
229
230
231
    }

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

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

        // ---------------------------------------------
        // 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 };

250
            SkinnedMeshRenderer[] rendererList = rb.GetComponentsInChildren<SkinnedMeshRenderer>();
251
252
253
            foreach (SkinnedMeshRenderer renderer in rendererList)
                renderer.materials = mats;
        }
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
        // --------------------------------------
        // ELSE ADD SOME VARIATION IN THE TEXTURE
        else
        {
            TextureVariation[] tvList = rb.GetComponentsInChildren<TextureVariation>();

            int variation = 0;
            if (tvList.Length>0)
            {
                variation = (int)(((int)(id / 2)) / 20);
                variation = (variation % (tvList[0].getNumberOfVariationsMax()-1)) + 1;
            }

            foreach (TextureVariation tv in tvList)
            {
                tv.SetVariationId(variation);
            }

        }
273

274
        return rb;
275
276
277
278
279
280
281
    }

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

        // -------------------
        // SET BOUNDING BOXES ITEM
285
        gameObject.AddComponent<GetMemberPositionPlasticMan>();
286
        GameObject headBoundingBox = Instantiate(Resources.Load<GameObject>("HeadBoundingBoxes/Hbb_PlasticMan"));
287
288
        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;
289
290
291
292
293
294
295
296
297
298
299
300
301

        // -----------------
        // 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;
    }

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
    /// <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
412
                menuM.Play();
413
            else
ATREVI Dieudonne's avatar
ATREVI Dieudonne committed
414
                menuM.Pause();
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
        }

        // --------------------------
        // 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;
        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;
        
        // -------------
        // 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
454
        cam_fc.init();
455
456
457
458
459
460
461
462
463
464
465
466
467

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

        cam_Movement.updateTargetedObject();
        cam_fc.OnSceneChange();

    }

BRUNEAU Julien's avatar
BRUNEAU Julien committed
468
}