예제 #1
0
int32_t NpcScriptInterface::luaOpenShopWindow(lua_State* L)
{
	//openShopWindow(cid, items, onBuy callback, onSell callback)
	int32_t sellCallback;
	if (lua_isfunction(L, -1) == 0) {
		sellCallback = -1;
		lua_pop(L, 1);    // skip it - use default value
	} else {
		sellCallback = popCallback(L);
	}

	int32_t buyCallback;
	if (lua_isfunction(L, -1) == 0) {
		buyCallback = -1;
		lua_pop(L, 1);    // skip it - use default value
	} else {
		buyCallback = popCallback(L);
	}

	if (lua_istable(L, -1) == 0) {
		reportError(__FUNCTION__, "item list is not a table.");
		pushBoolean(L, false);
		return 1;
	}

	std::list<ShopInfo> items;
	lua_pushnil(L);
	while (lua_next(L, -2) != 0) {
		const int32_t tableIndex = lua_gettop(L);
		ShopInfo item;

		item.itemId = getField<uint32_t>(L, tableIndex, "id");
		item.subType = getField<int32_t>(L, tableIndex, "subType");
		if (item.subType == 0) {
			item.subType = getField<int32_t>(L, tableIndex, "subtype");
			lua_pop(L, 1);
		}

		item.buyPrice = getField<uint32_t>(L, tableIndex, "buy");
		item.sellPrice = getField<uint32_t>(L, tableIndex, "sell");
		item.realName = getFieldString(L, tableIndex, "name");

		items.push_back(item);
		lua_pop(L, 6);
	}
	lua_pop(L, 1);

	Player* player = getPlayer(L, -1);
	if (!player) {
		reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
		pushBoolean(L, false);
		return 1;
	}

	//Close any eventual other shop window currently open.
	player->closeShopWindow(false);

	Npc* npc = getScriptEnv()->getNpc();
	if (!npc) {
		reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
		pushBoolean(L, false);
		return 1;
	}

	npc->addShopPlayer(player);
	player->setShopOwner(npc, buyCallback, sellCallback);
	player->openShopWindow(npc, items);

	pushBoolean(L, true);
	return 1;
}
예제 #2
0
파일: npc.cpp 프로젝트: Badhu/PokeB-Distro
int32_t NpcScriptInterface::luaNpcOpenShopWindow(lua_State* L)
{
	// npc:openShopWindow(cid, items, buyCallback, sellCallback)
	if (!isTable(L, 3)) {
		reportErrorFunc("item list is not a table.");
		pushBoolean(L, false);
		return 1;
	}

	Player* player = getPlayer(L, 2);
	if (!player) {
		reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
		pushBoolean(L, false);
		return 1;
	}

	Npc* npc = getUserdata<Npc>(L, 1);
	if (!npc) {
		reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND));
		pushBoolean(L, false);
		return 1;
	}

	int32_t sellCallback = -1;
	if (isFunction(L, 5)) {
		sellCallback = luaL_ref(L, LUA_REGISTRYINDEX);
	}

	int32_t buyCallback = -1;
	if (isFunction(L, 4)) {
		buyCallback = luaL_ref(L, LUA_REGISTRYINDEX);
	}

	std::list<ShopInfo> items;

	pushNil(L);
	while (lua_next(L, 3) != 0) {
		ShopInfo item;
		item.itemId = popField<uint32_t>(L, "id");
		item.subType = popField<int32_t>(L, "subType");
		if (item.subType == 0) {
			item.subType = popField<int32_t>(L, "subtype");
		}

		item.buyPrice = popField<uint32_t>(L, "buy");
		item.sellPrice = popField<uint32_t>(L, "sell");
		item.realName = popFieldString(L, "name");

		items.push_back(item);
		lua_pop(L, 1);
	}
	lua_pop(L, 1);

	player->closeShopWindow(false);
	npc->addShopPlayer(player);

	player->setShopOwner(npc, buyCallback, sellCallback);
	player->openShopWindow(npc, items);

	pushBoolean(L, true);
	return 1;
}
예제 #3
0
string SoundPlugin::fullName(const char *name)
{
    string sound;
    if ((name == NULL) || (*name == 0))
        return sound;
#ifdef WIN32
    char c = name[0];
    if (((((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'))) && (name[1] == ':')) ||
            ((c == '\\') && (name[1] == '\\'))){
#else
    if (name[0] == '/'){
#endif
        sound = name;
    }else{
        sound = "sounds/";
        sound += name;
        sound = app_file(sound.c_str());
    }
    return sound;
}

void SoundPlugin::playSound(const char *s)
{
    if ((s == NULL) || (*s == 0))
        return;
    string sound = fullName(s);
    // check whether file is available
    if (!QFile::exists(QString(sound.c_str())))
        return;
#ifdef WIN32
    sndPlaySoundA(sound.c_str(), SND_ASYNC | SND_NODEFAULT);
#else
#ifdef USE_KDE
    if (getUseArts()){
        KAudioPlayer::play(sound.c_str());
        return;
    }
#endif
    ExecParam p;
    p.cmd = getPlayer();
    p.arg = sound.c_str();
    Event e(EventExec, &p);
    e.process();
#endif
}

#ifdef WIN32

/**
 * DLL's entry point
 **/
int WINAPI DllMain(HINSTANCE, DWORD, LPVOID)
{
    return TRUE;
}

/**
 * This is to prevent the CRT from loading, thus making this a smaller
 * and faster dll.
 **/
extern "C" BOOL __stdcall _DllMainCRTStartup( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    return DllMain( hinstDLL, fdwReason, lpvReserved );
}
예제 #4
0
static void handleCharWarp(Character *player, std::string &args)
{
    int x, y;
    MapComposite *map;
    Character *other;

    // get the arguments
    std::string character = getArgument(args);
    std::string mapstr = getArgument(args);
    std::string xstr = getArgument(args);
    std::string ystr = getArgument(args);

    // if any of them are empty strings, no argument was given
    if (character.empty() || mapstr.empty() || xstr.empty() || ystr.empty())
    {
        say("Invalid number of arguments given.", player);
        say("Usage: @warp <character> <map> <x> <y>", player);
        return;
    }

    // if it contains # then it means the player
    if (character == "#")
    {
        other = player;
    }
    else
    {
        // check for valid player
        other = getPlayer(character);
        if (!other)
        {
            say("Invalid or offline character <" + character + ">.", player);
            return;
        }
    }

    // if it contains # then it means the player's map
    if (mapstr == "#")
    {
        map = player->getMap();
    }
    else
    {
        if (mapstr[0] == '#')
        {
            mapstr = mapstr.substr(1);
            // check for valid map id
            int id;
            if (!utils::isNumeric(mapstr))
            {
                say("Invalid map", player);
                return;
            }

            id = utils::stringToInt(mapstr);

            // get the map
            map = MapManager::getMap(id);
            if (!map)
            {
                say("Invalid map", player);
                return;
            }
        }
        else
        {
            map = MapManager::getMap(mapstr);

            if (!map)
            {
                say("Invalid map", player);
                return;
            }
        }
    }

    if (!utils::isNumeric(xstr))
    {
        say("Invalid x", player);
        return;
    }

    if (!utils::isNumeric(ystr))
    {
        say("Invalid y", player);
        return;
    }

    // change the x and y to integers
    x = utils::stringToInt(xstr);
    y = utils::stringToInt(ystr);

    // now warp the player
    GameState::warp(other, map, x, y);

    // log transaction
    std::stringstream ss;
    ss << "User warped " << other->getName() << " to " << map->getName() <<
            " (" << x << ", " << y << ")";
    accountHandler->sendTransaction(player->getDatabaseID(), TRANS_CMD_WARP,
                                    ss.str());
}
예제 #5
0
static void handleBan(Character *player, std::string &args)
{
    Character *other;
    int length;
    int lengthMutiplier = 0;

    // get arguments
    std::string character = getArgument(args);
    std::string valuestr = getArgument(args);

    // check all arguments are there
    if (character.empty() || valuestr.empty())
    {
        say("Invalid number of arguments given.", player);
        say("Usage: @ban <character> <duration>", player);
        return;
    }

    // check for valid player
    other = getPlayer(character);
    if (!other)
    {
        say("Invalid character", player);
        return;
    }

    // get the unit
    char unit = valuestr.at(valuestr.length()-1);
    switch (unit)
    {
        case 'm':
            lengthMutiplier = 1;
            break;
        case 'h':
            lengthMutiplier = 60;
            break;
        case 'd':
            lengthMutiplier = 60 * 24;
            break;
        case 'w':
            lengthMutiplier = 60 * 24 * 7;
            break;
        case 'y':
            lengthMutiplier = 60 * 24 * 365;
            break;
    }
    length = utils::stringToInt(valuestr.substr(0, valuestr.length()-1));
    length = length * lengthMutiplier;
    if (length <= 0)
    {
        std::string errmsg;
        errmsg += "Invalid length. Please enter a positive number ";
        errmsg += "followed by the letter m, h, d, w or y for minutes ";
        errmsg += ", hours, days, weeks or years.";
        say(errmsg , player);
        return;
    }

    // ban the player
    accountHandler->banCharacter(other, length);
    // disconnect the player
    MessageOut kickmsg(GPMSG_CONNECT_RESPONSE);
    kickmsg.writeInt8(ERRMSG_ADMINISTRATIVE_LOGOFF);
    other->getClient()->disconnect(kickmsg);

    // feedback for command user
    std::string msg = "You've banned " + other->getName() + " for " + utils::toString(length) + " minutes";
    say(msg.c_str(), player);
    // log transaction
    msg = "User banned " + other->getName() + " for " + utils::toString(length) + " minutes";
    accountHandler->sendTransaction(player->getDatabaseID(), TRANS_CMD_BAN, msg);
}
예제 #6
0
파일: player.cpp 프로젝트: alisci01/openmw
 bool Player::isInCombat() {
     return MWBase::Environment::get().getMechanicsManager()->getActorsFighting(getPlayer()).size() != 0;
 }
예제 #7
0
파일: player.cpp 프로젝트: alisci01/openmw
    void Player::setLeftRight (int value)
    {
        MWWorld::Ptr ptr = getPlayer();

        MWWorld::Class::get (ptr).getMovementSettings (ptr).mPosition[0] = value;
    }
예제 #8
0
CFBPlayer* CFBTeam::getHilightPlayer()
{
    return getPlayer(m_hilightPlayerId);
}
예제 #9
0
파일: network.c 프로젝트: b00s1/NewtonWars
void stepNetwork(void)
{
   int i, k, pi, pi2, nbytes, newfd;
   char remoteIP[INET6_ADDRSTRLEN];
   struct sockaddr_storage remoteaddr;
   socklen_t addrlen;
   struct timeval tv;

   if(getDeathMessage(sendbuf))
   {
      for(k = 0; k < conf.maxPlayers; ++k)
      {
         if(connection[k].socket && !connection[k].bot)
         {
            snd(connection[k].socket, "\r\n");
            snd(connection[k].socket, sendbuf);
            snd(connection[k].socket, "\r\n> ");
         }
      }
   }
   
   tv.tv_sec = 0;
   tv.tv_usec = 1;
   readfds = master;
   if(select(fdmax + 1, &readfds, NULL, NULL, &tv) == -1)
   {
      print_error("select");
      exit(5);
   }

   for(i = 0; i <= fdmax; ++i)
   {
      if(FD_ISSET(i, &readfds))
      {
         if(i == listener)
         {
            addrlen = sizeof remoteaddr;
            newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen);
            if(newfd == -1)
            {
               print_error("accept");
            }
            else
            {
               getnameinfo((struct sockaddr *)&remoteaddr, addrlen, remoteIP, sizeof remoteIP, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV);
               for(k = 0; k < conf.maxPlayers; ++k)
               {
                  if(connection[k].socket == 0)
                  {
                     connection[k].socket = newfd;
                     strncpy(connection[k].remoteIP,remoteIP,INET6_ADDRSTRLEN);
                     playerJoin(k);
                     updateName(k, "Anonymous");
                     allSendPlayerPos(k);
                     break;
                  }
               }
               if(k == conf.maxPlayers)
               {
                  close(newfd);
                  printf("new connection from %s on socket %d refused: max connections\n", remoteIP, newfd);
               }
               else
               {
                  FD_SET(newfd, &master);
                  if(newfd > fdmax)
                  {
                     fdmax = newfd;
                  }
                  printf("new connection from %s on socket %d accepted\n", remoteIP, newfd);
                  snd(newfd, WELCOME);
               }
            }
         }
         else
         {
            if((nbytes = recv(i, buf, sizeof buf, 0)) <= 0)
            {
               if(nbytes == 0)
               {
                  printf("socket %d hung up\n", i);
               }
               else
               {
                  print_error("recv");
               }
               for(k = 0; k < conf.maxPlayers; ++k)
               {
                  if(connection[k].socket == i)
                  {
                     connection[k].socket = 0;
                     connection[k].echo = 0;
                     connection[k].bot = 0;
                     playerLeave(k);
                     allSendPlayerLeave(k);
                     break;
                  }
               }   
               close(i);
               FD_CLR(i, &master);
            }
            else
            {
               pi = -1;
               for(k = 0; k < conf.maxPlayers; ++k)
               {
                  if(connection[k].socket == i)
                  {
                     pi = k;
                     break;
                  }
               }   
               for(k = 0; k < nbytes && pi >= 0; ++k)
               {
                  unsigned char c = buf[k];
                  if(c != '\r' && c != '\n')
                  {
                     if(isprint(c) && connection[pi].msgbufindex < 128 - 2)
                     {
                        connection[pi].msgbuf[connection[pi].msgbufindex++] = c;
                     }
                  }
                  else
                  {
                     if(connection[pi].msgbufindex == 0)
                     {
                        continue;
                     }
                     connection[pi].msgbuf[connection[pi].msgbufindex] = '\0';
                     connection[pi].msgbuf[connection[pi].msgbufindex + 1] = '\0';
                     connection[pi].msgbufindex = 0;
                     if(connection[pi].echo)
                     {
                        snd(i, connection[pi].msgbuf);
                        snd(i, "\r\n");
                     }
                     if(!overdrive)printf("%16s (%d): \"%s\"\n", getPlayer(pi)->name, pi, connection[pi].msgbuf);
                     switch(connection[pi].msgbuf[0])
                     {
                        case 'n':
                        {
                           updateName(pi, connection[pi].msgbuf + 2);
                           break;
                        }
                        case 't':
                        {
			  if(is_from_localhost(connection[pi])) {
                           tankEnergy(atoi(connection[pi].msgbuf + 2));
			  }
                          break;
                        }
                        case 'v':
                        {
                           updateVelocity(pi, atof(connection[pi].msgbuf + 2));
                           break;
                        }
			case 'w':
			{
			   toggleWatch(pi);
			   break;
			}
                        case 'z':
                        {
                           updateZoom(atof(connection[pi].msgbuf + 2));
                           break;
                        }
			case 'T':
			{
			  if(is_from_localhost(connection[pi])) {
		            double throttle = atof(connection[pi].msgbuf + 2);
			    conf.throttle.tv_sec= throttle;
			    conf.throttle.tv_nsec=(throttle - conf.throttle.tv_sec) * 1000000000;
			  }
			  break;
			}
			case 'D':
			{
			  if(is_from_localhost(connection[pi])) {
			    conf.debug = atoi(connection[pi].msgbuf + 2);
			  }
			  break;
			}
                        case 'c':
                        {
                           clearTraces(pi);
                           break;
                        }
                        case 'o':
                        {
			   if(is_from_localhost(connection[pi])) {
                             overdrive = !overdrive;
			   }
                           break;
                        }
                        case 'b':
                        {
                           connection[pi].bot = !connection[pi].bot;
                           if(connection[pi].bot)
                           {
                              sendOwnId(i, pi);
                              for(pi2 = 0; pi2 < conf.maxPlayers; ++pi2)
                              {
                                 if(connection[pi2].socket)
                                 {
                                    sendPlayerPos(i, pi2);
                                 }
                              }
                           }
                           break;
                        }
                        case 'f':
                        {
                           toggleFps();
                           break;
                        }
                        case 'i':
                        {
                           if(strcmp("init", connection[pi].msgbuf) == 0)
                           {
                              reinitialize();
                           }
                           break;
                        }
                        case 'x':
                        {
                           if(strcmp("xit", connection[pi].msgbuf) == 0)
                           {
                              exit(0);
                           }
                           break;
                        }
                        case 'e':
                        {
                           connection[pi].echo = !connection[pi].echo;
                           break;
                        }
                        case 'r':
                        {
                           validateOld(pi);
                           break;
                        }
                        default:
                        {
                           updateAngle(pi, atof(connection[pi].msgbuf));
                           break;
                        }
                     }

                     if(!connection[pi].bot)
                     {
                        snd(i, "> ");
                     }
                  }
               }
            }
         }
      }
   }
   for(k = 0; k < conf.maxPlayers; ++k)
   {
      if(getPlayer(k)->active && getPlayer(k)->timeoutcnt > 2)
      {
         connection[k].echo = 0;
         playerLeave(k);
         close(connection[k].socket);
         FD_CLR(connection[k].socket, &master);
         connection[k].socket = 0;
         connection[k].bot = 0;
         allSendPlayerLeave(k);
     }
   }   
}
예제 #10
0
void Player::reset() {
  getPlayer()->life = (initialLife);
  getPlayer()->currency = (initialMoney);
  getPlayer()->tick = (initialTick);
}
예제 #11
0
void CFBTeam::kickOff(int playerNumber)
{
    auto player = getPlayer(playerNumber);
    player->gainBall();
    m_state = FBDefs::TEAM_STATE::ATTACKING;
}
예제 #12
0
//------------------------------------------------------------------------------
// isIffUpdateRequired() -- check to see if an update is required
//------------------------------------------------------------------------------
bool Nib::isIffUpdateRequired(const LCreal curExecTime, const Simulation::Iff* const iffSystem)
{

   // System status Bits
   static const unsigned short SYSTEM_STATUS_ON     = 0x0001;
   static const unsigned short SYSTEM_STATUS_NO_P1  = 0x0002;
   static const unsigned short SYSTEM_STATUS_NO_P2  = 0x0004;
   static const unsigned short SYSTEM_STATUS_NO_P3  = 0x0008;
   static const unsigned short SYSTEM_STATUS_NO_P4  = 0x0010;
   static const unsigned short SYSTEM_STATUS_NO_P5  = 0x0020;
   static const unsigned short SYSTEM_STATUS_NO_P6  = 0x0040;
   static const unsigned short SYSTEM_STATUS_FAILED = 0x0080;

   // Parameter bits
   static const unsigned short MODE_ON             = 0x2000;
   static const unsigned short MODE_C_ALT_NEG      = 0x0001;

   //Modifier bits
   static const unsigned short MODIFIER_EMERGENCY  = 0x0002;
   static const unsigned short MODIFIER_IDENT      = 0x0004;

   // Informational layer bits
   static const unsigned short LAYER_1_PRESENT     = 0x0002;
   static const unsigned short LAYER_2_PRESENT     = 0x0004;


   enum { NO, YES, UNSURE } result = UNSURE;    // Result of update check
   unsigned char options = 0;                   // New IFF PDU option bits

   // ---
   // Delta time since last message
   // ---
   LCreal drTime = curExecTime - iffLastExecTime;

   // ---   
   // 1) First time?
   // ---   
   if (iffFunOpData == 0) {
      options = CHANGE_INDICATOR;   // Initial report
      iffFunOpData = new FundamentalOpData();
      result = YES;
   }

   // ---   
   // 2) Build the fundamental operational data and compare to the past values
   // ---
   if (options == CHANGE_INDICATOR || drTime >= 2.0f) {
      // not more than every 2 seconds or if this is the first time

      FundamentalOpData opData;

      // System Status
      opData.systemStatus = 0;
      if (iffSystem->getPowerSwitch() >= Simulation::Iff::PWR_ON) {
         opData.systemStatus = SYSTEM_STATUS_ON;
      }

      // Alternate parameter 4
      opData.alternateParam4 = 1;

      // Information Layers
      opData.informationLayers = LAYER_1_PRESENT;

      // Modifier
      opData.modifier = 0;
      if (iffSystem->getPowerSwitch() == Simulation::Iff::PWR_EMERGENCY) {
         opData.modifier = (opData.modifier | MODIFIER_EMERGENCY);
      }

      // Parameter 1 - Mode #1
      opData.param1 = iffSystem->getMode1();
      if (iffSystem->isEnabledMode1()) {
         opData.param1 = (opData.param1 | MODE_ON);
      }

      // Parameter 2 - Mode #2
      opData.param2 = iffSystem->getMode2();
      if (iffSystem->isEnabledMode2()) {
         opData.param2 = (opData.param2 | MODE_ON);
      }

      // Parameter 3 - Mode #3
      opData.param3 = iffSystem->getMode3a();
      if (iffSystem->isEnabledMode3a()) {
         opData.param3 = (opData.param3 | MODE_ON);
      }

      // Parameter 4 - Mode #4
      if (iffSystem->getWhichMode4()) {
         opData.param4 = iffSystem->getMode4A();
      }
      else {
         opData.param4 = iffSystem->getMode4B();
      }
      if (iffSystem->isEnabledMode4()) {
         opData.param4 = (opData.param4 | MODE_ON);
      }

      // Prameter 5 - Mode C
      opData.param5 = 0;
      LCreal alt100 = (LCreal) ((getPlayer()->getAltitudeFt() + 50.0) / 100.0);
      if (alt100 < 0) { alt100 = -alt100; opData.param5 = MODE_C_ALT_NEG; }
      unsigned short ialt = (unsigned short) alt100;
      opData.param5 = (opData.param5 | (ialt << 1));  // alt shifted left one bit
      if (iffSystem->isEnabledModeC()) {
         opData.param5 = (opData.param5 | MODE_ON);
      }

      // Parameter 6 -- Mode S (not supported)
      opData.param6 = 0;
      opData.systemStatus = (opData.systemStatus | SYSTEM_STATUS_NO_P6);

      // Now check if anything changed
      bool changed = 
         (opData.param1 != iffFunOpData->param1) ||
         (opData.param2 != iffFunOpData->param2) ||
         (opData.param3 != iffFunOpData->param3) ||
         (opData.param4 != iffFunOpData->param4) ||
         (opData.param5 != iffFunOpData->param5) ||
         (opData.param6 != iffFunOpData->param6) ||
         (opData.systemStatus != iffFunOpData->systemStatus) ||
         (opData.alternateParam4 != iffFunOpData->alternateParam4) ||
         (opData.informationLayers != iffFunOpData->informationLayers) ||
         (opData.modifier != iffFunOpData->modifier);

      if (changed) {
         options = CHANGE_INDICATOR;
         result = YES;
      }

      // DMOC wants all options bits set (0x07)
      options = (CHANGE_INDICATOR | ALTERNATE_MODE_4 | ALTERNATE_MODE_C);

      // And don't forget to save our new values for output
      iffFunOpData->param1 = opData.param1;
      iffFunOpData->param2 = opData.param2;
      iffFunOpData->param3 = opData.param3;
      iffFunOpData->param4 = opData.param4;
      iffFunOpData->param5 = opData.param5;
      iffFunOpData->param6 = opData.param6;
      iffFunOpData->systemStatus = opData.systemStatus;
      iffFunOpData->alternateParam4 = opData.alternateParam4;
      iffFunOpData->informationLayers = opData.informationLayers;
      iffFunOpData->modifier = opData.modifier;
   }

   // ---   
   // 3) At least every 10 seconds
   // ---   
   if ( (result == UNSURE)) {
      if ( drTime >= 10.0f ) {
         result = YES;
      }
   }

   iffOptions = options;
   return (result == YES);
}
예제 #13
0
//------------------------------------------------------------------------------
// IffManager() -- (Output support) IFF manager
//------------------------------------------------------------------------------
bool Nib::IffManager(const LCreal curExecTime)
{
   NetIO* disIO = (NetIO*)(getNetIO());
   const Basic::Pair* pair = getPlayer()->getRadioByType(typeid(Simulation::Iff));

   // OK if the player has an IFF transponder and we're the correct version.
   bool ok = (disIO->getVersion() >= NetIO::VERSION_1278_1A) && (pair != 0);

   if (ok) {
      const Simulation::Iff* iffSystem = (const Simulation::Iff*) pair->object();

      if (isIffUpdateRequired(curExecTime, iffSystem)) {


         // Standard header stuff
         IffAtcNavaidsPDU pdu;
         pdu.header.protocolVersion = disIO->getVersion();
         pdu.header.exerciseIdentifier = disIO->getExerciseID();
         pdu.header.PDUType = NetIO::PDU_IFF_ATC_NAVAIDS;
         pdu.header.protocolFamily = NetIO::PDU_FAMILY_DIS_EMISSION_REG;
         pdu.header.timeStamp = disIO->timeStamp();
         pdu.header.length = sizeof(IffAtcNavaidsPDU);

         // Entity ID
         pdu.emittingEntityID.simulationID.siteIdentification = getSiteID();
         pdu.emittingEntityID.simulationID.applicationIdentification = getApplicationID();
         pdu.emittingEntityID.ID = getPlayerID();

         // Location (default is center of parent entity)
         pdu.location.component[0] = 0;
         pdu.location.component[1] = 0;
         pdu.location.component[2] = 0;

         // System ID (for now just use a standard Mark X11; upgrade to type from IFF later)
         pdu.systemID.systemType = 1;        // Mark X11
         pdu.systemID.systemName = 2;        // Mark X11
         pdu.systemID.systemMode = 0;        // Other
         pdu.systemID.options = iffOptions;  // Option bits

         // Functional operational data
         pdu.operationalData.systemStatus = iffFunOpData->systemStatus;
         pdu.operationalData.alternateParam4 = iffFunOpData->alternateParam4;
         pdu.operationalData.informationLayers = iffFunOpData->informationLayers;
         pdu.operationalData.modifier = iffFunOpData->modifier;
         pdu.operationalData.param1 = iffFunOpData->param1;
         pdu.operationalData.param2 = iffFunOpData->param2;
         pdu.operationalData.param3 = iffFunOpData->param3;
         pdu.operationalData.param4 = iffFunOpData->param4;
         pdu.operationalData.param5 = iffFunOpData->param5;
         pdu.operationalData.param6 = iffFunOpData->param6;

         // Event ID
         pdu.eventID.simulationID.siteIdentification = disIO->getSiteID();
         pdu.eventID.simulationID.applicationIdentification = disIO->getApplicationID();
         pdu.eventID.eventNumber = disIO->getNewIffEventID();

         //pdu.dumpData();
         if (Basic::NetHandler::isNotNetworkByteOrder()) pdu.swapBytes();
         ok = disIO->sendData((char*)&pdu,sizeof(pdu));

         iffLastExecTime = curExecTime;

      }

   }

   return ok;
}
예제 #14
0
int32_t NpcScriptInterface::luaDoSellItem(lua_State* L)
{
	//doSellItem(cid, itemid, amount, <optional> subtype, <optional> actionid, <optional: default: 1> canDropOnMap)
	Player* player = getPlayer(L, 1);
	if (!player) {
		reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND));
		pushBoolean(L, false);
		return 1;
	}

	uint32_t sellCount = 0;

	uint32_t itemId = getNumber<uint32_t>(L, 2);
	uint32_t amount = getNumber<uint32_t>(L, 3);
	uint32_t subType;

	int32_t n = getNumber<int32_t>(L, 4, -1);
	if (n != -1) {
		subType = n;
	} else {
		subType = 1;
	}

	uint32_t actionId = getNumber<uint32_t>(L, 5, 0);
	bool canDropOnMap = getBoolean(L, 6, true);

	const ItemType& it = Item::items[itemId];
	if (it.stackable) {
		while (amount > 0) {
			int32_t stackCount = std::min<int32_t>(100, amount);
			Item* item = Item::CreateItem(it.id, stackCount);
			if (item && actionId != 0) {
				item->setActionId(actionId);
			}

			if (g_game.internalPlayerAddItem(player, item, canDropOnMap) != RETURNVALUE_NOERROR) {
				delete item;
				lua_pushnumber(L, sellCount);
				return 1;
			}

			amount -= stackCount;
			sellCount += stackCount;
		}
	} else {
		for (uint32_t i = 0; i < amount; ++i) {
			Item* item = Item::CreateItem(it.id, subType);
			if (item && actionId != 0) {
				item->setActionId(actionId);
			}

			if (g_game.internalPlayerAddItem(player, item, canDropOnMap) != RETURNVALUE_NOERROR) {
				delete item;
				lua_pushnumber(L, sellCount);
				return 1;
			}

			++sellCount;
		}
	}

	lua_pushnumber(L, sellCount);
	return 1;
}
예제 #15
0
파일: player.cpp 프로젝트: alisci01/openmw
 void Player::roll(float roll)
 {
     MWWorld::Ptr ptr = getPlayer();
     MWWorld::Class::get(ptr).getMovementSettings(ptr).mRotation[1] += roll;
 }
예제 #16
0
void Server::handleCommand_PlayerPos(NetworkPacket* pkt) {
	const auto peer_id = pkt->getPeerId();
	auto & packet = *(pkt->packet);
	auto player = m_env->getPlayer(pkt->getPeerId());
	if (!player) {
		m_con.DisconnectPeer(pkt->getPeerId());
		return;
	}
	auto playersao = player->getPlayerSAO();
	if (!playersao) {
		m_con.DisconnectPeer(pkt->getPeerId());
		return;
	}

	// If player is dead we don't care of this packet

	if (player->hp != 0 && playersao->m_ms_from_last_respawn > 1000)
		player->setPosition(packet[TOSERVER_PLAYERPOS_POSITION].as<v3f>());
	player->setSpeed(packet[TOSERVER_PLAYERPOS_SPEED].as<v3f>());
	player->setPitch(modulo360f(packet[TOSERVER_PLAYERPOS_PITCH].as<f32>()));
	player->setYaw(modulo360f(packet[TOSERVER_PLAYERPOS_YAW].as<f32>()));
	u32 keyPressed = packet[TOSERVER_PLAYERPOS_KEY_PRESSED].as<u32>();
	player->keyPressed = keyPressed;
	{
		std::lock_guard<Mutex> lock(player->control_mutex);
		player->control.up = (bool)(keyPressed & 1);
		player->control.down = (bool)(keyPressed & 2);
		player->control.left = (bool)(keyPressed & 4);
		player->control.right = (bool)(keyPressed & 8);
		player->control.jump = (bool)(keyPressed & 16);
		player->control.aux1 = (bool)(keyPressed & 32);
		player->control.sneak = (bool)(keyPressed & 64);
		player->control.LMB = (bool)(keyPressed & 128);
		player->control.RMB = (bool)(keyPressed & 256);
	}
	auto old_pos = playersao->m_last_good_position;
	if(playersao->checkMovementCheat()) {
		// Call callbacks
		m_script->on_cheat(playersao, "moved_too_fast");
		SendMovePlayer(peer_id);
	} else if (playersao->m_ms_from_last_respawn > 3000) {
		auto dist = (old_pos / BS).getDistanceFrom(playersao->m_last_good_position / BS);
		if (dist)
			stat.add("move", playersao->getPlayer()->getName(), dist);
	}

	if (playersao->m_ms_from_last_respawn > 2000) {
		auto obj = playersao; // copypasted from server step:
		auto uptime = m_uptime.get();
		if (!obj->m_uptime_last)  // not very good place, but minimum modifications
			obj->m_uptime_last = uptime - 0.1;
		if (uptime - obj->m_uptime_last > 0.5) {
			obj->step(uptime - obj->m_uptime_last, true); //todo: maybe limit count per time
			obj->m_uptime_last = uptime;
		}
	}

	/*infostream<<"Server::ProcessData(): Moved player "<<peer_id<<" to "
														<<"("<<position.X<<","<<position.Y<<","<<position.Z<<")"
														<<" pitch="<<pitch<<" yaw="<<yaw<<std::endl;*/
}
예제 #17
0
파일: player.cpp 프로젝트: alisci01/openmw
 MWMechanics::DrawState_ Player::getDrawState()
 {
      MWWorld::Ptr ptr = getPlayer();
      return MWWorld::Class::get(ptr).getNpcStats(ptr).getDrawState();
 }
예제 #18
0
EBuildingState::EBuildingState CGameInfoCallback::canBuildStructure( const CGTownInstance *t, BuildingID ID )
{
	ERROR_RET_VAL_IF(!canGetFullInfo(t), "Town is not owned!", EBuildingState::TOWN_NOT_OWNED);

	if(!t->town->buildings.count(ID))
		return EBuildingState::BUILDING_ERROR;

	const CBuilding * building = t->town->buildings.at(ID);


	if(t->hasBuilt(ID))	//already built
		return EBuildingState::ALREADY_PRESENT;

	//can we build it?
	if(vstd::contains(t->forbiddenBuildings, ID))
		return EBuildingState::FORBIDDEN; //forbidden

	auto possiblyNotBuiltTest = [&](BuildingID id) -> bool
	{
		return ((id == BuildingID::CAPITOL) ? true : !t->hasBuilt(id));
	};

	std::function<bool(BuildingID id)> allowedTest = [&](BuildingID id) -> bool
	{
		return !vstd::contains(t->forbiddenBuildings, id);
	};

	if (!t->genBuildingRequirements(ID, true).satisfiable(allowedTest, possiblyNotBuiltTest))
		return EBuildingState::FORBIDDEN;

	if(ID == BuildingID::CAPITOL)
	{
		const PlayerState *ps = getPlayer(t->tempOwner, false);
		if(ps)
		{
			for(const CGTownInstance *t : ps->towns)
			{
				if(t->hasBuilt(BuildingID::CAPITOL))
				{
					return EBuildingState::HAVE_CAPITAL; //no more than one capitol
				}
			}
		}
	}
	else if(ID == BuildingID::SHIPYARD)
	{
		const TerrainTile *tile = getTile(t->bestLocation(), false);

		if(!tile || tile->terType != ETerrainType::WATER)
			return EBuildingState::NO_WATER; //lack of water
	}

	auto buildTest = [&](BuildingID id) -> bool
	{
		return t->hasBuilt(id);
	};

	if (!t->genBuildingRequirements(ID).test(buildTest))
		return EBuildingState::PREREQUIRES;

	if(t->builded >= VLC->modh->settings.MAX_BUILDING_PER_TURN)
		return EBuildingState::CANT_BUILD_TODAY; //building limit

	//checking resources
	if(!building->resources.canBeAfforded(getPlayer(t->tempOwner)->resources))
		return EBuildingState::NO_RESOURCES; //lack of res

	return EBuildingState::ALLOWED;
}
예제 #19
0
파일: player.cpp 프로젝트: alisci01/openmw
 void Player::setDrawState (MWMechanics::DrawState_ state)
 {
      MWWorld::Ptr ptr = getPlayer();
      MWWorld::Class::get(ptr).getNpcStats(ptr).setDrawState (state);
 }
예제 #20
0
void GameState::readInput()
{
	if (getPlayer()->isEnabled())
	getPlayer()->updateInput(world.getCommandQueue());	
}
예제 #21
0
static void handleMute(Character *player, std::string &args)
{
    Character *other;
    int length;

    // Get arguments.
    std::string character = getArgument(args);
    std::string valuestr = getArgument(args);


    // Check for a valid player.
    other = getPlayer(character);
    if (!other)
    {
        say("Invalid character", player);
        return;
    }

    // Turn the length back to an integer.
    if (valuestr.empty())
        length = Configuration::getValue("command_defaultMuteLength", 60);
    else
        length = utils::stringToInt(valuestr);

    if (length < 0)
    {
        say("Invalid length, using default", player);
        length = Configuration::getValue("command_defaultMuteLength", 60);
    }

    // Mute the player.
    other->mute(length);

    // Feedback.
    std::stringstream targetMsg;
    std::stringstream userMsg;
    if (length > 0)
    {
        targetMsg << player->getName() << " muted you for "
        << length << " seconds.";

        userMsg << "You muted " << other->getName()
        << " for " << length << " seconds.";
    }
    else
    {
        targetMsg << player->getName() << " unmuted you.";
        userMsg << "You unmuted " << other->getName() << ".";
    }
    say(targetMsg.str(), other);
    say(userMsg.str(), player);

    // log transaction
    std::stringstream msg;
    if (length > 0)
    {
        msg << "User muted " << other->getName() << " for " << length << " seconds.";
    } else {
        msg << "User unmuted " << other->getName();
    }
    accountHandler->sendTransaction(player->getDatabaseID(), TRANS_CMD_MUTE, msg.str());
}
예제 #22
0
파일: player.cpp 프로젝트: alisci01/openmw
    void Player::setUpDown(int value)
    {
        MWWorld::Ptr ptr = getPlayer();

        MWWorld::Class::get (ptr).getMovementSettings (ptr).mPosition[2] = value;
    }
예제 #23
0
static void handleItem(Character *player, std::string &args)
{
    Character *other;
    ItemClass *ic;
    int value = 0;

    // get arguments
    std::string character = getArgument(args);
    std::string itemclass = getArgument(args);
    std::string valuestr = getArgument(args);

    // check all arguments are there
    if (character.empty() || itemclass.empty())
    {
        say("Invalid number of arguments given.", player);
        say("Usage: @item <character> <item> [amount]", player);
        return;
    }

    // if it contains # that means the player
    if (character == "#")
    {
        other = player;
    }
    else
    {
        // check for valid player
        other = getPlayer(character);
        if (!other)
        {
            say("Invalid character or they are offline", player);
            return;
        }
    }

    // identify the item type
    if (utils::isNumeric(itemclass))
    {
        int id = utils::stringToInt(itemclass);
        ic = itemManager->getItem(id);
    }
    else
    {
        ic = itemManager->getItemByName(itemclass);
    }
    if (!ic)
    {
        say("Invalid item", player);
        return;
    }

    //identify the amount
    if  (valuestr.empty())
    {
        value = 1;
    }
    else if (utils::isNumeric(valuestr))
    {
        value = utils::stringToInt(valuestr);
    }
    // check for valid amount
    if (value <= 0)
    {
        say("Invalid number of items", player);
        return;
    }

    // insert the item into the inventory
    Inventory(other).insert(ic->getDatabaseID(), value);

    // log transaction
    std::stringstream str;
    str << "User created item " << ic->getDatabaseID();
    accountHandler->sendTransaction(player->getDatabaseID(), TRANS_CMD_ITEM, str.str());
}
예제 #24
0
파일: player.cpp 프로젝트: alisci01/openmw
 void Player::setRunState(bool run)
 {
     MWWorld::Ptr ptr = getPlayer();
     ptr.getClass().getCreatureStats(ptr).setMovementFlag(MWMechanics::CreatureStats::Flag_Run, run);
 }
예제 #25
0
static void handleAttribute(Character *player, std::string &args)
{
    Character *other;
    int attr, value;

    // get arguments
    std::string character = getArgument(args);
    std::string attrstr = getArgument(args);
    std::string valuestr = getArgument(args);

    // check all arguments are there
    if (character.empty() || valuestr.empty() || attrstr.empty())
    {
        say("Invalid number of arguments given.", player);
        say("Usage: @attribute <character> <attribute> <value>", player);
        return;
    }

    // check if its the player or another player
    if (character == "#")
    {
        other = player;
    }
    else
    {
        // check for valid player
        other = getPlayer(character);
        if (!other)
        {
            say("Invalid character", player);
            return;
        }
    }

    // check they are really integers
    if (!utils::isNumeric(valuestr) || !utils::isNumeric(attrstr))
    {
        say("Invalid argument", player);
        return;
    }

    // put the attribute into an integer
    attr = utils::stringToInt(attrstr);

    if (attr < 0)
    {
        say("Invalid Attribute", player);
        return;
    }

    // put the value into an integer
    value = utils::stringToInt(valuestr);

    if (value < 0)
    {
        say("Invalid amount", player);
        return;
    }

    // change the player's attribute
    other->setAttribute(attr, value);

    // log transaction
    std::stringstream msg;
    msg << "User changed attribute " << attr << " of player " << other->getName()
        << " to " << value;
    accountHandler->sendTransaction(player->getDatabaseID(), TRANS_CMD_ATTRIBUTE, msg.str());
}
예제 #26
0
파일: player.cpp 프로젝트: alisci01/openmw
 void Player::yaw(float yaw)
 {
     MWWorld::Ptr ptr = getPlayer();
     MWWorld::Class::get(ptr).getMovementSettings(ptr).mRotation[2] += yaw;
 }
void EditorMenuManager::createItems()
{
    Rect rect = VisibleRect::getVisibleRect();
    this->setZOrder(2);
    
    auto scene = dynamic_cast<GameLogic*>(this->getParent());
    
    if (scene)
    {
        /*--------------------- Input Menu -------------------------*/
        auto player = scene->getPlayer();
        
        if (player)
        {
            auto inputMenu = InputMenuItem::create();
            inputMenu->setPosition(0, rect.getMaxY());
            
            inputMenu->setPlayer(player);
            inputMenu->initLevelVar();
            this->addChild(inputMenu, 0, INPUT_MENU);
            
            auto inputMenuSize = inputMenu->getContentSize();
            auto inputTabLayer = LayerColor::create(Color4B(50,50,50,200), inputMenuSize.width / 17, inputMenuSize.height / 3);
            inputTabLayer->setPosition(0, -(inputMenuSize.height / 3));
            inputMenu->addChild(inputTabLayer, 0, 1);
            
            Sprite* inputTabSprite = Sprite::create("Pan_Tab.png");
            inputTabSprite->setScale(0.6f, 0.6f);
            MenuItemSprite* inputTabItem = MenuItemSprite::create(inputTabSprite, inputTabSprite, inputTabSprite, CC_CALLBACK_1(EditorMenuManager::inputTabPressed, this));
            
            Menu *inputTab = Menu::create(inputTabItem, NULL);
            inputTab->setPosition(44, 48);
            inputTabLayer->addChild(inputTab, 0, 1);
        }
        
        /*--------------------- Sheep Menu -------------------------*/
        __Array* sheepArray = scene->getSheep();
        
        if (sheepArray->count() > 0)
        {
            auto sheepMenu = SheepMenuItem::create();
            sheepMenu->setPosition(0, rect.getMaxY());
            
            sheepMenu->setScene(scene);
            sheepMenu->initLevelVar();
            this->addChild(sheepMenu, 0, SHEEP_MENU);
            
            auto sheepMenuSize = sheepMenu->getContentSize();
            auto sheepTabLayer = LayerColor::create(Color4B(50,50,50,200), sheepMenuSize.width / 17, sheepMenuSize.height / 3);
            sheepTabLayer->setPosition(sheepMenuSize.width / 17, -(sheepMenuSize.height / 3));
            sheepMenu->addChild(sheepTabLayer, 0, 1);
            
            Sprite* sheepTabSprite = Sprite::create("Pecora_Tab.png");
            sheepTabSprite->setScale(0.8f, 0.8f);
            MenuItemSprite* sheepTabItem = MenuItemSprite::create(sheepTabSprite, sheepTabSprite, sheepTabSprite, CC_CALLBACK_1(EditorMenuManager::sheepTabPressed, this));
            
            Menu *sheepTab = Menu::create(sheepTabItem, NULL);
            sheepTab->setPosition(34, 34);
            sheepTabLayer->addChild(sheepTab, 0, 2);
        }
        
        /*--------------------- Note Menu --------------------------*/
        if (player && (sheepArray->count() >0))
        {
            auto noteMenu = NoteMenuItem::create();
            noteMenu->setPosition(0, rect.getMaxY());
            
            noteMenu->setPlayer(player);
            noteMenu->setScene(scene);
            noteMenu->initLevelVar();
            this->addChild(noteMenu, 0, NOTE_MENU);
            
            auto noteMenuSize = noteMenu->getContentSize();
            auto noteTabLayer = LayerColor::create(Color4B(50,50,50,200), noteMenuSize.width / 17, noteMenuSize.height / 3);
            noteTabLayer->setPosition(noteMenuSize.width / 8.5, -(noteMenuSize.height / 3));
            noteMenu->addChild(noteTabLayer, 0, 1);
            
            Sprite* noteTabSprite = Sprite::create("Nota_Tab.png");
            noteTabSprite->setScale(0.8f, 0.8f);
            MenuItemSprite* noteTabItem = MenuItemSprite::create(noteTabSprite, noteTabSprite, noteTabSprite, CC_CALLBACK_1(EditorMenuManager::noteTabPressed, this));
            
            Menu *noteTab = Menu::create(noteTabItem, NULL);
            noteTab->setPosition(34, 34);
            noteTabLayer->addChild(noteTab, 0, 3);
        }
        
        /*--------------------- Goatskin Menu --------------------------*/
        __Array* goatskinArray = scene->getGoatskins();
        
        if (goatskinArray->count() > 0)
        {
            auto goatskinMenu = GoatskinMenuItem::create();
            goatskinMenu->setPosition(0, rect.getMaxY());
            
            goatskinMenu->setScene(scene);
            goatskinMenu->initLevelVar();
            this->addChild(goatskinMenu, 0, GOATSKIN_MENU);
    
            auto goatskinMenuSize = goatskinMenu->getContentSize();
            auto goatskinTabLayer = LayerColor::create(Color4B(50,50,50,200), goatskinMenuSize.width / 17, goatskinMenuSize.height / 3);
            goatskinTabLayer->setPosition(goatskinMenuSize.width / 5.67, -(goatskinMenuSize.height / 3));
            goatskinMenu->addChild(goatskinTabLayer, 0, 1);
    
            Sprite* goatskinTabSprite = Sprite::create("rock_2x2.png");
            goatskinTabSprite->setScale(0.3f, 0.3f);
            MenuItemSprite* goatskinTabItem = MenuItemSprite::create(goatskinTabSprite, goatskinTabSprite, goatskinTabSprite, CC_CALLBACK_1(EditorMenuManager::goatskinTabPressed, this));
    
            Menu *goatskinTab = Menu::create(goatskinTabItem, NULL);
            goatskinTab->setPosition(74, 70);
            goatskinTabLayer->addChild(goatskinTab, 0, 4);
        }
    }
    
    /*----------------- Save Data selection --------------------*/
    auto saveTabLayer = LayerColor::create(Color4B(50,50,50,200), rect.getMaxX() / 17, rect.getMaxY() / 12);
    saveTabLayer->setPosition((rect.getMaxX() - (rect.getMaxX() / 8.5)), (rect.getMaxY() - (rect.getMaxY() / 12)));
    this->addChild(saveTabLayer, 0, SAVE);
    
    auto saveLabel = Label::createWithSystemFont("SAVE", "Marker Felt", 15);
    MenuItemLabel* saveTabItem = MenuItemLabel::create(saveLabel, CC_CALLBACK_1(EditorMenuManager::saveTabPressed, this));
    
    Menu *saveTab = Menu::create(saveTabItem, NULL);
    saveTab->setPosition(28, 26);
    saveTabLayer->addChild(saveTab, 0, 1);
    
    /*--------------- Back to Level selection ------------------*/
    auto backTabLayer = LayerColor::create(Color4B(50,50,50,200), rect.getMaxX() / 17, rect.getMaxY() / 12);
    backTabLayer->setPosition((rect.getMaxX() - (rect.getMaxX() / 17)), (rect.getMaxY() - (rect.getMaxY() / 12)));
    this->addChild(backTabLayer, 0, BACK);
    
    auto backLabel = Label::createWithSystemFont("BACK", "Marker Felt", 15);
    MenuItemLabel* backTabItem = MenuItemLabel::create(backLabel, CC_CALLBACK_1(EditorMenuManager::backTabPressed, this));
    
    Menu *backTab = Menu::create(backTabItem, NULL);
    backTab->setPosition(28, 26);
    backTabLayer->addChild(backTab, 0, 1);
}
예제 #28
0
파일: player.cpp 프로젝트: alisci01/openmw
 void Player::pitch(float pitch)
 {
     MWWorld::Ptr ptr = getPlayer();
     MWWorld::Class::get(ptr).getMovementSettings(ptr).mRotation[0] += pitch;
 }
예제 #29
0
int game_host::performUpdate(string upd)
{
	int updateType = 0;
	UpdMess update(upd);
	updateType = update.getType();

	if(updateType == TOWER)
	{
		int subType = update.getVal(0);
		//Tower Placement:		UpdMess(Player[1], TOWER, TOWERPLACE[2], TowerX[2], Tower[Y]);
		if(subType == TOWERPLACE)
		{
			// placeTower(int playerNumber, int towerType, int x, int y);
			if(isEmptyLocation(update.getVal(1), update.getVal(2)))
			{
				placeTower(update.getPlayer(), STRUCTURE, update.getVal(1), update.getVal(2));
			}
		}	
		else if(subType == MINEPLACE)
		{
			if(isEmptyLocation(update.getVal(1), update.getVal(2)))
			{
				placeTower(update.getPlayer(), MINETOWER, update.getVal(1), update.getVal(2));
			}
		}
		//Tower Upgrade:			UpdMess(Player[1], TOWER, TOWERUPGRADE[2], TowerID[4]);
		else if(subType == TOWERUPGRADE)
		{
			if(towerList.checkForObjectWithID(update.getId1()) == true)
			{
				if(towerList.getNodeWithID(update.getId1())->getData()->getType() != STRUCTURE)
				{
					if(towerList.getNodeWithID(update.getId1())->getData()->upgrade())
					{
						sendMessageToQueue(UpdMess(update.getPlayer(), TOWER, TOWERUPGRADE, update.getId1()).getMT());
					}
				}
			}
		}
		//Tower ChangeType:		UpdMess(Player[1], TOWER, TOWERCHANGE[2], TowerID[4], newType[2]);	
		else if(subType == TOWERCHANGE)
		{
			if(towerList.checkForObjectWithID(update.getId1()) == true)
			{
				if(towerList.getNodeWithID(update.getId1())->getData()->getType() == STRUCTURE)
				{
					return changeStructure(update.getId1(), update.getVal(1));
				}
				else if(towerList.getNodeWithID(update.getId1())->getData()->getType() == NORMCREEPTOWER)
				{
					if(towerList.getNodeWithID(update.getId1())->getData()->changeType(update.getVal(1)))
					{
						sendMessageToQueue(UpdMess(update.getPlayer(), TOWER, TOWERCHANGE, update.getId1(),update.getVal(1)).getMT());
					}
				}
			}
		}
		//Tower Toggle Pause:		UpdMess(Player[1], TOWER, TOWERTOGGLE[2], TowerID[4], newValue);
		else if(subType == TOWERTOGGLE)
		{
			if(towerList.checkForObjectWithID(update.getId1()))
			{
				int towerTypeRec = towerList.getNodeWithID(update.getId1())->getData()->getType();
				if(towerList.getNodeWithID(update.getId1())->getData()->getType() >= NORMCREEPTOWER && towerList.getNodeWithID(update.getId1())->getData()->getType() <= FATTYCREEPTOWER)
				{
					if(update.getVal(1) == 1)
						towerList.getNodeWithID(update.getId1())->getData()->pause();
					else if(update.getVal(1) == 0)
						towerList.getNodeWithID(update.getId1())->getData()->unpause();
					sendMessageToQueue(UpdMess(towerList.getNodeWithID(update.getId1())->getData()->getPlayer(), TOWER, TOWERTOGGLE, update.getId1(), towerList.getNodeWithID(update.getId1())->getData()->isPaused()).getMT());
				}
			}
		}
		else if(subType == TOWERDELETE)
		{	
			if(towerList.checkForObjectWithID(update.getId1()))
			{
				removeTower(update.getId1(), update.getPlayer());
			}
		}

	}
	else if(updateType == BASE)
	{
		int subType = update.getVal(0);
		if(subType == UPGRADE)
		{
			if(this->getPlayer(update.getPlayer())->getMoney() >= BASEUPGRADECOST)
			{
				if(update.getPlayer() == 1)
				{
					if(this->p1Spawner->getLevel() < 5 && players[0].getMoney() >= (p1Spawner->getLevel() + 1) * BASEUPGRADECOST)
					{
						players[0].spendMoney((p1Spawner->getLevel() + 1) * BASEUPGRADECOST);
						this->p1Spawner->setLevel(this->p1Spawner->getLevel() + 1);
						sendMessageToQueue(UpdMess(1, BASE, UPGRADE).getMT());
					}
				}
				else if(update.getPlayer() == 2)
				{
					if(this->p2Spawner->getLevel() < 5 && players[1].getMoney() >= (p2Spawner->getLevel() + 1) * BASEUPGRADECOST)
					{
						players[1].spendMoney((p2Spawner->getLevel() + 1) * BASEUPGRADECOST);
						this->p2Spawner->setLevel(this->p2Spawner->getLevel() + 1);
						sendMessageToQueue(UpdMess(2, BASE, UPGRADE).getMT());
					}
				}
			}
		}
		else if(subType == ADDTYPE)
		{
			int addType = update.getVal(1);
			if(!(addType >= FAST && addType <= FATTY))
				return -1;
			if(update.getPlayer() == 1)
			{
				if(this->p1Spawner->isInSpawner(addType))
					return -1;	// Already in the spawner
			}
			else if(update.getPlayer() == 2)
			{
				if(this->p2Spawner->isInSpawner(addType))
					return -1;  // Already in the spawner
			}
			else
				return -1;
			if(this->getPlayer(update.getPlayer())->getMoney() >= addSpawnArr[addType])
			{
				this->getPlayer(update.getPlayer())->spendMoney(addSpawnArr[addType]);
				if(update.getPlayer() == 1)
				{
					this->p1Spawner->addCreepType(addType);
					sendMessageToQueue(UpdMess(1, BASE, ADDTYPE, addType).getMT());
				}
				else
				{
					this->p2Spawner->addCreepType(addType);
					sendMessageToQueue(UpdMess(2, BASE, ADDTYPE, addType).getMT());
				}
			}
		}
		else
			return -1;
	}
	else 
		return -1;
	sendMessageToQueue(UpdMess(1, PLAYERUPDATE, getPlayer(1)->getHealth(), getPlayer(1)->getMoney()).getMT());
	sendMessageToQueue(UpdMess(2, PLAYERUPDATE, getPlayer(2)->getHealth(), getPlayer(2)->getMoney()).getMT());
	return 0;
}
예제 #30
0
//------------------------------------------------------------------------------
// Manage the articulated parameters and attached parts
//------------------------------------------------------------------------------
unsigned char Nib::manageArticulationParameters(EntityStatePDU* const pdu)
{
   unsigned char cnt = 0;
   NetIO* const disIO = static_cast<NetIO*>(getNetIO());

   // First articulation parameter is just after the main PDU
   unsigned char *p = (reinterpret_cast<unsigned char *>(pdu)) + sizeof(*pdu);
   VpArticulatedPart* ap = reinterpret_cast<VpArticulatedPart*>(p);

   // ---
   // Air Vehicle articulated parts and attachments
   // ---
   if ( getPlayer()->isMajorType(Simulation::Player::AIR_VEHICLE) ) {

      // Check wing sweep angle.
      if (getAPartWingSweepCnt() > 0) {
         // fill the articulation parameter structure
         ap->parameterTypeDesignator = VpArticulatedPart::ARTICULATED_PART;
         ap->changeIndicator = static_cast<unsigned char>(getAPartWingSweepCnt() & 0xff);
         ap->id = 0;
         ap->parameterType = (VpArticulatedPart::WING_SWEEP + VpArticulatedPart::AZIMUTH);
         ap->parameterValue.value[0] = static_cast<float>(getAPartWingSweep());  // radians
         ap->parameterValue.value[1] = 0;
         // Update part count & pointer
         cnt++;
         ap++;
      }

      // Check landing gear position.
      if (getAPartGearPosCnt() > 0) {
         // fill the articulation parameter structure
         ap->parameterTypeDesignator = VpArticulatedPart::ARTICULATED_PART;
         ap->changeIndicator = static_cast<unsigned char>(getAPartGearPosCnt() & 0xff);
         ap->id = 0;
         ap->parameterType = (VpArticulatedPart::LANDING_GEAR + VpArticulatedPart::POSITION);
         ap->parameterValue.value[0] = static_cast<float>(getAPartPartGearPos())/100.0f;
         ap->parameterValue.value[1] = 0;
         // Update part count & pointer
         cnt++;
         ap++;
      }

      // Check weapon bay door position (send out both doors)
      if (getAPartBayDoorCnt() > 0) {

         // Left door
         ap->parameterTypeDesignator = VpArticulatedPart::ARTICULATED_PART;
         ap->changeIndicator = static_cast<unsigned char>(getAPartBayDoorCnt() & 0xff);
         ap->id = 0;
         ap->parameterType = (VpArticulatedPart::LEFT_WEAPON_BAY_DOOR + VpArticulatedPart::POSITION);
         ap->parameterValue.value[0] = static_cast<float>(getAPartBayDoorPos())/100.0f;
         ap->parameterValue.value[1] = 0;

         // Update part count & pointer
         cnt++;
         ap++;

         // Right door
         ap->parameterTypeDesignator = VpArticulatedPart::ARTICULATED_PART;
         ap->changeIndicator = static_cast<unsigned char>(getAPartBayDoorCnt() & 0xff);
         ap->id = 0;
         ap->parameterType = (VpArticulatedPart::RIGHT_WEAPON_BAY_DOOR + VpArticulatedPart::POSITION);
         ap->parameterValue.value[0] = static_cast<float>(getAPartBayDoorPos())/100.0f;
         ap->parameterValue.value[1] = 0;

         // Update part count & pointer
         cnt++;
         ap++;

      }

   }

   // ---
   // Ground Vehicle articulated parts and attachments
   // ---
   else if ( getPlayer()->isMajorType(Simulation::Player::GROUND_VEHICLE) ) {

      // Check launcher elevation angle
      if (getAPartLauncherElevationCnt() > 0) {
         // fill the articulation parameter structure
         ap->parameterTypeDesignator = VpArticulatedPart::ARTICULATED_PART;
         ap->changeIndicator = static_cast<unsigned char>(getAPartLauncherElevationCnt() & 0xff);
         ap->id = 0;
         ap->parameterType = (VpArticulatedPart::PRIMARY_LAUNCHER_1 + VpArticulatedPart::ELEVATION);
         ap->parameterValue.value[0] = static_cast<float>( getAPartLauncherElevation() );
         ap->parameterValue.value[1] = 0;
         // Update part count & pointer
         cnt++;
         ap++;
      }

      // Check attached missiles
      unsigned int n = getAPartNumberAttachedNumMissiles();
      for (unsigned int i = 0; i < n; i++) {

         const Simulation::Missile* msl = getAPartAttachedMissile(i+1);

         // Find the missile's entity type
         if (apartMslTypes[i] == nullptr) {

            const Ntm* ntm = dynamic_cast<const Ntm*>( disIO->findNetworkTypeMapper(msl) );
            if (ntm != nullptr) {

               // found the NTM for the missile -- and it must be a DIS NTM
               apartMslTypes[i] = dynamic_cast<const Ntm*>(ntm);
               if (apartMslTypes[i] != nullptr) apartMslTypes[i]->ref();
            }

         }

         // We must have the missile's entity type to send the attached part ...
         if (apartMslTypes[i] != nullptr) {

            // fill the articulation parameter structure
            ap->parameterTypeDesignator = VpArticulatedPart::ATTACHED_PART;
            ap->changeIndicator = static_cast<unsigned char>(getAPartAttacheMissileChangeCnt(i+1) & 0xff);
            ap->id = 1;                   // ATTACHED to LAUNCHER (above)
            ap->parameterType = (i+1);    // Station number
            if (msl->isMode(Simulation::Player::LAUNCHED)) {
               ap->parameterValue.entityType.kind = 0;
               ap->parameterValue.entityType.domain = 0;
               ap->parameterValue.entityType.country = 0;
               ap->parameterValue.entityType.category = 0;
               ap->parameterValue.entityType.subcategory = 0;
               ap->parameterValue.entityType.specific = 0;
               ap->parameterValue.entityType.extra = 0;
            }
            else {
               ap->parameterValue.entityType.kind = apartMslTypes[i]->getEntityKind();
               ap->parameterValue.entityType.domain = apartMslTypes[i]->getEntityDomain();
               ap->parameterValue.entityType.country = apartMslTypes[i]->getEntityCountry();
               ap->parameterValue.entityType.category = apartMslTypes[i]->getEntityCategory();
               ap->parameterValue.entityType.subcategory = apartMslTypes[i]->getEntitySubcategory();
               ap->parameterValue.entityType.specific = apartMslTypes[i]->getEntitySpecific();
               ap->parameterValue.entityType.extra = apartMslTypes[i]->getEntityExtra();
            }

            // Update part count & pointer
            cnt++;
            ap++;
         }
      }
   }

   return cnt;
}