File: Entity.cpp

package info (click to toggle)
eris 1.3.10-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,592 kB
  • ctags: 1,516
  • sloc: cpp: 9,850; sh: 8,288; perl: 287; ansic: 165; makefile: 162
file content (581 lines) | stat: -rw-r--r-- 14,666 bytes parent folder | download
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
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
396
397
398
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
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#ifdef HAVE_CONFIG_H
    #include "config.h"
#endif

#include <Eris/Entity.h>
#include <Eris/Connection.h>
#include <Eris/TypeInfo.h>
#include <Eris/LogStream.h>
#include <Eris/EntityRouter.h>
#include <Eris/View.h>
#include <Eris/Exceptions.h>
#include <Eris/Avatar.h>
#include <Eris/Alarm.h>

#include <wfmath/atlasconv.h>
#include <Atlas/Objects/Entity.h>
#include <Atlas/Objects/Operation.h>
#include <Atlas/Objects/BaseObject.h>

#include <algorithm>
#include <set> 
#include <cmath>
#include <cassert>

using namespace Atlas::Objects::Operation;
using Atlas::Objects::Root;
using Atlas::Objects::Entity::RootEntity;
using Atlas::Message::Element;
using Atlas::Objects::smart_static_cast;
using Atlas::Objects::smart_dynamic_cast;

using WFMath::TimeStamp;
using WFMath::TimeDiff;

namespace Eris {

Entity::Entity(const std::string& id, TypeInfo* ty, View* vw) :
    m_type(ty),
    m_location(NULL),
    m_id(id),
    m_stamp(-1.0),
    m_visible(false),
    m_limbo(false),
    m_updateLevel(0),
    m_view(vw),
    m_hasBBox(false),
    m_moving(false),
    m_recentlyCreated(false)
{
    assert(m_id.size() > 0);
    m_orientation.identity();
    
    m_router = new EntityRouter(this);
    m_view->getConnection()->registerRouterForFrom(m_router, m_id);
}

Entity::~Entity()
{   
    BeingDeleted.emit();
    if (m_moving) m_view->removeFromPrediction(this);
    
    while (!m_contents.empty()) delete m_contents.back();    
    setLocation(NULL);
    
    m_view->getConnection()->unregisterRouterForFrom(m_router, m_id);
    m_view->entityDeleted(this); // remove ourselves from the View's content map
    delete m_router;
}

void Entity::init(const RootEntity& ge, bool fromCreateOp)
{
    // setup initial state
    sight(ge);
    
    if (fromCreateOp)
    {
        m_recentlyCreated = true;
        new Alarm(5000, sigc::mem_fun(this, &Entity::createAlarmExpired));
    }
}

#pragma mark -

const Element& Entity::valueOfAttr(const std::string& attr) const
{
    AttrMap::const_iterator A = m_attrs.find(attr);
    if (A == m_attrs.end())
    {
        error() << "did getAttr(" << attr << ") on entity " << m_id << " which has no such attr";
        throw InvalidOperation("no such attribute " + attr);
    } else
        return A->second;
}

bool Entity::hasAttr(const std::string& attr) const
{
    return m_attrs.count(attr) > 0;
}

SigC::Connection Entity::observe(const std::string& attr, const AttrChangedSlot& slot)
{
    // sometimes, I realize how great SigC++ is
    return m_observers[attr].connect(slot);
}

WFMath::Point<3> Entity::getViewPosition() const
{
    WFMath::Point<3> vpos(0.0, 0.0, 0.0);
    for (const Entity* e = this; e; e = e->getLocation())
        vpos = e->toLocationCoords(vpos);
        
    return vpos;
}

WFMath::Quaternion Entity::getViewOrientation() const
{
    WFMath::Quaternion vor;
	
	vor.identity();
    for (const Entity* e = this; e; e = e->getLocation())
        vor *= e->getOrientation();
        
    return vor;
}

WFMath::Point<3> Entity::getPredictedPos() const
{
    return (m_moving ? m_predicted.position : m_position);
}

WFMath::Vector<3> Entity::getPredictedVelocity() const
{
    return (m_moving ? m_predicted.velocity : WFMath::Vector<3>());
}

bool Entity::isMoving() const
{
    return m_moving;
}


void Entity::updatePredictedState(const WFMath::TimeStamp& t)
{
    assert(isMoving());
    
    double dt = (t - m_lastMoveTime).milliseconds() / 1000.0; 
    
    if (m_acc.isValid()) {
        m_predicted.velocity = m_velocity + (m_acc * dt);
        m_predicted.position = m_position + (m_velocity * dt) + (m_acc * 0.5 * dt * dt);
    } else {
        m_predicted.velocity = m_velocity;
        m_predicted.position = m_position + (m_velocity * dt);
    }
}

#pragma mark -

void Entity::sight(const RootEntity &ge)
{    
    if (!ge->isDefaultLoc()) setLocationFromAtlas(ge->getLoc());
    
    setContentsFromAtlas(ge->getContains());    
    setFromRoot(ge, true);
}

void Entity::setFromRoot(const Root& obj, bool allowMove)
{	
    beginUpdate();
    
    Atlas::Message::MapType attrs;
    obj->addToMessage(attrs);
    Atlas::Message::MapType::iterator A;
    
    attrs.erase("loc");
    attrs.erase("id");
    attrs.erase("contains");
    
    if (!allowMove) filterMoveAttrs(attrs);
    
    for (A = attrs.begin(); A != attrs.end(); ++A) {
        // see if the value in the sight matches the exsiting value
        AttrMap::iterator I = m_attrs.find(A->first);
        if ((I != m_attrs.end()) && (I->second == A->second)) continue;

        setAttr(A->first, A->second);
    }
    
    endUpdate();
}

void Entity::filterMoveAttrs(Atlas::Message::MapType& attrs) const
{
    attrs.erase("pos");
    attrs.erase("mode");
    attrs.erase("velocity");
    attrs.erase("orientation");
    attrs.erase("accel");
}

void Entity::onTalk(const Atlas::Objects::Operation::RootOperation& talk)
{
    const std::vector<Root>& talkArgs = talk->getArgs();
    if (talkArgs.empty())
    {
        warning() << "entity " << getId() << " got sound(talk) with no args";
        return;
    }

    Say.emit(talkArgs.front());
    Noise.emit(talk);
    m_view->getAvatar()->Hear.emit(this, talk);
}

void Entity::onLocationChanged(Entity* oldLoc)
{
    LocationChanged.emit(oldLoc);
}

void Entity::onMoved()
{
    Moved.emit();
}

void Entity::onAction(const Atlas::Objects::Operation::RootOperation& arg)
{
    Acted.emit(arg);
}

void Entity::onSoundAction(const Atlas::Objects::Operation::RootOperation& op)
{
    Noise.emit(op);
    m_view->getAvatar()->Hear.emit(this, op);
}

void Entity::onImaginary(const Atlas::Objects::Root& arg)
{
    if (arg->hasAttr("description")) {
        Emote.emit(arg->getAttr("description").asString());
    }
}

void Entity::setMoving(bool inMotion)
{
    assert(m_moving != inMotion);
    
    if (m_moving) m_view->removeFromPrediction(this);
    m_moving = inMotion;
    if (m_moving) {
        m_predicted.position = m_position;
        m_predicted.velocity = m_velocity;
        m_view->addToPrediction(this);
    }
    
    Moving.emit(inMotion);
}

void Entity::onChildAdded(Entity* child)
{
    ChildAdded.emit(child);
}

void Entity::onChildRemoved(Entity* child)
{
    ChildRemoved(child);
}

#pragma mark -

void Entity::setAttr(const std::string &attr, const Element &val)
{
    beginUpdate();

    Element& target = m_attrs[attr];
    mergeOrCopyElement(val, target);
    nativeAttrChanged(attr, target);
        
    onAttrChanged(attr, target);

    // fire observers
    
    ObserverMap::const_iterator obs = m_observers.find(attr);
    if (obs != m_observers.end()) obs->second.emit(attr, target);

    addToUpdate(attr);
    endUpdate();
}

bool Entity::nativeAttrChanged(const std::string& attr, const Element& v)
{
    // in the future, hash these names to a compile-time integer index, and
    // make this a switch statement. The same indice could also be used
    // in endUpdate
    
    if (attr == "name") {
        m_name = v.asString();
        return true;
    } else if (attr == "stamp") {
        m_stamp = v.asFloat();
        return true;
    } else if (attr == "pos") {
        m_position.fromAtlas(v);
        return true;
    } else if (attr == "velocity") {
        m_velocity.fromAtlas(v);
        return true;
    } else if (attr == "accel") {
        m_acc.fromAtlas(v);
        return true;
    } else if (attr == "orientation") {
        m_orientation.fromAtlas(v);
        return true;
    } else if (attr == "description") {
        m_description = v.asString();
        return true;
    } else if (attr == "bbox") {
        m_bbox.fromAtlas(v);
        m_hasBBox = true;
        return true;
    } else if ((attr == "loc") ||(attr == "contains")) {
        throw InvalidOperation("tried to set loc or contains via setProperty");
    }

    return false; // not a native property
}

void Entity::onAttrChanged(const std::string&, const Element&)
{
    // no-op by default
}

void Entity::beginUpdate()
{
    ++m_updateLevel;
}

void Entity::addToUpdate(const std::string& attr)
{
    assert(m_updateLevel > 0);
    m_modifiedAttrs.insert(attr);
}

void Entity::endUpdate()
{
    if (m_updateLevel < 1)
    {
        error() << "mismatched begin/end update pair on entity";
        return;
    }
        
    if (--m_updateLevel == 0) // unlocking updates
    {
        Changed.emit(m_modifiedAttrs);
        
        if (m_modifiedAttrs.count("pos") || 
            m_modifiedAttrs.count("velocity") ||
            m_modifiedAttrs.count("orientation"))
        {
            m_lastMoveTime = TimeStamp::now();
            
            const WFMath::Vector<3> & velocity = getVelocity();
            bool nowMoving = (velocity.isValid() && (velocity.sqrMag() > 1e-3));
            if (nowMoving != m_moving) setMoving(nowMoving);
            
            onMoved();
        }
        
        m_modifiedAttrs.clear();
    }
}

#pragma mark -

void Entity::setLocationFromAtlas(const std::string& locId)
{
    if (locId.empty()) return;
    
    Entity* newLocation = m_view->getEntity(locId);
    if (!newLocation)
    {
        m_view->getEntityFromServer(locId);
        
        m_limbo = true;
        setVisible(false); // fire disappearance, VisChanged if necessary
        
        if (m_location) removeFromLocation();
        m_location = NULL;
        assert(m_visible == false);
        return;
    }
    
    setLocation(newLocation);
}

void Entity::setLocation(Entity* newLocation)
{
    if (newLocation == m_location) return;
        
// do the actual member updating
    bool wasVisible = isVisible();
    if (m_location) removeFromLocation();
        
    Entity* oldLocation = m_location;
    m_location = newLocation;
    
    onLocationChanged(oldLocation);
    
// fire VisChanged and Appearance/Disappearance signals
    updateCalculatedVisibility(wasVisible);
    
    if (m_location) addToLocation();    
}

void Entity::addToLocation()
{
    assert(!m_location->hasChild(m_id));
    m_location->addChild(this);
}

void Entity::removeFromLocation()
{
    assert(m_location->hasChild(m_id));
    m_location->removeChild(this);
}

#pragma mark -

void Entity::buildEntityDictFromContents(IdEntityMap& dict)
{
    for (unsigned int C=0; C < m_contents.size(); ++C) {
        Entity* child = m_contents[C];
        dict[child->getId()] = child;
    }
}

void Entity::setContentsFromAtlas(const StringList& contents)
{
// convert existing contents into a map, for fast membership tests
    IdEntityMap oldContents;
    buildEntityDictFromContents(oldContents);
    
// iterate over new contents
    for (StringList::const_iterator I=contents.begin(); I != contents.end(); ++I) {
        Entity* child = NULL;
        
        IdEntityMap::iterator J = oldContents.find(*I);
        if (J != oldContents.end()) {
            child = J->second;
            assert(child->getLocation() == this);
            oldContents.erase(J);
        } else {
            child = m_view->getEntity(*I);
            if (!child) {
                // we don't have the entity at all, so request it and skip
                // processing it here; everything will come right when it
                // arrives.
                m_view->getEntityFromServer(*I);
                continue;
            }
            
            if (child->m_limbo) {
                assert(child->m_visible == false);
                child->m_limbo = false;
            } else if (child->isVisible()) {
                // server has gone mad, it has a location, and it's visible
                error() << "got set of contents, specifying child " << child
                    << " which is currently visible in another location";
                continue;
            }
            
            /* we have found the child, update it's location */
            child->setLocation(this);
        }
    
        child->setVisible(true);
    } // of contents list iteration
    
// mark previous contents which are not in new contents as invisible
    for (IdEntityMap::const_iterator J = oldContents.begin(); J != oldContents.end(); ++J) {
        J->second->setVisible(false);
    }
}

bool Entity::hasChild(const std::string& eid) const
{
    for (EntityArray::const_iterator C=m_contents.begin(); C != m_contents.end(); ++C) {
        if ((*C)->getId() == eid) return true;
    }
    
    return false;
}

void Entity::addChild(Entity* e)
{
    m_contents.push_back(e);
    onChildAdded(e);
    assert(e->getLocation() == this);
}

void Entity::removeChild(Entity* e)
{
    assert(e->getLocation() == this);
    
    for (EntityArray::iterator C=m_contents.begin(); C != m_contents.end(); ++C)
    {
        if (*C == e)
        {
            m_contents.erase(C);
            onChildRemoved(e);
            return;
        }
    }
        
   error() << "child " << e->getId() << " of entity " << m_id << " not found doing remove";
}

#pragma mark -
// visiblity related methods

void Entity::setVisible(bool vis)
{
    // force visibility to false if in limbo; necessary for the character entity,
    // which otherwise gets double appearances on activation
    if (m_limbo) vis = false;
    
    bool wasVisible = isVisible(); // store before we update m_visible
    m_visible = vis;

    updateCalculatedVisibility(wasVisible);
}

bool Entity::isVisible() const
{
    if (m_limbo) return false;
    
    if (m_location)
        return m_visible && m_location->isVisible();
    else
        return m_visible; // only for the root entity
}

void Entity::updateCalculatedVisibility(bool wasVisible)
{
    bool nowVisible = isVisible();
    if (nowVisible == wasVisible) return;
    
    /* the following code looks odd, so remember that only one of nowVisible and
    wasVisible can ever be true. The structure is necesary so that we fire
    Appearances top-down, but Disappearances bottom-up. */
    
    if (nowVisible) {
        m_view->setEntityVisible(this, true);
        onVisibilityChanged(true);
    }
    
    for (unsigned int C=0; C < m_contents.size(); ++C)
    {
        /* in case this isn't clear; if we were visible, then child visibility
        was simply it's locally set value; if we were invisible, that the
        child must also have been invisible too. */
        bool childWasVisible = wasVisible ? m_contents[C]->m_visible : false;
        m_contents[C]->updateCalculatedVisibility(childWasVisible);
    }
    
    if (wasVisible) {
        m_view->setEntityVisible(this, false);
        onVisibilityChanged(false);
    }
}

void Entity::onVisibilityChanged(bool vis)
{
    VisibilityChanged.emit(vis);
}

void Entity::createAlarmExpired()
{
    m_recentlyCreated = false;
}

} // of namespace