Project

General

Profile

Statistics
| Branch: | Revision:

scoutos / scout / scoutsim / src / sim_frame.cpp @ 7b94db2c

History | View | Annotate | Download (27.7 KB)

1 c492be62 Alex Zirbel
/**
2
 * The code in this package was developed using the structure of Willow
3
 * Garage's turtlesim package.  It was modified by the CMU Robotics Club
4
 * to be used as a simulator for the Colony Scout robot.
5 266ae7f2 Alex Zirbel
 *
6 c492be62 Alex Zirbel
 * All redistribution of this code is limited to the terms of Willow Garage's
7
 * licensing terms, as well as under permission from the CMU Robotics Club.
8
 * 
9
 * Copyright (c) 2011 Colony Project
10
 * 
11
 * Permission is hereby granted, free of charge, to any person
12
 * obtaining a copy of this software and associated documentation
13
 * files (the "Software"), to deal in the Software without
14
 * restriction, including without limitation the rights to use,
15
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the
17
 * Software is furnished to do so, subject to the following
18
 * conditions:
19
 * 
20
 * The above copyright notice and this permission notice shall be
21
 * included in all copies or substantial portions of the Software.
22
 * 
23
 * Copyright (c) 2009, Willow Garage, Inc.
24 266ae7f2 Alex Zirbel
 * All rights reserved.
25 c492be62 Alex Zirbel
 * 
26
 * Redistribution and use in source and binary forms, with or without
27
 * modification, are permitted provided that the following conditions are met:
28
 * 
29
 *    Redistributions of source code must retain the above copyright
30
 *       notice, this list of conditions and the following disclaimer.
31
 *    Redistributions in binary form must reproduce the above copyright
32
 *       notice, this list of conditions and the following disclaimer in the
33
 *       documentation and/or other materials provided with the distribution.
34
 *    Neither the name of the Willow Garage, Inc. nor the names of its
35
 *       contributors may be used to endorse or promote products derived from
36
 *       this software without specific prior written permission.
37
 * 
38
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
39
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
40
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
41
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
42
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
43
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
44
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
45
 * OTHER DEALINGS IN THE SOFTWARE.
46 266ae7f2 Alex Zirbel
 */
47
48 3a73516c Alex
/**
49
 * @file sim_frame.cpp
50
 *
51
 * @ingroup scoutsim
52
 * @{
53
 */
54
55 a8480867 Alex Zirbel
#include "sim_frame.h"
56 266ae7f2 Alex Zirbel
57 2eaafff2 Alex
#include <stdio.h>
58
59 266ae7f2 Alex Zirbel
#include <ros/package.h>
60
#include <cstdlib>
61
#include <ctime>
62
63 2eaafff2 Alex
using namespace std;
64 266ae7f2 Alex Zirbel
65
namespace scoutsim
66
{
67 2eaafff2 Alex
    SimFrame::SimFrame(wxWindow* parent, string map_name)
68 266ae7f2 Alex Zirbel
        : wxFrame(parent, wxID_ANY, wxT("ScoutSim"), wxDefaultPosition,
69
                  wxSize(500, 500), wxDEFAULT_FRAME_STYLE & ~wxRESIZE_BORDER)
70 144137a1 Alex Zirbel
          , frame_count(0)
71
          , id_counter(0)
72 46ed9b9b Yuyang (Misty) Guo
          , BOM_counter(0)
73 266ae7f2 Alex Zirbel
    {
74 2eaafff2 Alex
        std::cout << "Constructing sim frame." << std::endl;
75
76 266ae7f2 Alex Zirbel
        srand(time(NULL));
77
78 144137a1 Alex Zirbel
        update_timer = new wxTimer(this);
79 7f095440 Priya
        update_timer->Start(REAL_TIME_REFRESH_RATE * 1000);
80 266ae7f2 Alex Zirbel
81 144137a1 Alex Zirbel
        Connect(update_timer->GetId(), wxEVT_TIMER,
82 266ae7f2 Alex Zirbel
                wxTimerEventHandler(SimFrame::onUpdate), NULL, this);
83
        Connect(wxEVT_PAINT, wxPaintEventHandler(SimFrame::onPaint),
84
                NULL, this);
85
86 594c3bb9 Alex
        images_path = ros::package::getPath("scoutsim") + "/images/";
87 266ae7f2 Alex Zirbel
88 ade1b7f9 Alex
        map_base_name =  ros::package::getPath("scoutsim") + "/maps/" +
89
                           map_name + ".bmp";
90
        map_lines_name = ros::package::getPath("scoutsim") + "/maps/" +
91
                           map_name + "_lines.bmp";
92 7ffad595 Alex
        map_walls_name = ros::package::getPath("scoutsim") + "/maps/" +
93
                           map_name + "_walls.bmp";
94 ade1b7f9 Alex
        display_map_name = map_base_name;
95
96
        wxBitmap lines_bitmap;
97 e2770306 Alex
        wxBitmap walls_bitmap;
98 4c9fb6ba viki
        ROS_INFO("Loading map: %s", display_map_name.c_str());
99 e2770306 Alex
        path_bitmap.LoadFile(wxString::FromAscii(display_map_name.c_str()));
100
101
        // Try to load the file; if it fails, make a new blank file
102
        if (!lines_bitmap.LoadFile(wxString::FromAscii(map_lines_name.c_str())))
103
        {
104
            lines_bitmap = wxBitmap(path_bitmap.GetWidth(), path_bitmap.GetHeight(), 3);
105
        }
106 ade1b7f9 Alex
        lines_image = lines_bitmap.ConvertToImage();
107
108 e2770306 Alex
        // Try to load the file; if it fails, make a new blank file
109
        if (!walls_bitmap.LoadFile(wxString::FromAscii(map_walls_name.c_str())))
110
        {
111
            walls_bitmap = wxBitmap(path_bitmap.GetWidth(), path_bitmap.GetHeight(), 3);
112
        }
113 7ffad595 Alex
        walls_image = walls_bitmap.ConvertToImage();
114
115 266ae7f2 Alex Zirbel
        clear();
116
117 144137a1 Alex Zirbel
        clear_srv = nh.advertiseService("clear",
118 4612f7e4 Alex Zirbel
                                        &SimFrame::clearCallback, this);
119 144137a1 Alex Zirbel
        reset_srv = nh.advertiseService("reset",
120 4612f7e4 Alex Zirbel
                                        &SimFrame::resetCallback, this);
121 144137a1 Alex Zirbel
        spawn_srv = nh.advertiseService("spawn",
122 4612f7e4 Alex Zirbel
                                        &SimFrame::spawnCallback, this);
123 0e143737 Hui Jun Tay
        spawn_em_srv = nh.advertiseService("spawn_em",
124
                                        &SimFrame::spawnEmCallback, this);
125 144137a1 Alex Zirbel
        kill_srv = nh.advertiseService("kill",
126 43811241 Alex
                                        &SimFrame::killCallback, this);
127
        set_sonar_viz_srv = nh.advertiseService("set_sonar_viz",
128
                                        &SimFrame::setSonarVizCallback, this);
129
        set_ghost_srv = nh.advertiseService("set_ghost",
130
                                        &SimFrame::setGhostCallback, this);
131
        set_teleop_srv = nh.advertiseService("set_teleop",
132
                                        &SimFrame::setTeleopCallback, this);
133 266ae7f2 Alex Zirbel
134 82f3f746 Priya
        // Subscribe and publisher wirless from robots
135 7ffad595 Alex
        wireless_receive = nh.advertise< ::messages::WirelessPacket>(
136
            "/wireless/receive", 1000); 
137
        wireless_send = nh.subscribe("/wireless/send", 1000,
138
            &SimFrame::wirelessCallback, this);
139 82f3f746 Priya
140 0e77683c Alex
        // Teleop
141 43811241 Alex
        teleop_type = TELEOP_OFF;
142 0e77683c Alex
        teleop_l_speed = 0;
143
        teleop_r_speed = 0;
144 60a90290 Hui Jun Tay
        teleop_scoutname = "scout1";
145
146 11bb78c2 Hui Jun Tay
        //Emitter default values
147
        em_aperture = PI / 3.0;
148
        em_distance = 1.0;
149
150
151 6ebee82c Alex
        teleop_pub = nh.advertise< ::messages::set_motors>("/scout1/set_motors", 1000);
152 0e77683c Alex
153 266ae7f2 Alex Zirbel
        ROS_INFO("Starting scoutsim with node name %s",
154
                 ros::this_node::getName().c_str()) ;
155
156 2eaafff2 Alex
        wxMenu *menuFile = new wxMenu;
157
        menuFile->Append(ID_ABOUT, _("&About"));
158
        menuFile->AppendSeparator();
159
        menuFile->Append(ID_QUIT, _("E&xit"));
160
161
        wxMenu *menuSim = new wxMenu;
162
        menuSim->Append(ID_CLEAR, _("&Clear"));
163
164
        wxMenu *menuView = new wxMenu;
165
        menuView->Append(ID_MAP, _("&Map"));
166
        menuView->Append(ID_LINES, _("&Lines"));
167 7ffad595 Alex
        menuView->Append(ID_WALLS, _("&Walls"));
168 2eaafff2 Alex
169 0e77683c Alex
        wxMenu *menuTeleop = new wxMenu;
170
        menuTeleop->Append(ID_TELEOP_NONE, _("&None"));
171
        menuTeleop->Append(ID_TELEOP_PRECISE, _("&Precise"));
172
        menuTeleop->Append(ID_TELEOP_FLUID, _("&Fluid"));
173
174 2eaafff2 Alex
        wxMenuBar *menuBar = new wxMenuBar;
175
        menuBar->Append(menuFile, _("&File"));
176
        menuBar->Append(menuSim, _("&Sim"));
177
        menuBar->Append(menuView, _("&View"));
178 0e77683c Alex
        menuBar->Append(menuTeleop, _("&Teleop"));
179 2eaafff2 Alex
180
        SetMenuBar(menuBar);
181
182 c63c9752 Alex
        width_in_meters = GetSize().GetWidth() / PIX_PER_METER;
183
        height_in_meters = GetSize().GetHeight() / PIX_PER_METER;
184 25694a03 Priya
185
        spawnScout("scout1", 1.4, .78, 0);
186 266ae7f2 Alex Zirbel
    }
187
188
    SimFrame::~SimFrame()
189
    {
190 144137a1 Alex Zirbel
        delete update_timer;
191 266ae7f2 Alex Zirbel
    }
192
193 4612f7e4 Alex Zirbel
    bool SimFrame::spawnCallback(scoutsim::Spawn::Request  &req,
194
                                 scoutsim::Spawn::Response &res)
195 266ae7f2 Alex Zirbel
    {
196
        std::string name = spawnScout(req.name, req.x, req.y, req.theta);
197
        if (name.empty())
198
        {
199 43811241 Alex
            ROS_WARN("A scout named [%s] already exists", req.name.c_str());
200 266ae7f2 Alex Zirbel
            return false;
201
        }
202
203
        res.name = name;
204
        return true;
205
    }
206
207 0e143737 Hui Jun Tay
208
    bool SimFrame::spawnEmCallback(scoutsim::Spawn::Request  &req,
209
                                 scoutsim::Spawn::Response &res)
210
    {
211
        std::string name = spawnEmitter(req.name, req.x, req.y, req.theta);
212
        if (name.empty())
213
        {
214
            ROS_WARN("An emitter named [%s] already exists", req.name.c_str());
215
            return false;
216
        }
217
        res.name = name;
218
        return true;
219
    }
220
221 266ae7f2 Alex Zirbel
    bool SimFrame::killCallback(scoutsim::Kill::Request& req,
222
                                scoutsim::Kill::Response&)
223
    {
224 144137a1 Alex Zirbel
        M_Scout::iterator it = scouts.find(req.name);
225 98ed4757 Hui Jun Tay
        M_Emitter::iterator m_it = emitters.find(req.name);
226 144137a1 Alex Zirbel
        if (it == scouts.end())
227 266ae7f2 Alex Zirbel
        {
228 98ed4757 Hui Jun Tay
            if (m_it == emitters.end()) {
229
                ROS_WARN("Tried to kill scout/emitter [%s], which does not exist",
230
                req.name.c_str());
231
                return false;
232
            }
233
            emitters.erase(m_it);
234
            return true;
235 266ae7f2 Alex Zirbel
        }
236
237 144137a1 Alex Zirbel
        scouts.erase(it);
238 266ae7f2 Alex Zirbel
239
        return true;
240
    }
241
242 43811241 Alex
    bool SimFrame::setSonarVizCallback(SetSonarViz::Request& req,
243
                                       SetSonarViz::Response&)
244
    {
245
        M_Scout::iterator it = scouts.find(req.scout_name);
246
        if (it == scouts.end())
247
        {
248
            ROS_WARN("Tried to set sonar on scout [%s], which does not exist",
249
                     req.scout_name.c_str());
250
            return false;
251
        }
252
253
        it->second->set_sonar_visual(req.on);
254
        return true;
255
    }
256
257
    bool SimFrame::setGhostCallback(SetGhost::Request& req,
258
                                    SetGhost::Response&)
259
    {
260
        for (unsigned int i=0; i < ghost_scouts.size(); ++i)
261
        {
262
            if (ghost_scouts.at(i)->get_name() == req.scout_name)
263
            {
264
                ghost_scouts.at(i)->set_visible(req.on);
265
                return true;
266
            }
267
        }
268
269
        ROS_WARN("Tried to set ghost on scout [%s], which does not exist",
270
                 req.scout_name.c_str());
271
        return false;
272
    }
273
274
    bool SimFrame::setTeleopCallback(SetTeleop::Request& req,
275
                                     SetTeleop::Response&)
276
    {
277
        std::stringstream ss;
278
        ss << "/" << req.scout_name << "/set_motors";
279 6ebee82c Alex
        teleop_pub = nh.advertise< ::messages::set_motors>(ss.str(), 1000);
280 60a90290 Hui Jun Tay
        teleop_scoutname = req.scout_name.c_str();
281
        ROS_INFO("Teleoping %s...",teleop_scoutname.c_str()); //debug statement
282 43811241 Alex
283
        return true;
284
    }
285
286 266ae7f2 Alex Zirbel
    bool SimFrame::hasScout(const std::string& name)
287
    {
288 144137a1 Alex Zirbel
        return scouts.find(name) != scouts.end();
289 266ae7f2 Alex Zirbel
    }
290
291 0e143737 Hui Jun Tay
    bool SimFrame::hasEmitter(const std::string& name)
292
    {
293
        return emitters.find(name) != emitters.end();
294
    }
295
296 9b3564f3 Alex Zirbel
    std::string SimFrame::spawnScout(const std::string& name,
297
                                     float x, float y, float angle)
298 266ae7f2 Alex Zirbel
    {
299
        std::string real_name = name;
300
        if (real_name.empty())
301
        {
302 43811241 Alex
            // Generate the name scoutX, where X is an increasing number.
303 266ae7f2 Alex Zirbel
            do
304
            {
305
                std::stringstream ss;
306 144137a1 Alex Zirbel
                ss << "scout" << ++id_counter;
307 266ae7f2 Alex Zirbel
                real_name = ss.str();
308 43811241 Alex
            }
309
            while (hasScout(real_name));
310 266ae7f2 Alex Zirbel
        }
311
        else
312
        {
313
            if (hasScout(real_name))
314
            {
315
                return "";
316
            }
317
        }
318
319 594c3bb9 Alex
        wxImage scout_image;
320
321
        // Try to load a name-specific image; if not, load the default scout
322
        string specific_name = images_path + name + ".png";
323
        if (fileExists(specific_name))
324
        {
325
            scout_image.LoadFile(wxString::FromAscii(specific_name.c_str()));
326
            scout_image.SetMask(true);
327
            scout_image.SetMaskColour(255, 255, 255);
328
        }
329
        else
330
        {
331
            scout_image.LoadFile(
332
                wxString::FromAscii((images_path + "scout.png").c_str()));
333
            scout_image.SetMask(true);
334
            scout_image.SetMaskColour(255, 255, 255);
335
        }
336
337 266ae7f2 Alex Zirbel
        ScoutPtr t(new Scout(ros::NodeHandle(real_name),
338 594c3bb9 Alex
                   scout_image, Vector2(x, y), &path_bitmap, angle));
339 144137a1 Alex Zirbel
        scouts[real_name] = t;
340 266ae7f2 Alex Zirbel
341 0e0ef125 Priya
        ghost_scouts.push_back(new GhostScout(ros::NodeHandle(real_name),
342
                scout_image, Vector2(x, y), &path_bitmap, angle, name));
343
344 266ae7f2 Alex Zirbel
        ROS_INFO("Spawning scout [%s] at x=[%f], y=[%f], theta=[%f]",
345
                 real_name.c_str(), x, y, angle);
346
347
        return real_name;
348
    }
349
350 0e143737 Hui Jun Tay
351
    std::string SimFrame::spawnEmitter(const std::string& name,
352
                                     float x, float y, float angle)
353
    {
354
        std::string real_name = name;
355
        if (real_name.empty())
356
        {
357
            // Generate the name emitterX, where X is an increasing number.
358
            do
359
            {
360
                std::stringstream ss;
361 46ed9b9b Yuyang (Misty) Guo
                ss << "emitter_" << ++BOM_counter;
362 0e143737 Hui Jun Tay
                real_name = ss.str();
363
            }
364
            while (hasEmitter(real_name));
365
        }
366
        else
367
        {
368
            if (hasEmitter(real_name))
369
            {
370
                return "";
371
            }
372
        }
373
374
        wxImage emitter_image;
375
376
        // Try to load a name-specific image; if not, load the default emitter
377
        string specific_name = images_path + name + ".png";
378
        if (fileExists(specific_name))
379
        {
380
            emitter_image.LoadFile(wxString::FromAscii(specific_name.c_str()));
381
            emitter_image.SetMask(true);
382
            emitter_image.SetMaskColour(255, 255, 255);
383
        }
384
        else
385
        {
386
            ROS_INFO("LOADED EMITTER IMAGE");
387
            emitter_image.LoadFile(
388
                wxString::FromAscii((images_path + "emitter.png").c_str()));
389
            emitter_image.SetMask(true);
390
            emitter_image.SetMaskColour(255, 255, 255);
391
        }
392
393
        EmitterPtr t(new Emitter(ros::NodeHandle(real_name),
394
                   emitter_image, Vector2(x, y), &path_bitmap, 
395
                   angle, em_aperture, em_distance));
396
        emitters[real_name] = t;
397
398
        ROS_INFO("Spawning emitter [%s] at x=[%f], y=[%f], theta=[%f]",
399
                 real_name.c_str(), x, y, angle);
400
401
        return real_name;
402
    }
403
404
405 2eaafff2 Alex
    void SimFrame::onQuit(wxCommandEvent& WXUNUSED(event))
406
    {
407
        Close(true);
408
    }
409
410
    void SimFrame::onAbout(wxCommandEvent& WXUNUSED(event))
411
    {
412
        wxMessageBox(_("Scoutsim is the simulator the Colony Project's scout robot.\n"
413
                       "\nThe Colony Project is a part of the Carnegie Mellon\n"
414
                       "Robotics Club. Our goal is to use cooperative low-cost\n"
415
                       "robots to solve challenging problems."),
416
                     _("About Scoutsim"),
417
                     wxOK | wxICON_INFORMATION, this );
418
    }
419
420
    void SimFrame::onClear(wxCommandEvent& WXUNUSED(event))
421 266ae7f2 Alex Zirbel
    {
422 2eaafff2 Alex
        clear();
423
    }
424 266ae7f2 Alex Zirbel
425 2eaafff2 Alex
    void SimFrame::showMap(wxCommandEvent& WXUNUSED(event))
426
    {
427 ade1b7f9 Alex
        display_map_name = map_base_name;
428 2eaafff2 Alex
        clear();
429
    }
430 266ae7f2 Alex Zirbel
431 2eaafff2 Alex
    void SimFrame::showLines(wxCommandEvent& WXUNUSED(event))
432
    {
433 ade1b7f9 Alex
        display_map_name = map_lines_name;
434 2eaafff2 Alex
        clear();
435
    }
436 7ffad595 Alex
    
437
    void SimFrame::showWalls(wxCommandEvent& WXUNUSED(event))
438
    {
439
        display_map_name = map_walls_name;
440
        clear();
441
    }
442 2eaafff2 Alex
443
    void SimFrame::clear()
444
    {
445
        path_dc.SetBackground(wxBrush(wxColour(100, 100, 100)));
446 144137a1 Alex Zirbel
        path_dc.Clear();
447 2eaafff2 Alex
448 6639ce9c viki
        sonar_dc.SetBackground(wxBrush(wxColour(255, 0, 0)));
449
        sonar_dc.Clear();
450
451
        sonar_dc.SelectObject(path_bitmap);
452
453 2eaafff2 Alex
        path_bitmap.LoadFile(wxString::FromAscii(display_map_name.c_str()));
454
        path_dc.SelectObject(path_bitmap);
455
        SetSize(wxSize(path_bitmap.GetWidth(), path_bitmap.GetHeight()));
456 266ae7f2 Alex Zirbel
    }
457
458 7f095440 Priya
    // Runs every REAL_TIME_REFRESH_RATE.
459 266ae7f2 Alex Zirbel
    void SimFrame::onUpdate(wxTimerEvent& evt)
460
    {
461
        ros::spinOnce();
462
463 0e77683c Alex
        teleop();
464
465 266ae7f2 Alex Zirbel
        updateScouts();
466
467
        if (!ros::ok())
468
        {
469
            Close();
470
        }
471 04114d13 Alex
472
        frame_count++;
473 266ae7f2 Alex Zirbel
    }
474
475
    void SimFrame::onPaint(wxPaintEvent& evt)
476
    {
477
        wxPaintDC dc(this);
478
479 144137a1 Alex Zirbel
        dc.DrawBitmap(path_bitmap, 0, 0, true);
480 266ae7f2 Alex Zirbel
481 144137a1 Alex Zirbel
        M_Scout::iterator it = scouts.begin();
482
        M_Scout::iterator end = scouts.end();
483 266ae7f2 Alex Zirbel
        for (; it != end; ++it)
484
        {
485
            it->second->paint(dc);
486
        }
487 0e143737 Hui Jun Tay
488
489
        M_Emitter::iterator m_it = emitters.begin();
490
        M_Emitter::iterator m_end = emitters.end();
491
        for (; m_it != m_end; ++m_it)
492
        {
493
            m_it->second->paint(dc);
494
        }
495
496 43811241 Alex
        for (unsigned int i=0; i < ghost_scouts.size(); ++i)
497 0e0ef125 Priya
        {
498
            ghost_scouts.at(i)->paint(dc);
499
        }
500 266ae7f2 Alex Zirbel
    }
501
502 594c3bb9 Alex
    bool SimFrame::fileExists(const std::string& filename)
503
    {
504
        struct stat buf;
505
        if (stat(filename.c_str(), &buf) != -1)
506
        {
507
            return true;
508
        }
509
        return false;
510
    }
511
512 0e77683c Alex
    void SimFrame::stopTeleop(wxCommandEvent& event)
513
    {
514
        teleop_type = TELEOP_OFF;
515
        teleop_l_speed = 0;
516
        teleop_r_speed = 0;
517
    }
518
519
    void SimFrame::startTeleopPrecise(wxCommandEvent& event)
520
    {
521
        teleop_type = TELEOP_PRECISE;
522
        teleop_l_speed = 0;
523
        teleop_r_speed = 0;
524
    }
525
526
    void SimFrame::startTeleopFluid(wxCommandEvent& event)
527
    {
528
        teleop_type = TELEOP_FLUID;
529
        teleop_l_speed = 0;
530
        teleop_r_speed = 0;
531
        teleop_fluid_speed = 0;
532
        teleop_fluid_omega = 0;
533
    }
534
535
    void SimFrame::teleop_move_precise()
536
    {
537
        // Default to stop
538
        teleop_l_speed = 0;
539
        teleop_r_speed = 0;
540
541
        if (wxGetKeyState(WXK_UP))
542
        {
543
            teleop_l_speed = TELEOP_PRECISE_SPEED;
544
            teleop_r_speed = TELEOP_PRECISE_SPEED;
545
        }
546
        else if (wxGetKeyState(WXK_DOWN))
547
        {
548
            teleop_l_speed = -TELEOP_PRECISE_SPEED;
549
            teleop_r_speed = -TELEOP_PRECISE_SPEED;
550
        }
551
        else if (wxGetKeyState(WXK_LEFT))
552
        {
553 43811241 Alex
            teleop_l_speed = -TELEOP_PRECISE_TURN_SPEED;
554
            teleop_r_speed = TELEOP_PRECISE_TURN_SPEED;
555 0e77683c Alex
        }
556
        else if (wxGetKeyState(WXK_RIGHT))
557
        {
558 43811241 Alex
            teleop_l_speed = TELEOP_PRECISE_TURN_SPEED;
559
            teleop_r_speed = -TELEOP_PRECISE_TURN_SPEED;
560 0e77683c Alex
        }
561
    }
562
563
    void SimFrame::teleop_move_fluid()
564
    {
565
        if (wxGetKeyState(WXK_UP))
566
        {
567 c63c9752 Alex
            teleop_fluid_speed += TELEOP_FLUID_INC * 2;
568 0e77683c Alex
        }
569
        else if (wxGetKeyState(WXK_DOWN))
570
        {
571 c63c9752 Alex
            teleop_fluid_speed -= TELEOP_FLUID_INC * 2;
572 0e77683c Alex
        }
573 04114d13 Alex
        else if (teleop_fluid_speed > TELEOP_FLUID_INC)
574 0e77683c Alex
        {
575 c63c9752 Alex
            teleop_fluid_speed -= TELEOP_FLUID_INC;
576 0e77683c Alex
        }
577 04114d13 Alex
        else if (teleop_fluid_speed < -TELEOP_FLUID_INC)
578 0e77683c Alex
        {
579 c63c9752 Alex
            teleop_fluid_speed += TELEOP_FLUID_INC;
580 0e77683c Alex
        }
581 04114d13 Alex
        else
582
        {
583
            teleop_fluid_speed = 0;
584
        }
585 0e77683c Alex
586
        if (wxGetKeyState(WXK_LEFT))
587
        {
588 7f095440 Priya
            teleop_fluid_omega -= TELEOP_FLUID_INC * 2;
589 0e77683c Alex
        }
590
        else if (wxGetKeyState(WXK_RIGHT))
591
        {
592 7f095440 Priya
            teleop_fluid_omega += TELEOP_FLUID_INC * 2;
593 0e77683c Alex
        }
594 0076084e Alex
        else
595 0e77683c Alex
        {
596 0076084e Alex
            teleop_fluid_omega = 0;
597 0e77683c Alex
        }
598
599
        if (teleop_fluid_speed > TELEOP_FLUID_MAX_SPEED)
600
        {
601
            teleop_fluid_speed = TELEOP_FLUID_MAX_SPEED;
602
        }
603 c63c9752 Alex
        else if (teleop_fluid_speed < -TELEOP_FLUID_MAX_SPEED)
604
        {
605
            teleop_fluid_speed = -TELEOP_FLUID_MAX_SPEED;
606
        }
607 04114d13 Alex
        if (teleop_fluid_omega > TELEOP_FLUID_MAX_SPEED)
608 0e77683c Alex
        {
609 04114d13 Alex
            teleop_fluid_omega = TELEOP_FLUID_MAX_SPEED;
610 0e77683c Alex
        }
611 04114d13 Alex
        else if (teleop_fluid_omega < -TELEOP_FLUID_MAX_SPEED)
612 c63c9752 Alex
        {
613 04114d13 Alex
            teleop_fluid_omega = -TELEOP_FLUID_MAX_SPEED;
614 c63c9752 Alex
        }
615 0e77683c Alex
616 04114d13 Alex
        int l_speed = teleop_fluid_speed + teleop_fluid_omega;
617
        int r_speed = teleop_fluid_speed - teleop_fluid_omega;
618
619
        teleop_l_speed = max(MIN_ABSOLUTE_SPEED,
620
                             min(MAX_ABSOLUTE_SPEED, l_speed));
621
        teleop_r_speed = max(MIN_ABSOLUTE_SPEED,
622
                             min(MAX_ABSOLUTE_SPEED, r_speed));
623 0e77683c Alex
    }
624
625
    void SimFrame::teleop()
626
    {
627
        switch (teleop_type)
628
        {
629
            case TELEOP_OFF:
630
                return;
631
            case TELEOP_PRECISE:
632
                teleop_move_precise();
633
                break;
634
            case TELEOP_FLUID:
635
                teleop_move_fluid();
636
                break;
637
        }
638
639 6ebee82c Alex
        ::messages::set_motors msg;
640 0e77683c Alex
        msg.fl_set = true;
641
        msg.fr_set = true;
642
        msg.bl_set = true;
643
        msg.br_set = true;
644 60a90290 Hui Jun Tay
        msg.teleop_ON = true;
645 0e77683c Alex
646
        msg.fl_speed = teleop_l_speed;
647
        msg.fr_speed = teleop_r_speed;
648
        msg.bl_speed = teleop_l_speed;
649
        msg.br_speed = teleop_r_speed;
650
651
        teleop_pub.publish(msg);
652
    }
653
654 266ae7f2 Alex Zirbel
    void SimFrame::updateScouts()
655
    {
656 60a90290 Hui Jun Tay
657 144137a1 Alex Zirbel
        if (last_scout_update.isZero())
658 266ae7f2 Alex Zirbel
        {
659 144137a1 Alex Zirbel
            last_scout_update = ros::WallTime::now();
660 266ae7f2 Alex Zirbel
            return;
661
        }
662
663 04114d13 Alex
        path_image = path_bitmap.ConvertToImage();
664
        Refresh();
665 266ae7f2 Alex Zirbel
666 144137a1 Alex Zirbel
        M_Scout::iterator it = scouts.begin();
667
        M_Scout::iterator end = scouts.end();
668 e3f69e61 Alex
669 0e143737 Hui Jun Tay
        M_Emitter::iterator m_it = emitters.begin();
670
        M_Emitter::iterator m_end = emitters.end();
671
672 e3f69e61 Alex
        world_state state;
673
        state.canvas_width = width_in_meters;
674
        state.canvas_height = height_in_meters;
675
676 71ae6e3f Hui Jun Tay
677 98ed4757 Hui Jun Tay
        for (; m_it != m_end; ++m_it)
678 266ae7f2 Alex Zirbel
        {
679 60a90290 Hui Jun Tay
680 98ed4757 Hui Jun Tay
            m_it->second->update(SIM_TIME_REFRESH_RATE,
681
                               path_dc,
682 a2e6bd4c Alex
                               path_image, lines_image, walls_image,
683 144137a1 Alex Zirbel
                               path_dc.GetBackground().GetColour(),
684 f09d002e Hui Jun Tay
                               state);
685 266ae7f2 Alex Zirbel
        }
686
687 0e143737 Hui Jun Tay
688 98ed4757 Hui Jun Tay
        for (; it != end; ++it)
689 0e143737 Hui Jun Tay
        {
690 98ed4757 Hui Jun Tay
            //ROS_INFO(it->second);
691
            geometry_msgs::Pose2D scout_pos;
692
            scout_pos = it->second->update(SIM_TIME_REFRESH_RATE,
693
                               path_dc, sonar_dc,
694 0e143737 Hui Jun Tay
                               path_image, lines_image, walls_image,
695
                               path_dc.GetBackground().GetColour(),
696 98ed4757 Hui Jun Tay
                               sonar_dc.GetBackground().GetColour(),
697 0e143737 Hui Jun Tay
                               state);
698 98ed4757 Hui Jun Tay
699 71ae6e3f Hui Jun Tay
            checkBOM(scout_pos, it);            
700 0e143737 Hui Jun Tay
        }
701
702 98ed4757 Hui Jun Tay
703 43811241 Alex
        for (unsigned int i = 0; i < ghost_scouts.size(); ++i)
704 0e0ef125 Priya
        {
705 7f095440 Priya
            ghost_scouts.at(i)->update(SIM_TIME_REFRESH_RATE, path_dc, sonar_dc,
706 0e0ef125 Priya
                path_dc.GetBackground().GetColour(), state);
707
        }
708
709 0e143737 Hui Jun Tay
710 c492be62 Alex Zirbel
        frame_count++;
711 266ae7f2 Alex Zirbel
    }
712
713 0e143737 Hui Jun Tay
714 71ae6e3f Hui Jun Tay
    void SimFrame::checkBOM(geometry_msgs::Pose2D scout_pos, 
715
                            M_Scout::iterator it)
716 7b94db2c Hui Jun Tay
    {
717
718
        geometry_msgs::Pose2D bom_pos;       
719
        double x_offset;
720
        double y_offset;    
721
        double offset_angle;
722
        double diag_dis = pow((pow((SCOUT_W/2.0),2) + 
723
                          pow((SCOUT_H/2.0),2)),(0.5));
724
        int emitter_id;
725
726
        for (int i = 0; i < 10; i++) {
727
            emitter_id = -1;
728
                 
729
            diag_dis = pow((pow((SCOUT_W/2.0),2) + 
730
                              pow((SCOUT_H/2.0),2)),(0.5));
731
732
            if (i == 2) { //middle left
733
                offset_angle = PI/2.0;
734
                bom_pos.theta = scout_pos.theta + PI/2.0;
735
            }
736
            else if (i == 7) { //middle right
737
                offset_angle = 3*PI/2.0;
738
                bom_pos.theta = scout_pos.theta + 3.0*PI/2.0;
739
            }
740
            else if (i < 2) { //top left
741
                offset_angle =  atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
742
                bom_pos.theta = scout_pos.theta + PI/2.0 * i;
743
            }
744
            else if (i >= 2 && i <5) { //bottom left
745
                offset_angle =  PI - atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
746
                bom_pos.theta = scout_pos.theta + PI/2.0 + PI/2.0 * (i/4);
747
            }
748
            else if (i >= 5 && i < 8) { //bottom right
749
                offset_angle =  PI + atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
750
                bom_pos.theta = scout_pos.theta + PI + PI/2.0 * (i/6);
751
            }
752
            else { //top right
753
                offset_angle =  2*PI - atan(abs((SCOUT_W/2.0)/(SCOUT_H/2.0)));
754
                bom_pos.theta = scout_pos.theta + 3*PI/2.0 + PI/2.0 * (i/9);
755
            }
756
            offset_angle += scout_pos.theta;
757
            
758
            if (i == 2 || i == 7) {
759
                x_offset = (SCOUT_W/2.0)*cos(offset_angle);
760
                y_offset = (SCOUT_W/2.0)*sin(offset_angle);
761
            }
762
            else {
763
                x_offset = diag_dis*cos(offset_angle);
764
                y_offset = diag_dis*sin(offset_angle);
765
            }
766
767
            bom_pos.x = scout_pos.x + x_offset;
768
            bom_pos.y = scout_pos.y - y_offset;  
769
770
            if (bom_pos.theta > 2*PI) {
771
                bom_pos.theta -= 2*PI;
772
            }  
773
            else if (bom_pos.theta < 0) {
774
                bom_pos.theta += 2*PI;
775
            }
776
777
            emitter_id = getActiveEmitter(bom_pos);
778
779
            if (emitter_id >= 0) {                
780
                it->second->update_BOM(i, 1, emitter_id);
781
            }
782
            else {
783
                it->second->update_BOM(i, 0, -1);
784
            }
785
786
        }
787
788
789
    }
790
791
    int SimFrame::getActiveEmitter(geometry_msgs::Pose2D bom_pos) {
792 71ae6e3f Hui Jun Tay
793
        M_Emitter::iterator m_it = emitters.begin();
794
        M_Emitter::iterator m_end = emitters.end();
795 7b94db2c Hui Jun Tay
        int emitter_id = -1;
796
        for (; m_it != m_end; ++m_it) {
797 71ae6e3f Hui Jun Tay
            geometry_msgs::Pose2D emitter_pos;
798
            emitter_pos = m_it->second->get_pos();
799 46ed9b9b Yuyang (Misty) Guo
800 7b94db2c Hui Jun Tay
            if(is_inrange(bom_pos, emitter_pos, em_aperture, em_distance) &&
801
               is_inrange(emitter_pos, bom_pos, BOM_APERTURE, BOM_DISTANCE)) {
802
                string em_id_str = m_it->first.substr(m_it->first.find("_")+1);
803
                emitter_id = atoi(em_id_str.c_str());
804
                return emitter_id;
805 71ae6e3f Hui Jun Tay
            }
806
        }
807 7b94db2c Hui Jun Tay
        return -1;
808 71ae6e3f Hui Jun Tay
    }
809
810
811 266ae7f2 Alex Zirbel
    bool SimFrame::clearCallback(std_srvs::Empty::Request&,
812
                                 std_srvs::Empty::Response&)
813
    {
814
        ROS_INFO("Clearing scoutsim.");
815
        clear();
816
        return true;
817
    }
818
819
    bool SimFrame::resetCallback(std_srvs::Empty::Request&,
820
                                 std_srvs::Empty::Response&)
821
    {
822
        ROS_INFO("Resetting scoutsim.");
823 144137a1 Alex Zirbel
        scouts.clear();
824
        id_counter = 0;
825 46ed9b9b Yuyang (Misty) Guo
        BOM_counter = 0;
826
827 144137a1 Alex Zirbel
        spawnScout("", width_in_meters / 2.0, height_in_meters / 2.0, 0);
828 266ae7f2 Alex Zirbel
        clear();
829
        return true;
830
    }
831
832 1d1281cc Priya
    void SimFrame::wirelessCallback(const ::messages::WirelessPacket::ConstPtr& msg)
833 82f3f746 Priya
    {
834
        wireless_receive.publish(msg);
835
    }
836 0e143737 Hui Jun Tay
837
838 71ae6e3f Hui Jun Tay
    bool SimFrame::is_inrange(geometry_msgs::Pose2D scout_pos,
839 11bb78c2 Hui Jun Tay
                           geometry_msgs::Pose2D emitter_pos,
840
                           double aperture, double distance)
841 71ae6e3f Hui Jun Tay
                           
842 0e143737 Hui Jun Tay
    {
843 98ed4757 Hui Jun Tay
        //ROS_INFO("SCOUT: %f %f %f ", scout_pos.x, scout_pos.x, scout_pos.theta);
844
        //ROS_INFO("EMITTER: %f %f %f ", emitter_pos.x, emitter_pos.x, emitter_pos.theta);
845
        double se_distance = pow((pow((scout_pos.x - emitter_pos.x),2) + 
846
                              pow((scout_pos.y - emitter_pos.y),2)),(0.5));
847
        double se_angle = atan((scout_pos.x - emitter_pos.x)/(scout_pos.y - emitter_pos.y));
848
        if (scout_pos.y < emitter_pos.y)
849
        {
850
            se_angle = se_angle + PI/2;
851
        }        
852
        else 
853
        {
854
            se_angle = se_angle + PI*3/2;
855
        }
856
        double emitter_orient = emitter_pos.theta;
857
        
858
        //ROS_INFO("distance: %f, angle: %f, orient: %f", se_distance, se_angle, emitter_orient);
859
860 11bb78c2 Hui Jun Tay
        if ((se_distance <= distance)) { //distance check
861 0e143737 Hui Jun Tay
862 11bb78c2 Hui Jun Tay
            double upper_limit = (emitter_orient + aperture/2);
863
            double lower_limit = (emitter_orient - aperture/2);
864 98ed4757 Hui Jun Tay
865
            //ROS_INFO("upper: %f, lower: %f", upper_limit, lower_limit+2*PI);
866
867
            if (upper_limit > 2*PI) {
868
               if (((se_angle < 2*PI) && (se_angle > (lower_limit))) ||
869
                   ((se_angle < upper_limit-2*PI) && (se_angle >= 0))) {
870 71ae6e3f Hui Jun Tay
                return true;
871 98ed4757 Hui Jun Tay
                }
872
                
873
            }
874
            else if (lower_limit < 0) {
875
                if (((se_angle < 2*PI) && (se_angle > (lower_limit+2*PI))) ||
876
                   ((se_angle < upper_limit) && (se_angle >= 0))) {
877 71ae6e3f Hui Jun Tay
                return true;
878 98ed4757 Hui Jun Tay
                }
879
880
881
            }
882
            else {
883
                if ((se_angle < upper_limit) && //angle check 
884
                    (se_angle > lower_limit)) {
885 71ae6e3f Hui Jun Tay
                return true;
886 98ed4757 Hui Jun Tay
                }   
887
            }
888
        }
889 71ae6e3f Hui Jun Tay
        return false;
890 98ed4757 Hui Jun Tay
            
891 0e143737 Hui Jun Tay
    }
892
893 266ae7f2 Alex Zirbel
}
894 3a73516c Alex
895
/** @} */