summaryrefslogtreecommitdiffstats
path: root/src/game-server/mapcomposite.cpp
blob: 4a5d800ee9b5c9ef8b4ade4b70360a9ae7a6d68f (plain)
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
/*
 *  The Mana Server
 *  Copyright (C) 2006-2010  The Mana World Development Team
 *  Copyright (C) 2010-2012  The Mana Development Team
 *
 *  This file is part of The Mana Server.
 *
 *  The Mana Server 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
 *  any later version.
 *
 *  The Mana Server 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 The Mana Server.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <algorithm>
#include <cassert>

#include "accountconnection.h"
#include "common/configuration.h"
#include "common/resourcemanager.h"
#include "game-server/character.h"
#include "game-server/combatcomponent.h"
#include "game-server/mapcomposite.h"
#include "game-server/map.h"
#include "game-server/mapmanager.h"
#include "game-server/mapreader.h"
#include "game-server/monstermanager.h"
#include "game-server/spawnareacomponent.h"
#include "game-server/triggerareacomponent.h"
#include "scripting/script.h"
#include "scripting/scriptmanager.h"
#include "utils/logger.h"
#include "utils/point.h"

/* TODO: Implement overlapping map zones instead of strict partitioning.
   Purpose: to decrease the number of zone changes, as overlapping allows for
   hysteresis effect and prevents an actor from changing zone each server
   tick. It requires storing the zone in the actor since it will not be
   uniquely defined any longer. */

/* Pixel-based width and height of the squares used in partitioning the map.
   Squares should be big enough so that an actor cannot cross several ones
   in one world tick.
   TODO: Tune for decreasing server load. The higher the value, the closer we
   regress to quadratic behavior; the lower the value, the more we waste time
   in dealing with zone changes. */
static int const zoneDiam = 256;

void MapZone::insert(Entity *obj)
{
    int type = obj->getType();
    switch (type)
    {
        case OBJECT_CHARACTER:
        {
            if (nbCharacters != nbMovingObjects)
            {
                if (nbMovingObjects != objects.size())
                {
                    objects.push_back(objects[nbMovingObjects]);
                    objects[nbMovingObjects] = objects[nbCharacters];
                }
                else
                {
                    objects.push_back(objects[nbCharacters]);
                }
                objects[nbCharacters] = obj;
                ++nbCharacters;
                ++nbMovingObjects;
                break;
            }
            ++nbCharacters;
        } // no break!
        case OBJECT_MONSTER:
        case OBJECT_NPC:
        {
            if (nbMovingObjects != objects.size())
            {
                objects.push_back(objects[nbMovingObjects]);
                objects[nbMovingObjects] = obj;
                ++nbMovingObjects;
                break;
            }
            ++nbMovingObjects;
        } // no break!
        default:
        {
            objects.push_back(obj);
            break;
        }
    }
}

void MapZone::remove(Entity *obj)
{
    std::vector< Entity * >::iterator i_beg = objects.begin(), i, i_end;
    int type = obj->getType();
    switch (type)
    {
        case OBJECT_CHARACTER:
        {
            i = i_beg;
            i_end = objects.begin() + nbCharacters;
        } break;
        case OBJECT_MONSTER:
        case OBJECT_NPC:
        {
            i = objects.begin() + nbCharacters;
            i_end = objects.begin() + nbMovingObjects;
        } break;
        default:
        {
            i = objects.begin() + nbMovingObjects;
            i_end = objects.end();
            break;
        }
    }
    i = std::find(i, i_end, obj);
    assert(i != i_end);
    unsigned pos = i - i_beg;
    if (pos < nbCharacters)
    {
        objects[pos] = objects[nbCharacters - 1];
        pos = nbCharacters - 1;
        --nbCharacters;
    }
    if (pos < nbMovingObjects)
    {
        objects[pos] = objects[nbMovingObjects - 1];
        pos = nbMovingObjects - 1;
        --nbMovingObjects;
    }
    objects[pos] = objects[objects.size() - 1];
    objects.pop_back();
}

static void addZone(MapRegion &r, unsigned z)
{
    MapRegion::iterator i_end = r.end(),
                        i = std::lower_bound(r.begin(), i_end, z);
    if (i == i_end || *i != z)
    {
        r.insert(i, z);
    }
}

ZoneIterator::ZoneIterator(const MapRegion &r, const MapContent *m)
  : region(r), pos(0), map(m)
{
    current = &map->zones[r.empty() ? 0 : r[0]];
}

void ZoneIterator::operator++()
{
    current = nullptr;
    if (!region.empty())
    {
        if (++pos != region.size())
        {
            current = &map->zones[region[pos]];
        }
    }
    else
    {
        if (++pos != (unsigned)map->mapWidth * map->mapHeight)
        {
            current = &map->zones[pos];
        }
    }
}

CharacterIterator::CharacterIterator(const ZoneIterator &it)
  : iterator(it), pos(0)
{
    while (iterator && (*iterator)->nbCharacters == 0) ++iterator;
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}

void CharacterIterator::operator++()
{
    if (++pos == (*iterator)->nbCharacters)
    {
        do ++iterator; while (iterator && (*iterator)->nbCharacters == 0);
        pos = 0;
    }
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}

BeingIterator::BeingIterator(const ZoneIterator &it)
  : iterator(it), pos(0)
{
    while (iterator && (*iterator)->nbMovingObjects == 0) ++iterator;
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}

void BeingIterator::operator++()
{
    if (++pos == (*iterator)->nbMovingObjects)
    {
        do ++iterator; while (iterator && (*iterator)->nbMovingObjects == 0);
        pos = 0;
    }
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}

FixedActorIterator::FixedActorIterator(const ZoneIterator &it)
  : iterator(it), pos(0)
{
    while (iterator && (*iterator)->nbMovingObjects == (*iterator)->objects.size()) ++iterator;
    if (iterator)
    {
        pos = (*iterator)->nbMovingObjects;
        current = (*iterator)->objects[pos];
    }
}

void FixedActorIterator::operator++()
{
    if (++pos == (*iterator)->objects.size())
    {
        do ++iterator; while (iterator && (*iterator)->nbMovingObjects == (*iterator)->objects.size());
        if (iterator)
        {
            pos = (*iterator)->nbMovingObjects;
        }
    }
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}

ActorIterator::ActorIterator(const ZoneIterator &it)
  : iterator(it), pos(0)
{
    while (iterator && (*iterator)->objects.empty()) ++iterator;
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}

void ActorIterator::operator++()
{
    if (++pos == (*iterator)->objects.size())
    {
        do ++iterator; while (iterator && (*iterator)->objects.empty());
        pos = 0;
    }
    if (iterator)
    {
        current = (*iterator)->objects[pos];
    }
}


/******************************************************************************
 * ObjectBucket
 *****************************************************************************/

ObjectBucket::ObjectBucket()
  : free(256), next_object(0)
{
    for (unsigned i = 0; i < 256 / int_bitsize; ++i)
    {
        // An occupied ID is represented by zero in the bitmap.
        bitmap[i] = ~0u;
    }
}

int ObjectBucket::allocate()
{
    // Any free ID in the bucket?
    if (!free)
    {
        LOG_INFO("No free id in bucket");
        return -1;
    }

    int freeBucket = -1;
    // See if the the next_object bucket is free
    if (bitmap[next_object] != 0)
    {
        freeBucket = next_object;
    }
    else
    {
        /* next_object was not free. Check the whole bucket until one ID is found,
           starting from the IDs around next_object. */
        for (unsigned i = 0; i < 256 / int_bitsize; ++i)
        {
            // Check to see if this subbucket is free
            if (bitmap[i] != 0)
            {
                freeBucket = i;
                break;
            }
        }
    }

    assert(freeBucket >= 0);

    // One of them is free. Find it by looking bit-by-bit.
    int b = bitmap[freeBucket];
    int j = 0;
    while (!(b & 1))
    {
        b >>= 1;
        ++j;
    }
    // Flip that bit to on, and return the value
    bitmap[freeBucket] &= ~(1 << j);
    j += freeBucket * int_bitsize;
    next_object = freeBucket;
    --free;
    return j;
}

void ObjectBucket::deallocate(int i)
{
    assert(!(bitmap[i / int_bitsize] & (1 << (i % int_bitsize))));
    bitmap[i / int_bitsize] |= 1 << (i % int_bitsize);
    ++free;
}


/******************************************************************************
 * MapContent
 *****************************************************************************/

MapContent::MapContent(Map *map)
  : last_bucket(0), zones(nullptr)
{
    buckets[0] = new ObjectBucket;
    buckets[0]->allocate(); // Skip ID 0
    for (int i = 1; i < 256; ++i)
    {
        buckets[i] = nullptr;
    }
    mapWidth = (map->getWidth() * map->getTileWidth() + zoneDiam - 1)
               / zoneDiam;
    mapHeight = (map->getHeight() * map->getTileHeight() + zoneDiam - 1)
                / zoneDiam;
    zones = new MapZone[mapWidth * mapHeight];
}

MapContent::~MapContent()
{
    for (int i = 0; i < 256; ++i)
    {
        delete buckets[i];
    }
    delete[] zones;
}

bool MapContent::allocate(Entity *obj)
{
    // First, try allocating from the last used bucket.
    ObjectBucket *b = buckets[last_bucket];

    auto *actorComponent = obj->getComponent<ActorComponent>();

    int i = b->allocate();
    if (i >= 0)
    {
        b->objects[i] = obj;
        actorComponent->setPublicID(last_bucket * 256 + i);
        return true;
    }

    /* If the last used bucket is already full, scan all the buckets for an
       empty place. If none is available, create a new bucket. */
    for (i = 0; i < 256; ++i)
    {
        b = buckets[i];
        if (!b)
        {
            /* Buckets are created in order. If there is nothing at position i,
               there will not be anything in the next positions. So create a
               new bucket. */
            b = new ObjectBucket;
            buckets[i] = b;
            LOG_DEBUG("New bucket created");
        }
        int j = b->allocate();
        if (j >= 0)
        {
            last_bucket = i;
            b->objects[j] = obj;
            actorComponent->setPublicID(last_bucket * 256 + j);
            return true;
        }
    }

    // All the IDs are currently used, fail.
    LOG_ERROR("unable to allocate id");
    return false;
}

void MapContent::deallocate(Entity *obj)
{
    unsigned short id = obj->getComponent<ActorComponent>()->getPublicID();
    buckets[id / 256]->deallocate(id % 256);
}

void MapContent::fillRegion(MapRegion &r, const Point &p, int radius) const
{
    int ax = p.x > radius ? (p.x - radius) / zoneDiam : 0,
        ay = p.y > radius ? (p.y - radius) / zoneDiam : 0,
        bx = std::min((p.x + radius) / zoneDiam, mapWidth - 1),
        by = std::min((p.y + radius) / zoneDiam, mapHeight - 1);
    for (int y = ay; y <= by; ++y)
    {
        for (int x = ax; x <= bx; ++x)
        {
            addZone(r, x + y * mapWidth);
        }
    }
}

void MapContent::fillRegion(MapRegion &r, const Rectangle &p) const
{
    int ax = p.x / zoneDiam,
        ay = p.y / zoneDiam,
        bx = std::min((p.x + p.w) / zoneDiam, mapWidth - 1),
        by = std::min((p.y + p.h) / zoneDiam, mapHeight - 1);
    for (int y = ay; y <= by; ++y)
    {
        for (int x = ax; x <= bx; ++x)
        {
            addZone(r, x + y * mapWidth);
        }
    }
}

MapZone& MapContent::getZone(const Point &pos) const
{
    return zones[(pos.x / zoneDiam) + (pos.y / zoneDiam) * mapWidth];
}


/******************************************************************************
 * MapComposite
 *****************************************************************************/

Script::Ref MapComposite::mInitializeCallback;
Script::Ref MapComposite::mUpdateCallback;

MapComposite::MapComposite(int id, const std::string &name):
    mActive(false),
    mMap(0),
    mContent(0),
    mName(name),
    mID(id),
    mPvPRules(PVP_NONE)
{
}

MapComposite::~MapComposite()
{
    delete mMap;
    delete mContent;
}

bool MapComposite::readMap()
{
    std::string file = "maps/" + mName + ".tmx";

    mMap = MapReader::readMap(file);
    return mMap;
}

bool MapComposite::activate()
{
    assert(!isActive());

    if (!mMap)
        return false;

    initializeContent();

    std::string sPvP = mMap->getProperty("pvp");
    if (sPvP.empty())
        sPvP = Configuration::getValue("game_defaultPvp", std::string());

    if (sPvP == "free")
        mPvPRules = PVP_FREE;
    else
        mPvPRules = PVP_NONE;

    mActive = true;

    if (!mInitializeCallback.isValid())
    {
        LOG_WARN("No callback for map initialization found");
    }
    else
    {
        Script *s = ScriptManager::currentState();
        s->prepare(mInitializeCallback);
        s->execute(this);
    }

    return true;
}

ZoneIterator MapComposite::getAroundPointIterator(const Point &p, int radius) const
{
    MapRegion r;
    mContent->fillRegion(r, p, radius);
    return ZoneIterator(r, mContent);
}

ZoneIterator MapComposite::getAroundActorIterator(Entity *obj, int radius) const
{
    MapRegion r;
    mContent->fillRegion(r, obj->getComponent<ActorComponent>()->getPosition(),
                         radius);
    return ZoneIterator(r, mContent);
}

ZoneIterator MapComposite::getInsideRectangleIterator(const Rectangle &p) const
{
    MapRegion r;
    mContent->fillRegion(r, p);
    return ZoneIterator(r, mContent);
}

ZoneIterator MapComposite::getAroundBeingIterator(Entity *obj, int radius) const
{
    MapRegion r1;
    mContent->fillRegion(r1,
                         obj->getComponent<BeingComponent>()->getOldPosition(),
                         radius);
    MapRegion r2 = r1;
    for (MapRegion::iterator i = r1.begin(), i_end = r1.end(); i != i_end; ++i)
    {
        /* Fills region with destinations taken around the old position.
           This is necessary to detect two moving objects changing zones at the
           same time and at the border, and going in opposite directions (or
           more simply to detect teleportations, if any). */
        MapRegion &r4 = mContent->zones[*i].destinations;
        if (!r4.empty())
        {
            MapRegion r3;
            r3.reserve(r2.size() + r4.size());
            std::set_union(r2.begin(), r2.end(), r4.begin(), r4.end(),
                           std::back_insert_iterator< MapRegion >(r3));
            r2.swap(r3);
        }
    }
    mContent->fillRegion(r2,
                         obj->getComponent<ActorComponent>()->getPosition(),
                         radius);
    return ZoneIterator(r2, mContent);
}

bool MapComposite::insert(Entity *ptr)
{
    if (ptr->isVisible())
    {
        if (ptr->canMove() && !mContent->allocate(ptr))
            return false;

        const Point &point =
                ptr->getComponent<ActorComponent>()->getPosition();
        mContent->getZone(point).insert(ptr);
    }

    ptr->setMap(this);
    mContent->entities.push_back(ptr);
    return true;
}

void MapComposite::remove(Entity *ptr)
{
    for (std::vector<Entity*>::iterator i = mContent->entities.begin(),
         i_end = mContent->entities.end(); i != i_end; ++i)
    {
        if ((*i)->canFight())
        {
            if ((*i)->getComponent<CombatComponent>()->getTarget() == ptr)
            {
                (*i)->getComponent<CombatComponent>()->clearTarget();
            }
        }
        if (*i == ptr)
        {
            i = mContent->entities.erase(i);
        }
    }

    if (ptr->isVisible())
    {
        const Point &point =
                ptr->getComponent<ActorComponent>()->getPosition();
        mContent->getZone(point).remove(ptr);

        if (ptr->canMove())
        {
            mContent->deallocate(ptr);
        }
    }
}

void MapComposite::update()
{
    // Update object status
    const std::vector< Entity * > &entities = getEverything();
    for (std::vector< Entity * >::const_iterator it = entities.begin(),
         it_end = entities.end(); it != it_end; ++it)
    {
        (*it)->update();
    }

    if (mUpdateCallback.isValid())
    {
        Script *s = ScriptManager::currentState();
        s->prepare(mUpdateCallback);
        s->push(mID);
        s->execute(this);
    }

    // Move objects around and update zones.
    for (BeingIterator it(getWholeMapIterator()); it; ++it)
    {
        (*it)->getComponent<BeingComponent>()->move(**it);
    }

    for (int i = 0; i < mContent->mapHeight * mContent->mapWidth; ++i)
    {
        mContent->zones[i].destinations.clear();
    }

    // Cannot use a WholeMap iterator as objects will change zones under its feet.
    for (std::vector< Entity * >::iterator i = mContent->entities.begin(),
         i_end = mContent->entities.end(); i != i_end; ++i)
    {
        if (!(*i)->canMove())
            continue;

        const Point &pos1 =
                (*i)->getComponent<BeingComponent>()->getOldPosition();
        const Point &pos2 =
                (*i)->getComponent<ActorComponent>()->getPosition();

        MapZone &src = mContent->getZone(pos1),
                &dst = mContent->getZone(pos2);
        if (&src != &dst)
        {
            addZone(src.destinations, &dst - mContent->zones);
            src.remove(*i);
            dst.insert(*i);
        }
    }
}

const std::vector< Entity * > &MapComposite::getEverything() const
{
    return mContent->entities;
}


std::string MapComposite::getVariable(const std::string &key) const
{
    std::map<std::string, std::string>::const_iterator i = mScriptVariables.find(key);
    if (i != mScriptVariables.end())
        return i->second;
    else
        return std::string();
}

void MapComposite::setVariable(const std::string &key, const std::string &value)
{
    // check if the value actually changed
    std::map<std::string, std::string>::iterator i = mScriptVariables.find(key);
    if (i == mScriptVariables.end() || i->second != value)
    {
        // changed value or unknown variable
        mScriptVariables[key] = value;
        callMapVariableCallback(key, value);
        // update accountserver
        accountHandler->updateMapVar(this, key, value);
    }
}

static void callVariableCallback(Script::Ref &function, const std::string &key,
                                 const std::string &value, MapComposite *map)
{
    if (function.isValid())
    {
        Script *s = ScriptManager::currentState();
        s->prepare(function);
        s->push(key);
        s->push(value);
        s->execute(map);
    }
}

void MapComposite::callMapVariableCallback(const std::string &key,
                                           const std::string &value)
{
    std::map<const std::string, Script::Ref>::iterator it =
            mMapVariableCallbacks.find(key);
    if (it == mMapVariableCallbacks.end())
        return;
    callVariableCallback(it->second, key, value, this);
}

void MapComposite::callWorldVariableCallback(const std::string &key,
                                             const std::string &value)
{
    std::map<const std::string, Script::Ref>::iterator it =
            mWorldVariableCallbacks.find(key);
    if (it == mWorldVariableCallbacks.end())
        return;
    callVariableCallback(it->second, key, value, this);
}

/**
 * Finds a map object by its name and type.
 * Name and type are case insensitive.
 */
const MapObject *MapComposite::findMapObject(const std::string &name,
                                             const std::string &type) const
{
    const std::vector<MapObject *> &destObjects = mMap->getObjects();
    std::vector<MapObject *>::const_iterator it, it_end;
    for (it = destObjects.begin(), it_end = destObjects.end();
         it != it_end; ++it)
    {
        const MapObject *obj = *it;
        if (utils::compareStrI(obj->getType(), type) == 0 &&
            utils::compareStrI(obj->getName(), name) == 0)
        {
            return obj;
        }
    }
    return 0; // nothing found
}

/**
 * Initializes the map content. This creates the warps, spawn areas, npcs and
 * other scripts.
 */
void MapComposite::initializeContent()
{
    mContent = new MapContent(mMap);

    const std::vector<MapObject *> &objects = mMap->getObjects();

    for (size_t i = 0; i < objects.size(); ++i)
    {
        const MapObject *object = objects.at(i);
        const std::string &type = object->getType();

        if (utils::compareStrI(type, "WARP") == 0)
        {
            std::string destMapName = object->getProperty("DEST_MAP");
            std::string destMapObjectName = object->getProperty("DEST_NAME");

            MapComposite *destMap = MapManager::getMap(destMapName);
            int destX = 0;
            int destY = 0;

            if (destMap && !destMapObjectName.empty())
            {
                const MapObject *obj =
                        destMap->findMapObject(destMapObjectName, "WARP");
                if (obj)
                {
                    const Rectangle &rect = obj->getBounds();
                    destX = rect.x + rect.w / 2;
                    destY = rect.y + rect.h / 2;
                }
                else
                {
                    LOG_ERROR("Warp target \"" << destMapObjectName << "\" "
                              << "was not found on the map "
                              << destMap->getName());
                }
            }
            else
            {
                destX = utils::stringToInt(object->getProperty("DEST_X"));
                destY = utils::stringToInt(object->getProperty("DEST_Y"));
            }


            if (destMap && destX && destY)
            {
                Entity *entity = new Entity(OBJECT_OTHER, this);
                const Point warpTarget(destX, destY);
                WarpAction *action = new WarpAction(destMap, warpTarget);
                entity->addComponent(
                            new TriggerAreaComponent(object->getBounds(),
                                                     action, false));
                insert(entity);
            }
            else
            {
                LOG_WARN("Unrecognized warp format on map " << mName);
            }
        }
        else if (utils::compareStrI(type, "SPAWN") == 0)
        {
            MonsterClass *monster = 0;
            int maxBeings = utils::stringToInt(object->getProperty("MAX_BEINGS"));
            int spawnRate = utils::stringToInt(object->getProperty("SPAWN_RATE"));
            std::string monsterName = object->getProperty("MONSTER_ID");
            int monsterId = utils::stringToInt(monsterName);

            if (monsterId)
            {
                monster = monsterManager->getMonster(monsterId);
                if (!monster)
                {
                    LOG_WARN("Couldn't find monster ID " << monsterId <<
                             " for spawn area");
                }
            }
            else
            {
                monster = monsterManager->getMonsterByName(monsterName);
                if (!monster)
                {
                    LOG_WARN("Couldn't find monster " << monsterName <<
                             " for spawn area");
                }
            }

            if (monster && maxBeings && spawnRate)
            {
                Entity *entity = new Entity(OBJECT_OTHER, this);
                SpawnAreaComponent *spawnArea =
                        new SpawnAreaComponent(monster, object->getBounds(),
                                               maxBeings, spawnRate);

                entity->addComponent(spawnArea);
                insert(entity);
            }
        }
        else if (utils::compareStrI(type, "NPC") == 0)
        {
            int npcId = utils::stringToInt(object->getProperty("NPC_ID"));
            std::string gender = object->getProperty("GENDER");
            std::string scriptText = object->getProperty("SCRIPT");

            if (npcId && !scriptText.empty())
            {
                Script *script = ScriptManager::currentState();
                script->loadNPC(object->getName(), npcId,
                                ManaServ::getGender(gender),
                                object->getX(), object->getY(),
                                scriptText.c_str(), this);
            }
            else
            {
                LOG_WARN("Unrecognized format for npc");
            }
        }
        else if (utils::compareStrI(type, "SCRIPT") == 0)
        {
            std::string scriptFilename = object->getProperty("FILENAME");
            std::string scriptText = object->getProperty("TEXT");

            Script *script = ScriptManager::currentState();
            Script::Context context;
            context.map = this;

            if (!scriptFilename.empty())
            {
                script->loadFile(scriptFilename, context);
            }
            else if (!scriptText.empty())
            {
                std::string name = "'" + object->getName() + "'' in " + mName;
                script->load(scriptText.c_str(), name.c_str(), context);
            }
            else
            {
                LOG_WARN("Unrecognized format for script");
            }
        }
    }
}