Mangos code reading

Source: Internet
Author: User
Tags random seed vc9
Mangos code reading

15:51:07 | category: mangos research | report | font size subscription

Logic layer: the world class implements wow world and all logic processing.
Download, compile, configure, and run mangos. Download and install msysgit. For code management, we use git-
Download and install tortoisegit for code management I'm using TortoiseGit-
Use git: // extract mangoscode from github.
Clone existing repository using the git gui tool to get the mangos code (my version is 9560. Refer to this for installation of UDB)
Use git: // extract scriptdev2code from github.
Use the clone existing repository of the git gui tool to obtain the scriptdev2 code.
Compile mangos. I used vc9 to open mangoswinmangosdvc90.sln for construction. After the construction is complete, the mangosbinwin32_debug folder will be obtained.
Compile scriptdev2. I use vc9 and open mangoswinscriptdev2vc90. sln for construction. After the construction is complete, the scriptdev2binwin32_debug folder will be obtained. For details, refer
Copy mangosd. conf. Dist. In from the mangossrcmangosd directory to mangosbinwin32_debugmangosd.conf.
Copy realmd. conf. Dist. In under the mangossrcrealmd directory to mangosbinwin32_debugrealmd.conf.
Download and install the wowserver from upgrade it to the latest version. What I use is wow 3.3.2 build 11403.
The mangos tool ad is used to extract the map from the mpq of wow and obtain all the map data files. The file naming convention is map_id (3 bits) tiley (2 bits) tilex (2 bits ). map. If the file name is, it indicates Azeroth (map id is 000, tile coordinate is (35,20 ). note: The Tile of the wow client corresponds to the grid in the mangos, And the chunk of the wow client corresponds to the cell (1 cell = 4 chunk) in the mangos)
Run the server according to the general process (including database creation and server configuration), create an account using account create zzh1234567, and set account set gmlevel zzh1234567 to Super User
After configuring the client, run wow and log on smoothly.
Full dB 9560: Here is a wide array of scenarios by installing UDB. When I installed db9560, I found that the creature template Addons loading error occurred when mangos was loadcreatureaddons, mangos only requires creature template Addons to have seven fields, while creature template Addons has nine fields. Now I just simply skip the call of loadcreatureaddons.

Run mangos (run mangos expired, which is the previous installation configuration for China server 3.1.3). Use the mangos tool ad to extract map from mpq of wow, for all the map data files, the file naming convention is map_id (3 bits) tiley (2 bits) tilex (2 bits ). map. If the file name is, it indicates Azeroth (map id is 000, tile coordinate is (35,20 ). note: The Tile of the wow client corresponds to the grid in the mangos, And the chunk of the wow client corresponds to the cell (1 cell = 4 chunk) in the mangos)
After configuring the client, run wow and log on smoothly.

Mangos code reading
Mangos has 13 projects
Four external tool libraries are used: cross-platform network communication framework the Adaptive Communication Environment (ACE)
Compressed library zlib
Socket communication library C ++ sockets Library (used in the realmd project, and used in the rasocket in the mangosd project, responsible for processing remote administration where this c ++ sockets library is not used elsewhere) it is found that there is a problem in the tcpsocket: Open of C ++ sockets library. After the n = connect (S, AD, AD); statement is executed, if n =-1, c ++ sockets library checks whether err is wsaewouldblock; otherwise, it indicates success. But when tcpsocket is used in the dynamic library, I found n = connect (S, AD, AD ); after the statement is executed, n =-1 and err will be 0. At this time, the connection is successful, but tcpsocket: Open will handle this problem as unsuccessful, but there is no time to explore the cause, maybe it is not a problem
C ++ parallel programming template library threading building blocks (TBB and tbbmalloc)
The implementation of mangos is divided into: Login Server (realmd) and World server (mangosd + game) realmd and mangos share the mangos Public Library (shared)
Project shared
Provides common functions, including database encapsulation classes, and enables access to MySQL. Similarly, we can compile a derived class to support other databases.
Engineering script
Provides the script interface and implements several simple scripts, which are encapsulated as DLL and provided for game use. For details, see mangos script interface.
By using different script DLL to replace the share DLL, game can have a stronger aiscriptdev2 is such a library scriptdev2 is a replacement for the script library that comes with mangos ( written in C ++ and is compatible with Windows and Linux. it provides scripts for NPCs, boss events, and items currently. once scriptdev2 is compiled it is automatically run by mangos on server startup.

Engineering mangosd
Mangos is the manager of the world server and is responsible for initializing and starting threads at all layers of the world server. These tasks are mainly implemented by the class master: use the three database objects worlddatabase, characterdatabase, and logindatabase to initialize the three databases: World Database, character database, and login database, a DB delay threads is enabled for each database access. The specific database operation function is provided by the mangos public database shared.
Call sworld. setinitialworldsettings: initializes the world, including loading all game data and Initializing Various update timers and email timers. Some other initialization work class world member functions setinitialworldsettings call the member function loadconfigsettings to parse mangosd. conf. The parsed content is placed in uint32 m_configs [config_value_count ].
The loaded game data includes:
DBC data
Objects data
Spells data
Pooling data
Game event data
Loot data
Skill data
All other game data, including waypoints and trainers
Script data
Other initialization tasks include:
Initialize mapmanager and start Map System
Initialize battlegrounds and start battleground System
Initialize dailyquestresettime
Initialize sgameeventmgr, starting game Event System
Class master starts worldrunnable and starts the game logic heartbeat for the world. It is created by the master and sets the thread to the highest priority.
Class master starts clirunnable: command line interface handling thread. When a clirunnable is created by the master, a worlddatabase thread is generated during the run. After receiving the input, sworld is called. queueclicommand puts CMD in world: clicmdqueue
Mangosd threads have a total of (1 + 3 + 1 + 1 + 1 + 2 + 1 = 10) 10 main threads master
2 network threads reactorrunnable (configurable number) (Network Layer)
One World thread (logical layer)
Three dB threads (data layer)
A cli thread (input layer) will generate a worlddatabase thread during runtime
One Ra thread (management layer)
A freeze catcher thread (optional)
Engineering g3dlite: underlying library of the game logic layer
Engineering Framework: System Framework
Engineering realm
Log on to and select the game server, perform load balancing, use the C ++ sockets library for login, and use the select I/O model to implement wow, when a mangos user logs on, the srp6 authentication client acts as its client to connect to the realm Server Authentication. If the mangos server is selected, the client is disconnected, while the mangos server and the realm server are not connected, but the data is interacted through the database: the mangos Server puts its status and number of roles into the database. The realm server reads the information in the database to learn the realmlist table of the State database realm of the mangos server. The realm list is saved.
Realm logs on to and selects game servers using the following event processing functions
Const authhandler table [] =
{Auth_logon_challenge, status_connected, & authsocket: _ handlelogonchallenge },
{Auth_logon_proof, status_connected, & authsocket: _ handlelogonproof },
{Auth_reconnect_challenge, status_connected, & authsocket: _ handlereconnectchallenge },
{Auth_reconnect_proof, status_connected, & authsocket: _ handlereconnectproof },
{Realm_list, status_authed, & authsocket: _ handlerealmlist },
{Xfer_accept, status_connected, & authsocket: _ handlexferaccept },
{Xfer_resume, status_connected, & authsocket: _ handlexferresume },
{Xfer_cancel, status_connected, & authsocket: _ handlexfercancel}
}; Logon handling:
The user logs on to the realm server for identity authentication, and selects the mangos serveruser to log on to the mangos server. After logging on, the user no longer interacts with the realm server.
Reference: Wow Server Resolution
Engineering game
Game: The Core code of mangos. The network layer and logic layer code (using the ace reactor Mode)
Network Layer: worldsocket: Responsible for network I/O, while worldsession is responsible for logical processing. worldsocket and worldsession run in independent threads reactorrunnable and worldrunnable respectively, the message queue _ recvqueue in worldsession is used for data buffering. After worldsocket receives the netstore input, it calls m_session-> queuepacket (new_pct). The Network Package is placed in the _ recvqueue of worldsession, we can see that worldsocket is the network layer of mangos game, while worldsession is the logic processing layer worldsocketmgr is a manager at the network layer. It is responsible for assigning the reactorrunnable management to which worldsocket belongs (mangos can create multiple reactorrunnable, 2 by default)
Worldsocketmgr (manages all sockets connected to peers and network threads) manages the worldsocketmgr: startnetwork of worldsocketworldsocketmgr to listen to the 8085 (default) port in the world :: loop processing in update includes:
Refresh update Timer
Refresh game timer and handle game Shutdown
Process routine tasks
Deal with the auction
Refreshing sessionsworld: updatesessions will call worldsession: update of all worldsessions for logical processing in worldsession: update.
Handling weather
Refresh uptime table
Refresh objects, including maps, transport, creatures ,,,,
Refresh all running battlegrounds
Refresh sqlresultqueue. The logic layer and data layer perform asynchronous operations through Queue (asyncpquery and sqlresultqueue are used)
Process corpse Removal
Handle game events
Process move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
Refresh instancesavemanager
You can call World: processclicommands to obtain cmd from clicmdqueue from CLI for parsing and executing all valid cmd statements, which can be found in chathandler: getcommandtable.
Class worldsession: Class worldsession is responsible for logical processing.
Void worldsession: sendpacket (worldpacket const * packet) is responsible for sending packets to the client and sending packets directly without an output buffer queue.
Logic processing in worldsession: update world: updatesessions will call worldsession: update of all worldsessions
Run opcodehandler & ophandle = opcodetable [packet-> getopcode ()];
Execute (this-> * ophandle. Handler) (* packet) according to the obtained ophandle );
Worldsession: handleplayerlogin
Build player
PLAYER: loadfromdb loads player data from the database. In PLAYER: loadfromdb, setmap (mapmanager: instance () is called (). createmap (getmapid (), this); load the map of the current player
PLAYER: When setposition is in the player motion, change the position and save and process the boast area.
Class map implements a state machine and uses state pattern to organize four State objects of GID: invalidstate; ActiveState; idlestate; removalstate
The managers in game include: objectmgr
Mmangosstringlocalemap is associated with mangos_string table
M_scriptnames is associated with tables: creature_template; gameobject_template; item_templat E; areatrigger_scripts; instance_template
Mcreaturelocalemap is associated with locales_creature table
Mgameobjectlocalemap is associated with locales_gameobject table
Mitemlocalemap is associated with locales_item table
Mquestlocalemap-> locales_quest
Mnpctextlocalemap-> locales_npc_text
Mpagetextlocalemap-> locales_page_text
Mgossipmenuitemslocalemap-> locales_gossip_menu_option
Mpointofinterestlocalemap-> locales_points_of_interest
Object class hierarchy
The class hierarchy of the object is as follows. All objects are managed by objectmgr. objectmgr manages characters, creature, item_instance, gameobject, auctionhouse, mail, item_text, corpse, arena_team, character_equipmentsets in guid mode.


Player status
/// Player state
Enum sessionstatus
Status_authed = 0, // <player authenticated (_ player = NULL, m_playerrecentlylogout = false or will be reset before handler call, m_guid have garbage)
Status_loggedin, // <player in game (_ player! = NULL, m_guid = _ player-> getguid (), inworld ())
Status_transfer, // <player transferring to another map (_ player! = NULL, m_guid = _ player-> getguid (),! Inworld ())
Status_loggedin_or_recently_loggout, // <_ player! = NULL or _ player = NULL & m_playerrecentlylogout, m_guid store last _ player guid)
Status_never // <opcode not accepted from client (deprecated or server side only)
Biological status
Enum deathstate
Alive = 0,
Just_died = 1,
Corpse = 2,
Dead = 3,
Just_alived = 4,
Dead_falling = 5
Player Login
After the connection is enabled, the server sends smsg_auth_challenge to the seed sent from the client from the server and the srp6 data to generate random seed, generate the sha1 string, and use the data to generate the cmsg_auith_session packet, the process of sending data to the server is not encrypted.
The client sends smsg_auth_session to the server.
Server processing smsg_auth_session
The server sends smsg_auth_response to the client.
The server sends smsg_addon_info to the client.
The server sends the smsg_clientcache_version to the client.
The server sends smsg_tutorial_flags to the client.
The packet structure smsg_auth_session is a client packet with a header (clientpktheader) followed by a data block.
Smsg_auth_response is a server packet with a header (servicepktheader) followed by a data block.
Packet organization of smsg_auth_response
The opcode of smsg_auth_response is 01ee, And the bytebuffer size is 1 + 4 + 1 + 4 + 1 = 11. The data of a smsg_auth_response is as follows: After smsg_auth_response packet is constructed, worldsocket :: sendpacket constructs a serverpktheader Based on smsg_auth_response packet and encrypts and sends data headers in serverpktheader using m_crypt.encryptsend (uint8 *) header. header, header. getheaderlength (); worldsocket: handle_input_header decrypts the data received from the client. The decryption uses m_crypt.decryptrecv (uint8 *) m_header.rd_ptr (), sizeof (clientpktheader ));
Role enumeration: After a player is on the server, it sends smsg_char_enum from the client to the server.
On the server side
According to {"cmsg_char_enum", status_authed, & worldsession: handlecharenumopcode}, the server will call worldsession: handlecharenumopcode
Worldsession: handlecharenumopcode will call characterdatabase. asyncpquery for asynchronous query, and then call characterhandler: handlecharenumcallback
Characterhandler: handlecharenumcallback will call session-> handlecharenum (result );
Worldsession: handlecharenum Based on the query results of the characters database, call PLAYER: buildenumdata to load role data, construct the smsg_char_enum return package, and send it back to the client.
Role creation

The role is initialized in charstartoutfit. DBC
The role creation and selection settings are in chrraces. DBC.
All created attributes of a role are in playercreateinfo, including the location and birth attributes.
The playercreateinfo_spell table is the table of all spell contained by the character by default when a new character is created.
Delete role

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.