Example #1
0
int DataChn::connect(const string& ip, int port)
{
   // no need to connect to self
   if ((ip == m_strIP) && (port == m_iPort))
      return 1;

   Address addr;
   addr.m_strIP = ip;
   addr.m_iPort = port;

   pthread_mutex_lock(&m_ChnLock);
   map<Address, ChnInfo*, AddrComp>::iterator i = m_mChannel.find(addr);
   if (i != m_mChannel.end())
   {
      if ((NULL != i->second->m_pTrans) && i->second->m_pTrans->isConnected())
      {
         pthread_mutex_unlock(&m_ChnLock);
         return 0;
      }
      delete i->second->m_pTrans;
      i->second->m_pTrans = NULL;
   }

   ChnInfo* c = NULL;
   if (i == m_mChannel.end())
   {
      c = new ChnInfo;
      c->m_pTrans = NULL;
      pthread_mutex_init(&c->m_SndLock, NULL);
      pthread_mutex_init(&c->m_RcvLock, NULL);
      pthread_mutex_init(&c->m_QueueLock, NULL);
      m_mChannel[addr] = c;
   }
   else
   {
      c = i->second;
   }

   pthread_mutex_unlock(&m_ChnLock);

   pthread_mutex_lock(&c->m_SndLock);
   if ((NULL != c->m_pTrans) && c->m_pTrans->isConnected())
   {
      c->m_iCount ++;
      pthread_mutex_unlock(&c->m_SndLock);
      return 0;
   }

   Transport* t = new Transport;
   t->open(m_iPort, true, true);
   int r = t->connect(ip.c_str(), port);

   if (NULL == c->m_pTrans)
      c->m_pTrans = t;
   else
   {
      Transport* tmp = c->m_pTrans;
      c->m_pTrans = t;
      delete tmp;
   }

   pthread_mutex_unlock(&c->m_SndLock);

   return r;
}
Example #2
0
  /**
   * test Server and Client memory leak
   * test whether packets are deleted when connection closed
   */
  void TCPCONNECTIONTF::testMemLeak() {
    char spec[] = "tcp:localhost:13147";
    int64_t now = TimeUtil::getTime();
    Transport *tranServer = new Transport;
    Transport *tranClient = new Transport;

    ConnServerAdapter *adapter = new ConnServerAdapter;

    //add listener to tranServer
    IOComponent *listener = tranServer->listen(spec, _streamer, adapter);
    CPPUNIT_ASSERT(listener);
    tranServer->eventIteration(now);
    
    //create a connection
    Connection *conn = tranClient->connect(spec, _streamer, false);
    CPPUNIT_ASSERT(conn);
    tranClient->eventIteration(now);

    //accept the connection
    tranServer->eventIteration(now);

    // client send two packets

    _conn->postPacket(new ConnPacket, _handler, NULL, true);    
    _conn->postPacket(new ConnPacket, _handler, NULL, true);
    tranClient->eventIteration(now);

    //server accept two packets
    tranServer->eventIteration(now);
    IOComponent *ioc = tranServer->_iocListTail;
    Connection *tmpConn = ((TCPComponent *)ioc)->_connection;
    //client close the connection
    _conn->close();
    tranClient->eventIteration(now);
    
    tranServer->eventIteration(now);
    CPPUNIT_ASSERT_EQUAL((size_t)0, tmpConn->_outputQueue.size());

    delete adapter;
    delete tranClient;
    delete tranServer;
    listener->subRef();
    conn->subRef();
  }
bool HostFilterComponent::perform (const InvocationInfo& info)
{
    Config* config = Config::getInstance();

    GraphComponent* graph = main->getGraph ();
    Transport* transport = getFilter()->getTransport();

    switch (info.commandID)
    {
    //----------------------------------------------------------------------------------------------
    case CommandIDs::pluginOpen:
        {
            graph->loadAndAppendPlugin ();
            break;
        }
    case CommandIDs::pluginClose:
        {
            graph->closeSelectedPlugins ();
            break;
        }
    case CommandIDs::pluginClear:
        {
            graph->closeAllPlugins ();
            break;
        }
    case CommandIDs::showPluginListEditor:
        {
           if (PluginListWindow::currentPluginListWindow == 0)
               PluginListWindow::currentPluginListWindow = new PluginListWindow (knownPluginList);

           PluginListWindow::currentPluginListWindow->toFront (true);
            
            break;
        }

    //----------------------------------------------------------------------------------------------
#ifndef JOST_VST_PLUGIN
    case CommandIDs::audioOptions:
        {
            StandaloneFilterWindow* window = findParentComponentOfClass ((StandaloneFilterWindow*) 0);
            if (window)
                window->showAudioSettingsDialog ();

            break;
        }
#endif

    case CommandIDs::audioPlay:
        {
            transport->play ();
            break;
        }
    case CommandIDs::audioPlayPause:
        {
            transport->togglePlay ();
            break;
        }
    case CommandIDs::audioStop:
        {
            transport->stop ();
            break;
        }
    case CommandIDs::audioRecord:
        {
            transport->record ();
            break;
        }
    case CommandIDs::audioRewind:
        {
            transport->rewind ();
            break;
        }
    case CommandIDs::audioLoop:
        {
            transport->setLooping (! transport->isLooping());
            break;
        }

    //----------------------------------------------------------------------------------------------
    case CommandIDs::sessionNew:
        {
           bool retValue = 
               AlertWindow::showYesNoCancelBox (AlertWindow::WarningIcon,
                                             T("Unsaved Changes"),
                                             T("Are you sure you want to close the current session? You may lose any unsaved changes."));
            if (retValue)
            {
               closePluginEditorWindows ();
               getFilter()->getHost ()->closeAllPlugins (true);

               clearComponents ();
               Config::getInstance()->lastSessionFile = File::nonexistent;
               rebuildComponents ();
            }
            break;
        }
    
    case CommandIDs::sessionLoad:
        {
            FileChooser myChooser (T("Load a session file..."),
                                    Config::getInstance ()->lastSessionDirectory,
                                    JOST_SESSION_WILDCARD, JOST_USE_NATIVE_FILE_CHOOSER);

            if (myChooser.browseForFileToOpen())
            {
              bool retValue = 
               AlertWindow::showYesNoCancelBox (AlertWindow::WarningIcon,
                                             T("Unsaved Changes"),
                                             T("Are you sure you want to close the current session? You may lose any unsaved changes."));
               if (retValue)
               {

                MemoryBlock fileData;
                File fileToLoad = myChooser.getResult();

                if (fileToLoad.existsAsFile()
                    && fileToLoad.loadFileAsData (fileData))
                {
                    getFilter ()->setStateInformation (fileData.getData (), fileData.getSize());

                    Config::getInstance()->addRecentSession (fileToLoad);
                    Config::getInstance()->lastSessionFile = fileToLoad;
                }
               }
            }
            break;
        }
    case CommandIDs::sessionSave:
        {
            handleSaveCommand();
            break;
        }
    case CommandIDs::sessionSaveNoPrompt:
        {
            handleSaveCommand(true);
            break;
        }

    case CommandIDs::audioStemsStartStop:
        {
            getHost()->toggleStemRendering();
            break;
        }
    case CommandIDs::audioStemsSetup:
        {
            FileChooser myChooser (T("Save Rendered Stem Files To..."),
                                    Config::getInstance ()->lastStemsDirectory);
            if (myChooser.browseForDirectory ())
            {
                Config::getInstance ()->lastStemsDirectory = myChooser.getResult();
            }
            break; 
        }

    //----------------------------------------------------------------------------------------------
    case CommandIDs::appToolbar:
        {
            toolbar->showCustomisationDialog (*factory,
                                              Toolbar::allCustomisationOptionsEnabled);
                                              // (Toolbar::allowIconsOnlyChoice | Toolbar::showResetToDefaultsButton));
            break;
        }
    case CommandIDs::appBrowser:
        {
            setBrowserVisible (! config->showBrowser, config->browserLeft);
            break;
        }
    case CommandIDs::appFullScreen:
        {
            DocumentWindow* window = findParentComponentOfClass <DocumentWindow> ();
            if (window) {
                window->setFullScreen (! window->isFullScreen ());
                window->setMenuBar (window->isFullScreen () ? 0 : this);
            }
            break;
        }
    case CommandIDs::appExit:
        {
            deleteAndZero(PluginListWindow::currentPluginListWindow);
            JUCEApplication::getInstance()->systemRequestedQuit();
            break;
        }
    case CommandIDs::appAbout:
        {
//            Image* splashImage = ImageCache::getFromMemory (Resource::jost_about,
//                                                            Resource::jost_about_size);
         // todo: move appResourcesFolder() to somewhere everyone can use it
#if JUCE_MAC
			File appResourcesFolder(File::getSpecialLocation(File::currentApplicationFile).getChildFile("./Contents/Resources"));
#else
			File appResourcesFolder(File::getSpecialLocation(File::currentApplicationFile).getParentDirectory());
#endif
			File splashImageFile(appResourcesFolder.getChildFile("JiveAbout.png"));
            Image* splashImage = ImageFileFormat::loadFrom(splashImageFile);
            SplashScreen* splash = new SplashScreen();
            splash->show (T(JucePlugin_Name), splashImage, 3500, false);
            break;
        }

    //----------------------------------------------------------------------------------------------
    default:
        return false;
    }

    return true;
}
Example #4
0
void f_header(CStrRef str, bool replace /* = true */,
              int http_response_code /* = 0 */) {
  if (f_headers_sent()) {
    raise_warning("Cannot modify header information - headers already sent");
  }

  String header = f_rtrim(str);

  // new line safety check
  // NOTE: PHP actually allows "\n " and "\n\t" to fall through. Is that bad
  // for security?
  if (header.find('\n') >= 0 || header.find('\r') >= 0) {
    raise_warning("Header may not contain more than a single header, "
                  "new line detected");
    return;
  }

  Transport *transport = g_context->getTransport();
  if (transport && header->size()) {
    const char *header_line = header->data();

    // handle single line of status code
    if (header->size() >= 5 && strncasecmp(header_line, "HTTP/", 5) == 0) {
      int code = 200;
      for (const char *ptr = header_line; *ptr; ptr++) {
        if (*ptr == ' ' && *(ptr + 1) != ' ') {
          code = atoi(ptr + 1);
          break;
        }
      }
      if (code) {
        transport->setResponse(code, "explicit_header");
      }
      return;
    }

    const char *colon_offset = strchr(header_line, ':');
    String newHeader;
    if (colon_offset) {
      if (!strncasecmp(header_line, "Content-Type",
                       colon_offset - header_line)) {
        const char *ptr = colon_offset+1, *mimetype = NULL;
        while (*ptr == ' ') ptr++;
        mimetype = ptr;
        if (strncmp(mimetype, "text/", 5) == 0 &&
            strstr(mimetype, "charset=") == NULL) {
          newHeader = header + ";charset=utf-8";
        }
      }
    }
    if (replace) {
      transport->replaceHeader(newHeader.empty() ? header : newHeader);
    } else {
      transport->addHeader(newHeader.empty() ? header : newHeader);
    }
    if (http_response_code) {
      transport->setResponse(http_response_code,
                             "explicit_header_response_code");
    }
  }
}
Example #5
0
void MapManager::LoadTransports()
{
    uint32 oldMSTime = getMSTime();

    QueryResult result = WorldDatabase.Query("SELECT guid, entry, name, period, ScriptName FROM transports");

    if (!result)
    {
        sLog->outString(">> Loaded 0 transports. DB table `transports` is empty!");
        sLog->outString();
        return;
    }

    uint32 count = 0;

    do
    {
        Field *fields = result->Fetch();
        uint32 lowguid = fields[0].GetUInt32();
        uint32 entry = fields[1].GetUInt32();
        std::string name = fields[2].GetString();
        uint32 period = fields[3].GetUInt32();
        uint32 scriptId = sObjectMgr->GetScriptId(fields[4].GetCString());

        Transport *t = new Transport(period, scriptId);

        const GameObjectInfo *goinfo = ObjectMgr::GetGameObjectInfo(entry);

        if (!goinfo)
        {
            sLog->outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template missing", entry, name.c_str());
            delete t;
            continue;
        }

        if (goinfo->type != GAMEOBJECT_TYPE_MO_TRANSPORT)
        {
            sLog->outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template type wrong", entry, name.c_str());
            delete t;
            continue;
        }

        // sLog->outString("Loading transport %d between %s, %s", entry, name.c_str(), goinfo->name);

        std::set<uint32> mapsUsed;

        if (!t->GenerateWaypoints(goinfo->moTransport.taxiPathId, mapsUsed))
            // skip transports with empty waypoints list
        {
            sLog->outErrorDb("Transport (path id %u) path size = 0. Transport ignored, check DBC files or transport GO data0 field.", goinfo->moTransport.taxiPathId);
            delete t;
            continue;
        }

        float x = t->m_WayPoints[0].x;
        float y = t->m_WayPoints[0].y;
        float z = t->m_WayPoints[0].z;
        uint32 mapid = t->m_WayPoints[0].mapid;
        float o = 1.0f;

         // creates the Gameobject
        if (!t->Create(lowguid, entry, mapid, x, y, z, o, 100, 0))
        {
            delete t;
            continue;
        }

        m_Transports.insert(t);

        for (std::set<uint32>::const_iterator i = mapsUsed.begin(); i != mapsUsed.end(); ++i)
            m_TransportsByMap[*i].insert(t);

        //If we someday decide to use the grid to track transports, here:
        t->SetMap(sMapMgr->CreateMap(mapid, t, 0));
        t->AddToWorld();

        ++count;
    }
    while (result->NextRow());

    // check transport data DB integrity
    result = WorldDatabase.Query("SELECT gameobject.guid, gameobject.id, transports.name FROM gameobject, transports WHERE gameobject.id = transports.entry");
    if (result)                                              // wrong data found
    {
        do
        {
            Field *fields = result->Fetch();

            uint32 guid  = fields[0].GetUInt32();
            uint32 entry = fields[1].GetUInt32();
            std::string name = fields[2].GetString();
            sLog->outErrorDb("Transport %u '%s' have record (GUID: %u) in `gameobject`. Transports DON'T must have any records in `gameobject` or its behavior will be unpredictable/bugged.", entry, name.c_str(), guid);
        }
        while (result->NextRow());
    }

    sLog->outString(">> Loaded %u transports in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
    sLog->outString();
}
Example #6
0
int CmdPull::execute (std::string& output)
{
  context.footnote ("The 'pull' command is deprecated, and will be removed in a subsequent release.");

  std::vector <std::string> words = context.a3.extract_words ();
  std::string file;
  if (words.size ())
    file = words[0];

  Uri uri (file, "pull");
  uri.parse ();

  if (uri._data.length ())
  {
		Directory location (context.config.get ("data.location"));

    if (! uri.append ("{pending,undo,completed}.data"))
      throw format (STRING_CMD_PULL_NOT_DIR, uri._path);

		Transport* transport;
		if ((transport = Transport::getTransport (uri)) != NULL)
		{
			transport->recv (location._data + "/");
			delete transport;
		}
		else
		{
      // Verify that files are not being copied from rc.data.location to the
      // same place.
      if (Directory (uri._path) == Directory (context.config.get ("data.location")))
        throw std::string (STRING_CMD_PULL_SAME);

      // copy files locally

      // remove {pending,undo,completed}.data
      uri._path = uri.parent();

      Path path1 (uri._path + "undo.data");
      Path path2 (uri._path + "pending.data");
      Path path3 (uri._path + "completed.data");

      if (path1.exists() && path2.exists() && path3.exists())
      {
//        if (confirm ("xxxxxxxxxxxxx"))
//        {
          std::ofstream ofile1 ((location._data + "/undo.data").c_str(), std::ios_base::binary);
          std::ifstream ifile1 (path1._data.c_str()                    , std::ios_base::binary);
          ofile1 << ifile1.rdbuf();

          std::ofstream ofile2 ((location._data + "/pending.data").c_str(), std::ios_base::binary);
          std::ifstream ifile2 (path2._data.c_str()                    , std::ios_base::binary);
          ofile2 << ifile2.rdbuf();

          std::ofstream ofile3 ((location._data + "/completed.data").c_str(), std::ios_base::binary);
          std::ifstream ifile3 (path3._data.c_str()                    , std::ios_base::binary);
          ofile3 << ifile3.rdbuf();
//        }
      }
      else
      {
        throw format (STRING_CMD_PULL_MISSING, uri._path);
      }
		}

    output += format (STRING_CMD_PULL_TRANSFERRED, uri.ToString ()) + "\n";
  }
  else
    throw std::string (STRING_CMD_PULL_NO_URI);

  return 0;
}
Example #7
0
void sync(Transport tr){
    //std::cout << tr.toString() << std::endl;
    transport_string = tr.toString()	;
    if(playing){
    	Transport diff = tr - last_transport;
    	t = diff.toSec();
    	ros::Duration elapsed = ros::Time::now() - last_update_time;
    	sync_offset = t - elapsed.toSec();
    	offset_string = std::to_string(sync_offset);
    	
    	//upon reaching a new bar, obtain note info for the next bar
    	if(tr.position.bar != last_transport.position.bar || tr.tempo != last_transport.tempo){
    		double cur_t = (ros::Time::now() - playback_start_time).toSec();
    		
    		//information about the beats
    		std::vector<terpsichore::pair> beats;
			//binary bars
			//if(tr.timeSignature.beatsPerBar % 2 == 0){
				for(int i = 1; i <= tr.timeSignature.beatsPerBar; i++){
					double beats_ahead = (1 * tr.timeSignature.beatsPerBar) + (i - 1);	
    				double beat_time = ((double)(beats_ahead + (tr.position.unit/tr.position.resolution))/tr.tempo) * 60.0 + cur_t;
					
					terpsichore::pair b;
					std::vector<double> d;
					b.t = beat_time;
					
					if(i % 2 == 0){
					//weak beat
						d.push_back(0.5);
					}else{
					//stronk beat
						d.push_back(1.0);
					}
					b.data = d;
					beats.push_back(b);
				}
			//}
    		bardata.beats = beats;
    		
    		std::vector<terpsichore::pair> events;
    		//grab the first clip in the map
    		std::map<int, Clip*>::iterator it = listener->clips.begin();
    		if(it != listener->clips.end()){
				Clip* c = it->second;
				
				//std::cout << "now in " << tr.position.toString() << std::endl;
				for(std::multimap<Position, Note>::iterator it = c->notes.begin(); it != c->notes.end(); it++){
					Position p = it->first;
					if(p.bar == (tr.position.bar + 1) || (tr.position.bar) % c->length.bar + 1 == p.bar){
						Note n = it->second;
						terpsichore::pair d;
						d.t = (1.0 * tr.timeSignature.beatsPerBar + p.toFloat(tr.timeSignature))/tr.tempo * 60.0 + cur_t;
						double scaled_pitch = (double)(n.pitch)/(double)(108);
						double scaled_vel = double(n.velocity)/(double)(127);
		
						std::vector<double> info;
						info.push_back(scaled_pitch);
						info.push_back((double)n.duration);
						info.push_back(scaled_vel);
						d.data = info;
						events.push_back(d);
						//std::cout << "added note in " << p.toString() << std::endl;
					}else{
						//std::cout << "not adding the note in " << p.toString() << std::endl;
						continue;
					}
			
				}
				bardata.events = events;
			}
    		
    		data_pub.publish(bardata);
    	}
    }
	last_update_time = ros::Time::now();
    last_transport = tr;
}
Example #8
0
bool AreaTrigger::Create(uint32 spellMiscId, Unit* caster, Unit* target, SpellInfo const* spell, Position const& pos, int32 duration, uint32 spellXSpellVisualId, ObjectGuid const& castId, AuraEffect const* aurEff)
{
    _targetGuid = target ? target->GetGUID() : ObjectGuid::Empty;
    _aurEff = aurEff;

    SetMap(caster->GetMap());
    Relocate(pos);
    if (!IsPositionValid())
    {
        TC_LOG_ERROR("entities.areatrigger", "AreaTrigger (spellMiscId %u) not created. Invalid coordinates (X: %f Y: %f)", spellMiscId, GetPositionX(), GetPositionY());
        return false;
    }

    _areaTriggerMiscTemplate = sAreaTriggerDataStore->GetAreaTriggerMiscTemplate(spellMiscId);
    if (!_areaTriggerMiscTemplate)
    {
        TC_LOG_ERROR("entities.areatrigger", "AreaTrigger (spellMiscId %u) not created. Invalid areatrigger miscid (%u)", spellMiscId, spellMiscId);
        return false;
    }

    Object::_Create(ObjectGuid::Create<HighGuid::AreaTrigger>(GetMapId(), GetTemplate()->Id, caster->GetMap()->GenerateLowGuid<HighGuid::AreaTrigger>()));

    SetEntry(GetTemplate()->Id);
    SetDuration(duration);

    SetObjectScale(1.0f);

    SetGuidValue(AREATRIGGER_CASTER, caster->GetGUID());
    SetGuidValue(AREATRIGGER_CREATING_EFFECT_GUID, castId);

    SetUInt32Value(AREATRIGGER_SPELLID, spell->Id);
    SetUInt32Value(AREATRIGGER_SPELL_FOR_VISUALS, spell->Id);
    SetUInt32Value(AREATRIGGER_SPELL_X_SPELL_VISUAL_ID, spellXSpellVisualId);
    SetUInt32Value(AREATRIGGER_TIME_TO_TARGET_SCALE, GetMiscTemplate()->TimeToTargetScale != 0 ? GetMiscTemplate()->TimeToTargetScale : GetUInt32Value(AREATRIGGER_DURATION));
    SetFloatValue(AREATRIGGER_BOUNDS_RADIUS_2D, GetTemplate()->MaxSearchRadius);
    SetUInt32Value(AREATRIGGER_DECAL_PROPERTIES_ID, GetMiscTemplate()->DecalPropertiesId);

    for (uint8 scaleCurveIndex = 0; scaleCurveIndex < MAX_AREATRIGGER_SCALE; ++scaleCurveIndex)
        if (GetMiscTemplate()->ScaleInfo.ExtraScale[scaleCurveIndex].AsInt32)
            SetUInt32Value(AREATRIGGER_EXTRA_SCALE_CURVE + scaleCurveIndex, GetMiscTemplate()->ScaleInfo.ExtraScale[scaleCurveIndex].AsInt32);

    PhasingHandler::InheritPhaseShift(this, caster);

    if (target && GetTemplate()->HasFlag(AREATRIGGER_FLAG_HAS_ATTACHED))
    {
        m_movementInfo.transport.guid = target->GetGUID();
    }

    UpdateShape();

    uint32 timeToTarget = GetMiscTemplate()->TimeToTarget != 0 ? GetMiscTemplate()->TimeToTarget : GetUInt32Value(AREATRIGGER_DURATION);

    if (GetTemplate()->HasFlag(AREATRIGGER_FLAG_HAS_CIRCULAR_MOVEMENT))
    {
        AreaTriggerCircularMovementInfo cmi = GetMiscTemplate()->CircularMovementInfo;
        if (target && GetTemplate()->HasFlag(AREATRIGGER_FLAG_HAS_ATTACHED))
            cmi.PathTarget = target->GetGUID();
        else
            cmi.Center = pos;

        InitCircularMovement(cmi, timeToTarget);
    }
    else if (GetMiscTemplate()->HasSplines())
    {
        InitSplineOffsets(GetMiscTemplate()->SplinePoints, timeToTarget);
    }

    // movement on transport of areatriggers on unit is handled by themself
    Transport* transport = m_movementInfo.transport.guid.IsEmpty() ? caster->GetTransport() : nullptr;
    if (transport)
    {
        float x, y, z, o;
        pos.GetPosition(x, y, z, o);
        transport->CalculatePassengerOffset(x, y, z, &o);
        m_movementInfo.transport.pos.Relocate(x, y, z, o);

        // This object must be added to transport before adding to map for the client to properly display it
        transport->AddPassenger(this);
    }

    AI_Initialize();

    // Relocate areatriggers with circular movement again
    if (HasCircularMovement())
        Relocate(CalculateCircularMovementPosition());

    if (!GetMap()->AddToMap(this))
    {
        // Returning false will cause the object to be deleted - remove from transport
        if (transport)
            transport->RemovePassenger(this);
        return false;
    }

    caster->_RegisterAreaTrigger(this);

    _ai->OnCreate();

    return true;
}
Example #9
0
int main(int argc, char** argv) {
  int k;
  string infile = "diamond.xml";
 
  try {

   
    IdealGasMix g("gri30.xml", "gri30_mix");
    int nsp = g.nSpecies();
    double pres = 1.0E5;
    vector_fp Xset(nsp, 0.0);
    Xset[0] =  0.269205 ;
    Xset[1] =  0.000107082;
    Xset[2] =  1.36377e-09 ;
    Xset[3] =  4.35475e-10; 
    Xset[4] =  4.34036e-06 ;
    Xset[5] =  0.192249; 
    Xset[6] =  3.59356e-13;     
    Xset[7] =  2.78061e-12 ;  
    Xset[8] =  4.7406e-18   ; 
    Xset[9] =  4.12955e-17 ;
    Xset[10] = 2.58549e-14  ;  
    Xset[11] = 8.96502e-16 ;    
    Xset[12] = 6.09056e-11   ;
    Xset[13] = 7.56752e-09  ;
    Xset[14] = 0.192253;
    Xset[15] = 0.0385036;  
    Xset[16] = 1.49596e-08   ;
    Xset[17] = 2.22378e-08     ;
    Xset[18] =   1.43096e-13   ;
    Xset[19] =   1.45312e-15 ;
    Xset[20] =  1.96948e-12 ;
    Xset[21] =   8.41937e-19;
    Xset[22] =  3.18852e-13 ;
    Xset[23] =  7.93625e-18 ;
    Xset[24] = 3.20653e-15  ;
    Xset[25] = 1.15149e-19 ;
    Xset[26] = 1.61189e-18  ;
    Xset[27] =   1.4719e-15 ;
    Xset[28] =  5.24728e-13 ;
    Xset[29] = 6.90582e-17  ;
    Xset[30] = 6.37248e-12   ;
    Xset[31] = 5.93728e-11   ;
    Xset[32] = 2.71219e-09  ;
    Xset[33] = 2.66645e-06 ;
    Xset[34] = 6.57142e-11 ;
    Xset[35] = 9.52453e-08 ;
    Xset[36] = 1.26006e-14;  
    Xset[37] = 3.49802e-12;
    Xset[38] = 1.19232e-11 ;
    Xset[39] = 7.17782e-13; 
    Xset[40] = 1.85347e-07   ;
    Xset[41] = 8.25325e-14   ;
    Xset[42] =  5.00914e-20 ;
    Xset[43] = 1.54407e-16 ;
    Xset[44] =3.07176e-11 ;
    Xset[45] =4.93198e-08 ;
    Xset[46] =4.84792e-12 ;
    Xset[47] = 0.307675  ;
    Xset[48] =0;
    Xset[49] =6.21649e-29;
    Xset[50] = 8.42393e-28 ;
    Xset[51] = 6.77865e-18;
    Xset[52] = 2.19225e-16;
    double T1 = 1500.;

    double sum = 0.0;
    for (k = 0; k < nsp; k++) {
      sum += Xset[k];
    }
    for (k = 0; k < nsp; k++) {
      Xset[k] /= sum;
    }

    vector_fp X2set(nsp, 0.0);
    X2set[0]  = 0.25 ; 
    X2set[5]  = 0.17; 
    X2set[14] = 0.15;
    X2set[15] = 0.05;  
    X2set[47] =  0.38 ;
    double T2 = 1200.;
 
    double dist = 0.1;

    vector_fp X3set(nsp, 0.0);
    X3set[0]  = 0.27 ; 
    X3set[5]  = 0.15; 
    X3set[14] = 0.18;
    X3set[15] = 0.06;  
    X3set[47] = 0.36 ;
    double T3 = 1400.;
   
    vector_fp grad_T(3, 0.0);

    Array2D grad_X(nsp, 2, 0.0);


    for( k = 0; k < nsp; k++) {
      grad_X(k,0) = (X2set[k] - Xset[k])/dist; 
      grad_X(k,1) = (X3set[k] - Xset[k])/dist; 
    }

    grad_T[0] = (T2 - T1) / dist;
    grad_T[1] = (T3 - T1) / dist;

    int log_level = 0;
    Transport * tran = newTransportMgr("Multi", &g, log_level=0);

    MultiTransport * tranMix = dynamic_cast<MultiTransport *>(tran);


    g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
 
    
    vector_fp mixDiffs(nsp, 0.0);
    
    tranMix->getMixDiffCoeffs(DATA_PTR(mixDiffs));
    printf(" Dump of the mixture Diffusivities:\n");
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      printf("    %15s %13.5g\n", sss.c_str(), mixDiffs[k]);
    }
  

    vector_fp specVisc(nsp, 0.0);
    
    tranMix->getSpeciesViscosities(DATA_PTR(specVisc));
    printf(" Dump of the species viscosities:\n");
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      printf("    %15s %13.5g\n", sss.c_str(), specVisc[k]);
    }

    vector_fp thermDiff(nsp, 0.0);
    tranMix->getThermalDiffCoeffs(DATA_PTR(thermDiff));
    printf(" Dump of the Thermal Diffusivities :\n");
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      double ddd = cutoff(thermDiff[k]);
      printf("    %15s %13.5g\n", sss.c_str(), ddd);
    }

    printf("Viscoscity and thermal Cond vs. T\n");
    for (k = 0; k < 10; k++) {
      T1 = 400. + 100. * k;
      g.setState_TPX(T1, pres, DATA_PTR(Xset));
      double visc = tran->viscosity();
      double cond = tran->thermalConductivity();
      printf("    %13g %13.5g %13.5g\n", T1, visc, cond);
    }

    g.setState_TPX(T1, pres, DATA_PTR(Xset));

    Array2D Bdiff(nsp, nsp, 0.0);
    printf("Binary Diffusion Coefficients H2 vs species\n");

    tranMix->getBinaryDiffCoeffs(nsp, Bdiff.ptrColumn(0));
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      printf(" H2 -   %15s %13.5g %13.5g\n", sss.c_str(), Bdiff(0,k), Bdiff(k,0));
    }


    vector_fp specMob(nsp, 0.0);
    
    //tranMix->getMobilities(DATA_PTR(specMob));
    printf(" Dump of the species mobilities:\n");
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      printf("    %15s %13.5g\n", sss.c_str(), specMob[k]);
    }

    Array2D fluxes(nsp, 2, 0.0);
    
    tranMix->getSpeciesFluxes(2, DATA_PTR(grad_T), nsp,
			      grad_X.ptrColumn(0), nsp, fluxes.ptrColumn(0));
    printf(" Dump of the species fluxes:\n");
    double sum1 = 0.0;
    double sum2 = 0.0;
    double max1 = 0.0;
    double max2 = 0.0;
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      double ddd = cutoff(fluxes(k,0));
      double eee = cutoff(fluxes(k,1));
      printf("    %15s %13.4g %13.4g\n", sss.c_str(), ddd, eee);
      sum1 += fluxes(k,0);
      if (fabs(fluxes(k,0)) > max1) {
	max1 = fabs(fluxes(k,0));
      } 
      sum2 += fluxes(k,1);
      if (fabs(fluxes(k,1)) > max2) {
	max2 = fabs(fluxes(k,0));
      } 
    }
   
    // Make sure roundoff error doesn't interfere with the printout.
    // these should be zero.
    if (fabs(sum1) * 1.0E14 > max1) {
      printf("sum in x direction = %13.5g\n", sum1);
    } else {
      printf("sum in x direction = 0\n");
    }
    if (fabs(sum2) * 1.0E14 > max2) {
      printf("sum in y direction = %13.5g\n", sum1);
    } else {
      printf("sum in y direction = 0\n");
    }
 

    Array2D MDdiff(nsp, nsp, 0.0);
    printf("Multicomponent Diffusion Coefficients H2 vs species\n");

    tranMix->getMultiDiffCoeffs(nsp, MDdiff.ptrColumn(0));
    for (k = 0; k < nsp; k++) {
      string sss = g.speciesName(k);
      printf(" H2 -   %15s %13.5g %13.5g\n", sss.c_str(), MDdiff(0,k), MDdiff(k,0));
    }


  }
  catch (CanteraError) {
    showErrors(cout);
  }

  return 0;
}
Example #10
0
void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
{
    CHECK_PACKET_SIZE(recv_data,8);

    m_playerLoading = true;
    uint64 playerGuid = 0;

    DEBUG_LOG( "WORLD: Recvd Player Logon Message" );

    recv_data >> playerGuid;

    Player* plr = new Player(this);

    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!plr->LoadFromDB(GUID_LOPART(playerGuid)))
    {
        KickPlayer();                                       // disconnect client, player no set to session and it will not deleted or saved at kick
        delete plr;                                         // delete it manually
        m_playerLoading = false;
        return;
    }
    //plr->_RemoveAllItemMods();

    //set a count of unread mails
    time_t cTime = time(NULL);
    QueryResult *resultMails = sDatabase.PQuery("SELECT COUNT(id) FROM `mail` WHERE `receiver` = '%u' AND `checked` = 0 AND `deliver_time` <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
    if (resultMails)
    {
        Field *fieldMail = resultMails->Fetch();
        plr->unReadMails = fieldMail[0].GetUInt8();
        delete resultMails;
    }

    // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
    resultMails = sDatabase.PQuery("SELECT MIN(`deliver_time`) FROM `mail` WHERE `receiver` = '%u' AND `checked` = 0", GUID_LOPART(playerGuid));
    if (resultMails)
    {
        Field *fieldMail = resultMails->Fetch();
        plr->m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
        delete resultMails;
    }

    SetPlayer(plr);

    Player *pCurrChar = GetPlayer();

    pCurrChar->SendDungeonDifficulty();

    WorldPacket data( SMSG_LOGIN_VERIFY_WORLD, 20 );
    data << plr->GetMapId();
    data << plr->GetPositionX();
    data << plr->GetPositionY();
    data << plr->GetPositionZ();
    data << plr->GetOrientation();
    SendPacket(&data);

    data.Initialize( SMSG_ACCOUNT_DATA_MD5, 128 );
    for(int i = 0; i < 32; i++)
        data << uint32(0);
    SendPacket(&data);

    pCurrChar->LoadIgnoreList();
    pCurrChar->SendFriendlist();
    pCurrChar->SendIgnorelist();

    // Send MOTD
    {
        data.Initialize(SMSG_MOTD, 50);                     // new in 2.0.1
        data << (uint32)0;

        uint32 linecount=0;
        string str_motd = sWorld.GetMotd();
        string::size_type pos, nextpos;

        pos = 0;
        while ( (nextpos= str_motd.find('@',pos)) != string::npos )
        {
            if (nextpos != pos)
            {
                data << str_motd.substr(pos,nextpos-pos);
                linecount++;
            }
            pos = nextpos+1;
        }

        if (pos<str_motd.length())
        {
            data << str_motd.substr(pos);
            linecount++;
        }

        data.put(0, linecount);

        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent motd (SMSG_MOTD)" );
    }

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << (uint8)GE_MOTD;
            data << (uint8)1;
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<pCurrChar->GetGUID();
            guild->BroadcastPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
        }
        else
        {
            // remove wrong guild data
            sLog.outError("Player %s (GUID: %u) marked as member not existed guild (id: %u), removing guild membership for player.",pCurrChar->GetName(),pCurrChar->GetGUIDLow(),pCurrChar->GetGuildId());
            pCurrChar->SetUInt32Value(PLAYER_GUILDID,0);
            pCurrChar->SetUInt32ValueInDB(PLAYER_GUILDID,0,pCurrChar->GetGUID());
        }
    }

    // rest_start

    // home bind stuff
    {
        QueryResult *result4 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `character_homebind` WHERE `guid` = '%u'", GUID_LOPART(playerGuid));
        if (result4)
        {
            Field *fields = result4->Fetch();
            _player->m_homebindMapId = fields[0].GetUInt32();
            _player->m_homebindZoneId = fields[1].GetUInt16();
            _player->m_homebindX = fields[2].GetFloat();
            _player->m_homebindY = fields[3].GetFloat();
            _player->m_homebindZ = fields[4].GetFloat();
            delete result4;
        }
        else
        {
            int plrace = GetPlayer()->getRace();
            int plclass = GetPlayer()->getClass();
            QueryResult *result5 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `playercreateinfo` WHERE `race` = '%u' AND `class` = '%u'", plrace, plclass);

            if(!result5)
            {
                sLog.outErrorDb("Table `playercreateinfo` not have data for race %u class %u , character can't be loaded.",plrace, plclass);
                LogoutPlayer(false);                        // without save
                return;
            }

            Field *fields = result5->Fetch();
            // store and send homebind for player
            _player->m_homebindMapId = fields[0].GetUInt32();
            _player->m_homebindZoneId = fields[1].GetUInt16();
            _player->m_homebindX = fields[2].GetFloat();
            _player->m_homebindY = fields[3].GetFloat();
            _player->m_homebindZ = fields[4].GetFloat();
            sDatabase.PExecute("INSERT INTO `character_homebind` (`guid`,`map`,`zone`,`position_x`,`position_y`,`position_z`) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GUID_LOPART(playerGuid), _player->m_homebindMapId, (uint32)_player->m_homebindZoneId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ);
            delete result5;
        }

        data.Initialize (SMSG_BINDPOINTUPDATE, 5*4);
        data << _player->m_homebindX << _player->m_homebindY << _player->m_homebindZ;
        data << (uint32) _player->m_homebindMapId;
        data << (uint32) _player->m_homebindZoneId;
        SendPacket (&data);

        DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
            _player->m_homebindMapId,_player->m_homebindZoneId,_player->m_homebindX,_player->m_homebindY, _player->m_homebindZ);
    }

    data.Initialize( SMSG_TUTORIAL_FLAGS, 8*32 );
    for (int i = 0; i < 8; i++)
        data << uint32( GetPlayer()->GetTutorialInt(i) );
    SendPacket(&data);
    //sLog.outDebug( "WORLD: Sent tutorial flags." );

    pCurrChar->_LoadSpellCooldowns();
    GetPlayer()->SendInitialSpells();
    GetPlayer()->SendInitialActionButtons();
    GetPlayer()->SendInitialReputations();

    /*if(GetPlayer()->getClass() == CLASS_HUNTER || GetPlayer()->getClass() == CLASS_ROGUE)
    {
        uint32 shiftdata=0x01;
        for(uint8 i=0;i<32;i++)
        {
            if ( 522753 & shiftdata )
            {
                data.Initialize(SMSG_SET_FLAT_SPELL_MODIFIER);
                data << uint8(i);
                data << uint8(5);
                data << uint16(1);
                data << uint16(0);
                SendPacket(&data);
            }
            shiftdata=shiftdata<<1;
        }
    }*/

    //Show cinematic at the first time that player login
    if( !GetPlayer()->getCinematic() )
    {
        GetPlayer()->setCinematic(1);

        ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(GetPlayer()->getRace());
        if(rEntry)
        {
            data.Initialize( SMSG_TRIGGER_CINEMATIC,4 );
            data << uint32(rEntry->startmovie);
            SendPacket( &data );
        }
    }

    pCurrChar->SendInitWorldStates();

    pCurrChar->CastSpell(pCurrChar, 836, true);             // LOGINEFFECT

    data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
    time_t gameTime = sWorld.GetGameTime();
    struct tm *lt = localtime(&gameTime);
    uint32 xmitTime = (lt->tm_year - 100) << 24 | lt->tm_mon  << 20 |
        (lt->tm_mday - 1) << 14 | lt->tm_wday << 11 |
        lt->tm_hour << 6 | lt->tm_min;
    data << xmitTime;
    data << (float)0.017f;                                  // game speed
    SendPacket( &data );

    GetPlayer()->UpdateHonorFields();

    QueryResult *result = sDatabase.PQuery("SELECT `guildid`,`rank` FROM `guild_member` WHERE `guid` = '%u'",pCurrChar->GetGUIDLow());

    if(result)
    {
        Field *fields = result->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete result;
    }
    else if(pCurrChar->GetGuildId())                        // clear guild related fields in case wrong data about non existed membership
    {
        pCurrChar->SetInGuild(0);
        pCurrChar->SetRank(0);
    }

    if (!MapManager::Instance().GetMap(pCurrChar->GetMapId(), pCurrChar)->AddInstanced(pCurrChar))
    {
        // TODO : Teleport to zone-in area
    }

    MapManager::Instance().GetMap(pCurrChar->GetMapId(), pCurrChar)->Add(pCurrChar);
    ObjectAccessor::Instance().InsertPlayer(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());

    if (pCurrChar->m_transport)
    {
        Transport* curTrans = pCurrChar->m_transport;
        pCurrChar->TeleportTo(curTrans->GetMapId(), curTrans->GetPositionX(), curTrans->GetPositionY(), curTrans->GetPositionZ(), curTrans->GetOrientation(), true, false);
    }

    sDatabase.PExecute("UPDATE `character` SET `online` = 1 WHERE `guid` = '%u'", pCurrChar->GetGUIDLow());
    loginDatabase.PExecute("UPDATE `account` SET `online` = 1 WHERE `id` = '%u'", GetAccountId());
    plr->SetInGameTime( getMSTime() );

    // set some aura effects after add player to map
    if(pCurrChar->HasAuraType(SPELL_AURA_MOD_STUN))
        pCurrChar->SetMovement(MOVE_ROOT);

    if(pCurrChar->HasAuraType(SPELL_AURA_MOD_ROOT))
    {
        WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
        data.append(pCurrChar->GetPackGUID());
        data << (uint32)2;
        pCurrChar->SendMessageToSet(&data,true);
    }

    // announce group about member online (must be after add to player list to receive announce to self)
    if(pCurrChar->groupInfo.group)
    {
        //pCurrChar->groupInfo.group->SendInit(this); // useless
        pCurrChar->groupInfo.group->SendUpdate();
    }

    // friend status
    data.Initialize(SMSG_FRIEND_STATUS, 19);
    data<<uint8(FRIEND_ONLINE);
    data<<pCurrChar->GetGUID();
    data<<uint8(1);
    data<<pCurrChar->GetAreaId();
    data<<pCurrChar->getLevel();
    data<<pCurrChar->getClass();
    pCurrChar->BroadcastPacketToFriendListers(&data);

    pCurrChar->SendEnchantmentDurations();                  // must be after add to map

    // Place character in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();

    // setting Ghost+speed if dead
    //if ( pCurrChar->m_deathState == DEAD )
    if ( pCurrChar->m_deathState != ALIVE )
    {
        // not blizz like, we must correctly save and load player instead...
        if(pCurrChar->getRace() == RACE_NIGHTELF)
            pCurrChar->CastSpell(pCurrChar, 20584, true, 0);// auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
        pCurrChar->CastSpell(pCurrChar, 8326, true, 0);     // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)

        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+41, 8326);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURA+42, 20584);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAFLAGS+6, 238);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURALEVELS+11, 514);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_AURAAPPLICATIONS+11, 65535);
        //pCurrChar->SetUInt32Value(UNIT_FIELD_DISPLAYID, 1825);
        //if (pCurrChar->getRace() == RACE_NIGHTELF)
        //{
        //    pCurrChar->SetSpeed(MOVE_RUN,  1.5f*1.2f, true);
        //    pCurrChar->SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
        //}
        //else
        //{
        //    pCurrChar->SetSpeed(MOVE_RUN,  1.5f, true);
        //    pCurrChar->SetSpeed(MOVE_SWIM, 1.5f, true);
        //}
        pCurrChar->SetMovement(MOVE_WATER_WALK);
    }

    // Load pet if any and player is alive
    if(pCurrChar->isAlive())
        pCurrChar->LoadPet();

    // show time before shutdown if shutdown planned.
    if(sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    if(pCurrChar->isGameMaster())
        SendNotification("GM mode is ON");
    m_playerLoading = false;
    pCurrChar->SendAllowMove();

    data.Initialize(SMSG_UNKNOWN_811, 4);
    data << uint32(0);
    SendPacket(&data);
}
Example #11
0
int main(int argc, char *argv[]) {
    if(2 > argc) {
        printf("Less address!\n");
        return 1;
    }
    Logger::logSetup();
    Logger::setLogLevel(0);  
    char *address = argv[1];
    char host[100] = {0};
    char path[1024*1024] = {0};
    char spec[200] = {0};
    int port = -1;
    sscanf(address, "http://%[-a-zA-Z0-9.]:%d%s", host, &port, path);
    if(0 == host[0] || -1 == port) {
        sscanf(address, "%[-a-zA-Z0-9.]:%d%s", host, &port, path);
    }
    if(0 == host[0] || -1 == port) {
        port = 80;
        sscanf(address, "http://%[-a-zA-Z0-9.]%s", host, path);
    }
    if(0 == host[0] || -1 == port) {
        sscanf(address, "%[-a-zA-Z0-9.]%s", host, path);
    }
    if(0 == host[0] || -1 == port) {
        printf("Wrong address!\n");
        return 1;
    }
    if(0 == path[0]) {
        path[0] = '/';
        path[1] = 0;
    }
    sprintf(spec, "tcp:%s:%d", host, port);
    Transport transport;
    transport.start();
    Connection *connection = NULL;
    HTTPPacketFactory factory;
    HTTPStreamer streamer(&factory);
    connection = transport.connect(spec, &streamer);
    if (NULL == connection) {
        printf("Failed to connect server %s\n", spec);
        exit(1);
    }
    
    HTTPPacket *requst = new HTTPPacket;
    requst->setMethod(HTTPPacket::HM_GET);
    requst->setURI(path);
    requst->addHeader("Accept", "*/*");
    requst->addHeader("Connection", "Keep-Alive");
    requst->addHeader("Host", (const char*)(spec+4));

    Packet *ret = connection->sendPacket(requst);
    HTTPPacket *reply = NULL;
    if (NULL != ret && ret->isRegularPacket() 
        && (reply = dynamic_cast<HTTPPacket*>(ret))) 
    {
        printf("------------reply from '%s' ----------\r\n", address);
        printf("%s %d %s\r\n", reply->getVersion() ? "HTTP/1.1" : "HTTP/1.0",
               reply->getStatusCode(), reply->getReasonPhrase());
        for (HTTPPacket::ConstHeaderIterator it = reply->headerBegin();
             it != reply->headerEnd(); it ++) 
        {
            printf("%s: %s\r\n", it->first, it->second);
        }
        printf("\r\n");
        if (reply->getBody()) {
            fwrite(reply->getBody(), 1, reply->getBodyLen(), stdout);
        }
        printf("\n-----------end of reply-------------------\n");
    } else {
        printf("Fail to get reply from '%s' ----------\r\n", address);
        ControlPacket *cmd = dynamic_cast<ControlPacket*>(ret);
        if (cmd) {
            printf("%s", cmd->what());
        }
    }
    connection->subRef();
    transport.stop();
    transport.wait();
    return 0;
}
Example #12
0
void showVehichle( Transport& transport ) {
    transport.showWheels();
}
Example #13
0
    //teleport to creature
    static bool HandleGoCreatureCommand(ChatHandler* handler, char const* args)
    {
        if (!*args)
            return false;

        Player* player = handler->GetSession()->GetPlayer();

        // "id" or number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
        char* param1 = handler->extractKeyFromLink((char*)args, "Hcreature");
        if (!param1)
            return false;

        std::ostringstream whereClause;

        // User wants to teleport to the NPC's template entry
        if (strcmp(param1, "id") == 0)
        {
            // Get the "creature_template.entry"
            // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r
            char* tail = strtok(NULL, "");
            if (!tail)
                return false;
            char* id = handler->extractKeyFromLink(tail, "Hcreature_entry");
            if (!id)
                return false;

            int32 entry = atoi(id);
            if (!entry)
                return false;

            whereClause << "WHERE id = '" << entry << '\'';
        }
        else
        {
            int32 guid = atoi(param1);

            // Number is invalid - maybe the user specified the mob's name
            if (!guid)
            {
                std::string name = param1;
                WorldDatabase.EscapeString(name);
                whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name " _LIKE_" '" << name << '\'';
            }
            else
                whereClause <<  "WHERE guid = '" << guid << '\'';
        }

        QueryResult result = WorldDatabase.PQuery("SELECT position_x, position_y, position_z, orientation, map, guid, id FROM creature %s", whereClause.str().c_str());
        if (!result)
        {
            handler->SendSysMessage(LANG_COMMAND_GOCREATNOTFOUND);
            handler->SetSentErrorMessage(true);
            return false;
        }
        if (result->GetRowCount() > 1)
            handler->SendSysMessage(LANG_COMMAND_GOCREATMULTIPLE);

        Field* fields = result->Fetch();
        float x = fields[0].GetFloat();
        float y = fields[1].GetFloat();
        float z = fields[2].GetFloat();
        float o = fields[3].GetFloat();
        uint32 mapId = fields[4].GetUInt16();

        Transport* transport = NULL;

        if (!MapManager::IsValidMapCoord(mapId, x, y, z, o) || sObjectMgr->IsTransportMap(mapId))
        {
            handler->PSendSysMessage(LANG_INVALID_TARGET_COORD, x, y, mapId);
            handler->SetSentErrorMessage(true);
            return false;
        }

        // stop flight if need
        if (player->IsInFlight())
        {
            player->GetMotionMaster()->MovementExpired();
            player->CleanupAfterTaxiFlight();
        }
        // save only in non-flight case
        else
            player->SaveRecallPosition();

        if (player->TeleportTo(mapId, x, y, z, o))
        {
            if (transport)
                transport->AddPassenger(player);
        }
        return true;
    }
Example #14
0
void VMEvent::create_event_request(PacketInputStream *in, 
                                   PacketOutputStream *out, jbyte event_kind)
{

  UsingFastOops fast_oops;
  VMEvent::Fast ep;
  int i;
  bool error = false;
  VMEventModifier::Fast current_modifier_slot, new_modifier, event_modifier;
 
  ep = create_vm_event_request();
    
  ep().set_event_kind(event_kind);
  ep().set_suspend_policy(in->read_byte());
  ep().set_num_modifiers(in->read_int());
  Transport *transport = in->transport();
  ep().set_transport(transport);
#if ENABLE_ISOLATES
  ep().set_task_id(transport->task_id());
  TaskGCContext tmp(transport->task_id());
#endif
  for (i=0; i < ep().num_modifiers(); i++) {

    new_modifier = VMEventModifier::new_modifier(in, out, error);

    if (error) {
      // some sort of error happened
      if (out->error() != 0) {
        out->send_packet();
      }
      return;
    }
    if (new_modifier.is_null()) {
      // Most likely we don't support this modifier
      continue;
    }
    if (event_kind == JDWP_EventKind_BREAKPOINT &&
        new_modifier().mod_kind() ==
        JDWP_EventRequest_Set_Out_modifiers_Modifier_LocationOnly) {
      UsingFastOops fastoops2;
      LocationModifier *lmp = (LocationModifier *)&new_modifier;
      VMEvent::Fast epb = VMEvent::find_breakpoint_event(lmp,
                                                         transport->task_id());
      if (epb.not_null()) {
        out->write_int(epb().event_id());
        out->send_packet();
        //        out->send_error(JDWP_Error_NOT_IMPLEMENTED);
        // there's a breakpoint here already, don't bother installing another
        return;
      }
#if ENABLE_ISOLATES
      InstanceClass::Raw ic = JavaDebugger::get_object_by_id(new_modifier().clazz_id());
      if (ic().class_id() < ROM::number_of_system_classes()) {
        // breakpoint in system class, allow in any task
        ep().set_task_id(-1);
      }
      // See if any other task already has a breakpoint here.
      epb = find_breakpoint_event(lmp);
      if (!epb.is_null()) {
        // Has to be some other task since we haven't linked in this event
        GUARANTEE(epb().task_id() != transport->task_id(),
                  "Breakpoint already inserted");
        LocationModifier::Raw lmod = get_modifier(&epb,
                   JDWP_EventRequest_Set_Out_modifiers_Modifier_LocationOnly);
        GUARANTEE(!lmod.is_null(),"Breakpoint event has no location modifier");
        lmp->set_save_opcode(lmod().save_opcode());
      } else {
#endif
        /* Return an error back to the debugger if 
         * the breakpoint could not be installed.
         */
        lmp->unlink_method();
        lmp->save_method_entry();
        if (lmp->set_method_opcode(Bytecodes::_breakpoint, true) ==
            false){
          out->send_error(JDWP_Error_INVALID_LOCATION);
          return;
        }
#if ENABLE_ISOLATES
      }
#endif
    }
    // insert the mod at the end of the list of modifiers
    event_modifier = ep().mods();
    if (event_modifier.is_null()) {
      ep().set_mods(&new_modifier);
      current_modifier_slot = ep().mods();
    } else {
      current_modifier_slot().set_next(&new_modifier);
      current_modifier_slot = new_modifier;
    }
  }
#ifdef AZZERT
  if (TraceDebugger) {
    tty->print_cr("Create Event: xprt = 0x%x, ep = 0x%lx, id = 0x%x, kind = 0x%lx, suspend = 0x%lx, num mods = 0x%lx",
                  transport->obj(),
                  ep.obj(), 
                  ep().event_id(),
                  ep().event_kind(), 
                  ep().suspend_policy(), 
                  ep().num_modifiers());
  }
#endif
  ep().set_next((VMEvent *)Universe::vmevent_request_head());
  *Universe::vmevent_request_head() = ep;
  out->write_int(ep().event_id());
  out->send_packet();
  VMEvent::add_notification(JDWP_eventkind_to_dbg_eventkind(event_kind));
}
Example #15
0
int transport_example2(int job) {

    try {

        cout << "Multicomponent transport properties." << endl;
        if (job > 0) {
            cout << "Viscosity, thermal conductivity, and thermal diffusion\n"
                " coefficients at 2 atm for a "
                 << "range of temperatures" << endl;
        }
        if (job <= 1) return 0;

        // header
        writeCanteraHeader(cout);


        // create a gas mixture, and set its state

        IdealGasMix gas("gri30.cti", "gri30");
        doublereal temp = 2000.0;
        doublereal pres = 2.0*OneAtm;
        gas.setState_TPX(temp, pres, "H2:1.0, O2:0.5, CH4:0.1, N2:0.2");
        equilibrate(gas,"TP");


        // create a transport manager that implements
        // multicomponent transport properties

        Transport* tr = newTransportMgr("Multi",  &gas);
        int nsp = gas.nSpecies();


        // create a 2D array to hold the outputs
        int ntemps = 20;
        Array2D output(nsp+3, ntemps);

        // main loop
        clock_t t0 = clock();
        for (int i = 0; i < ntemps; i++) {
            temp = 500.0 + 100.0*i;
            gas.setState_TP(temp, pres);
            output(0,i) = temp;
            output(1,i) = tr->viscosity();
            output(2,i) = tr->thermalConductivity();
            tr->getThermalDiffCoeffs(&output(3,i));
        }
        clock_t t1 = clock();

        // make a Tecplot data file and an Excel spreadsheet
        string plotTitle = "transport example 2: "
                           "multicomponent transport properties";
        plotTransportSoln("tr2.dat", "TEC", plotTitle, gas, output);
        plotTransportSoln("tr2.csv", "XL", plotTitle, gas, output);

        // print final temperature and timing data
        doublereal tmm = 1.0*(t1 - t0)/CLOCKS_PER_SEC;
        cout << " time = " << tmm << endl << endl;

        cout << "Output files:" << endl
             << "  tr2.csv    (Excel CSV file)" << endl
             << "  tr2.dat    (Tecplot data file)" << endl;

        return 0;
    }

    // handle exceptions thrown by Cantera
    catch (CanteraError) {
        showErrors(cout);
        cout << " terminating... " << endl;
        appdelete();
        return -1;
    }
}
Example #16
0
int32 MoveSplineInit::Launch()
{
    float realSpeedRun = 0.0f;
    MoveSpline& move_spline = *unit.movespline;

    Transport* newTransport = NULL;
    if (args.transportGuid)
        newTransport = HashMapHolder<Transport>::Find(ObjectGuid(HIGHGUID_MO_TRANSPORT, args.transportGuid));
    Vector3 real_position(unit.GetPositionX(), unit.GetPositionY(), unit.GetPositionZ());
    // there is a big chance that current position is unknown if current state is not finalized, need compute it
    // this also allows calculate spline position and update map position in much greater intervals
    if (!move_spline.Finalized())
    {
        real_position = move_spline.ComputePosition();
        Transport* oldTransport = NULL;
        if (move_spline.GetTransportGuid())
            oldTransport = HashMapHolder<Transport>::Find(ObjectGuid(HIGHGUID_MO_TRANSPORT, move_spline.GetTransportGuid()));
        if (oldTransport)
            oldTransport->CalculatePassengerPosition(real_position.x, real_position.y, real_position.z);
    }
    if (newTransport)
        newTransport->CalculatePassengerOffset(real_position.x, real_position.y, real_position.z);

    if (args.path.empty())
    {
        // should i do the things that user should do?
        MoveTo(real_position);
    }

    // corrent first vertex
    args.path[0] = real_position;
    uint32 moveFlags = unit.m_movementInfo.GetMovementFlags();
    uint32 oldMoveFlags = moveFlags;
    if (args.flags.done)
    {
        args.flags = MoveSplineFlag::Done;
        moveFlags &= ~(MOVEFLAG_SPLINE_ENABLED | MOVEFLAG_MASK_MOVING);
    }
    else
    {
        moveFlags |= (MOVEFLAG_SPLINE_ENABLED | MOVEFLAG_FORWARD);

        if (args.flags.runmode)
            moveFlags &= ~MOVEFLAG_WALK_MODE;
        else
            moveFlags |= MOVEFLAG_WALK_MODE;
    }

    if (newTransport)
        moveFlags |= MOVEFLAG_ONTRANSPORT;
    else
        moveFlags &= ~MOVEFLAG_ONTRANSPORT;

    if (args.velocity == 0.f)
        realSpeedRun = args.velocity = unit.GetSpeed(SelectSpeedType(moveFlags));
    else
        realSpeedRun = unit.GetSpeed(MOVE_RUN);

    if (!args.Validate(&unit))
        return 0;

    unit.m_movementInfo.SetMovementFlags((MovementFlags)moveFlags);
    unit.clearUnitState(UNIT_STAT_CLIENT_ROOT);
    move_spline.SetMovementOrigin(movementType);
    move_spline.Initialize(args);

    WorldPacket data(SMSG_MONSTER_MOVE, 64);
    data << unit.GetPackGUID();
    if (newTransport)
    {
        data.SetOpcode(SMSG_MONSTER_MOVE_TRANSPORT);
        data << newTransport->GetPackGUID();
    }
    if (unit.GetTransport() && unit.GetTransport() != newTransport)
        unit.GetTransport()->RemovePassenger(&unit);
    if (newTransport && unit.GetTransport() != newTransport)
        newTransport->AddPassenger(&unit);

    // Stop packet
    if (args.flags.done)
    {
        data << real_position.x << real_position.y << real_position.z;
        data << move_spline.GetId();
        data << uint8(1); // MonsterMoveStop=1
    }
    else
        move_spline.setLastPointSent(PacketBuilder::WriteMonsterMove(move_spline, data));
    // Compress data or not ?
    bool compress = false;
    if (!args.flags.done && args.velocity > 4 * realSpeedRun)
        compress = true;
    else if ((data.wpos() + 2) > 0x10)
        compress = true;
    else if (unit.hasUnitState(UNIT_STAT_CLIENT_ROOT))
        compress = true;
    // Since packet size is stored with an uint8, packet size is limited for compressed packets
    if ((data.wpos() + 2) > 0xFF)
        compress = false;

    MovementData mvtData(compress ? NULL : &unit);
    // Nostalrius: client has a hardcoded limit to spline movement speed : 4*runSpeed.
    // We need to fix this, in case of charges for example (if character has movement slowing effects)
    if (args.velocity > 4 * realSpeedRun && !args.flags.done) // From client
        mvtData.SetUnitSpeed(SMSG_SPLINE_SET_RUN_SPEED, unit.GetObjectGuid(), args.velocity);
    if (unit.hasUnitState(UNIT_STAT_CLIENT_ROOT))
        mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_UNROOT, unit.GetObjectGuid());
    if (oldMoveFlags & MOVEFLAG_WALK_MODE && !(moveFlags & MOVEFLAG_WALK_MODE)) // Switch to run mode
        mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_SET_RUN_MODE, unit.GetObjectGuid());
    if (moveFlags & MOVEFLAG_WALK_MODE && !(oldMoveFlags & MOVEFLAG_WALK_MODE)) // Switch to walk mode
        mvtData.SetSplineOpcode(SMSG_SPLINE_MOVE_SET_WALK_MODE, unit.GetObjectGuid());

    mvtData.AddPacket(data);
    // Do not forget to restore velocity after movement !
    if (args.velocity > 4 * realSpeedRun && !args.flags.done)
        mvtData.SetUnitSpeed(SMSG_SPLINE_SET_RUN_SPEED, unit.GetObjectGuid(), realSpeedRun);
    // Restore correct walk mode for players
    if (unit.GetTypeId() == TYPEID_PLAYER && (moveFlags & MOVEFLAG_WALK_MODE) != (oldMoveFlags & MOVEFLAG_WALK_MODE))
        mvtData.SetSplineOpcode(oldMoveFlags & MOVEFLAG_WALK_MODE ? SMSG_SPLINE_MOVE_SET_WALK_MODE : SMSG_SPLINE_MOVE_SET_RUN_MODE, unit.GetObjectGuid());
    if (compress)
    {
        WorldPacket data2;
        mvtData.BuildPacket(data2);
        unit.SendMovementMessageToSet(std::move(data2), true);
    }
    return move_spline.Duration();
}
Example #17
0
Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid /*= 0*/, Map* map /*= NULL*/, uint32 phaseid /*= 0*/, uint32 phasegroup /*= 0*/)
{
    // instance case, execute GetGameObjectEntry hook
    if (map)
    {
        // SetZoneScript() is called after adding to map, so fetch the script using map
        if (map->IsDungeon())
            if (InstanceScript* instance = static_cast<InstanceMap*>(map)->GetInstanceScript())
                entry = instance->GetGameObjectEntry(0, entry);

        if (!entry)
            return NULL;
    }

    TransportTemplate const* tInfo = GetTransportTemplate(entry);
    if (!tInfo)
    {
        TC_LOG_ERROR("sql.sql", "Transport %u will not be loaded, `transport_template` missing", entry);
        return NULL;
    }

    // create transport...
    Transport* trans = new Transport();

    // ...at first waypoint
    TaxiPathNodeEntry const* startNode = tInfo->keyFrames.begin()->Node;
    uint32 mapId = startNode->MapID;
    float x = startNode->Loc.X;
    float y = startNode->Loc.Y;
    float z = startNode->Loc.Z;
    float o = tInfo->keyFrames.begin()->InitialOrientation;

    // initialize the gameobject base
    ObjectGuid::LowType guidLow = guid ? guid : ASSERT_NOTNULL(map)->GenerateLowGuid<HighGuid::Transport>();
    if (!trans->Create(guidLow, entry, mapId, x, y, z, o, 255))
    {
        delete trans;
        return NULL;
    }

    if (phaseid)
        trans->SetInPhase(phaseid, false, true);

    if (phasegroup)
        for (auto ph : sDB2Manager.GetPhasesForGroup(phasegroup))
            trans->SetInPhase(ph, false, true);

    if (MapEntry const* mapEntry = sMapStore.LookupEntry(mapId))
    {
        if (mapEntry->Instanceable() != tInfo->inInstance)
        {
            TC_LOG_ERROR("entities.transport", "Transport %u (name: %s) attempted creation in instance map (id: %u) but it is not an instanced transport!", entry, trans->GetName().c_str(), mapId);
            delete trans;
            return NULL;
        }
    }

    // use preset map for instances (need to know which instance)
    trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, NULL));
    if (map && map->IsDungeon())
        trans->m_zoneScript = map->ToInstanceMap()->GetInstanceScript();

    // Passengers will be loaded once a player is near
    HashMapHolder<Transport>::Insert(trans);
    trans->GetMap()->AddToMap<Transport>(trans);
    return trans;
}
Example #18
0
void HHVM_FUNCTION(header, const String& str, bool replace /* = true */,
                   int http_response_code /* = 0 */) {
  if (HHVM_FN(headers_sent)()) {
    raise_warning("Cannot modify header information - headers already sent");
  }

  String header = HHVM_FN(rtrim)(str);

  // new line safety check
  if (header.find('\n') >= 0 || header.find('\r') >= 0) {
    raise_error("Header may not contain more than a single header, "
                "new line detected");
    return;
  }

  Transport *transport = g_context->getTransport();
  if (transport && header.size()) {
    const char *header_line = header.data();

    // handle single line of status code
    if ((header.size() >= 5 && strncasecmp(header_line, "HTTP/", 5) == 0) ||
        (header.size() >= 7 && strncasecmp(header_line, "Status:", 7) == 0)) {
      int code = 200;
      const char *reason = nullptr;
      for (const char *ptr = header_line + 5; *ptr; ptr++) {
        if (*ptr == ' ' && *(ptr + 1) != ' ') {
          code = atoi(ptr + 1);
          for (ptr++; *ptr; ptr++) {
            if (*ptr == ' ' && *(ptr + 1) != ' ') {
              reason = ptr + 1;
              break;
            }
          }
          break;
        }
      }
      if (code) {
        transport->setResponse(code, reason);
      }
      return;
    }

    const char *colon_offset = strchr(header_line, ':');
    String newHeader;
    if (colon_offset) {
      if (!strncasecmp(header_line, "Content-Type",
                       colon_offset - header_line)) {
        const char *ptr = colon_offset+1, *mimetype = NULL;
        while (*ptr == ' ') ptr++;
        mimetype = ptr;
        if (strncmp(mimetype, "text/", 5) == 0 &&
            strstr(mimetype, "charset=") == NULL) {
          newHeader = header + ";charset=utf-8";
        }
      }
    }
    if (replace) {
      transport->replaceHeader(newHeader.empty() ? header : newHeader);
    } else {
      transport->addHeader(newHeader.empty() ? header : newHeader);
    }
    if (http_response_code) {
      transport->setResponse(http_response_code);
    }
  }
}
Example #19
0
int main( int argc, char * argv[] )
{
	// initialize and create transport
	
	TransportType type = Transport_LAN;
	
	if ( !Transport::Initialize( Transport_LAN ) )
	{
		printf( "failed to initialize transport layer\n" );
		return 1;
	}
	
	Transport * transport = Transport::Create();
	
	if ( !transport )
	{
		printf( "could not create transport\n" );
		return 1;
	}
	
	// enter lobby (transport specific)
	
	switch ( type )
	{
		case Transport_LAN:
		{
			TransportLAN * lan_transport = dynamic_cast<TransportLAN*>( transport );
			lan_transport->EnterLobby();
		}
		break;
		
		default:
			break;
	}

	// main loop

	const float DeltaTime = 1.0f / 30.0f;

	float accumulator = 0.0f;

	while ( true )
	{
		accumulator += DeltaTime;

		while ( accumulator >= 1.5f )
		{
			switch ( type )
			{
				case Transport_LAN:
				{
					TransportLAN * lan_transport = dynamic_cast<TransportLAN*>( transport );
					printf( "---------------------------------------------\n" );
					const int entryCount = lan_transport->GetLobbyEntryCount();
					for ( int i = 0; i < entryCount; ++i )
					{
						TransportLAN::LobbyEntry entry;
						if ( lan_transport->GetLobbyEntryAtIndex( i, entry ) )
							printf( "%s -> %s\n", entry.name, entry.address );
					}
					printf( "---------------------------------------------\n" );
				}
				break;

				default:
					break;
			}

			accumulator -= 1.5f;
		}
		
		transport->Update( DeltaTime );
		
		wait_seconds( DeltaTime );
	}
	
	// shutdown
	
	Transport::Destroy( transport );
	
	Transport::Shutdown();

	return 0;
}
Example #20
0
Transport* TransportMgr::CreateTransport(uint32 entry, Map* map /*= NULL*/)
{
    // instance case, execute GetGameObjectEntry hook
    if (map)
    {
        // SetZoneScript() is called after adding to map, so fetch the script using map
        if (map->IsDungeon())
            if (InstanceScript* instance = static_cast<InstanceMap*>(map)->GetInstanceScript())
                entry = instance->GetGameObjectEntry(0, entry);

        if (!entry)
            return NULL;
    }

    TransportTemplate const* tInfo = GetTransportTemplate(entry);
    if (!tInfo)
    {
        sLog->outErrorDb("Transport %u will not be loaded, `transport_template` missing", entry);
        return NULL;
    }

    // create transport...
    Transport* trans = new Transport();

    // ...at first waypoint
    TaxiPathNodeEntry const* startNode = tInfo->keyFrames.begin()->node;
    uint32 mapId = startNode->mapid;
    float x = startNode->x;
    float y = startNode->y;
    float z = startNode->z;
    float o = 1.0f;

    // initialize the gameobject base
    if (!trans->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_MO_TRANSPORT), entry, mapId, x, y, z, o, 100, 0))
    {
        delete trans;
        return NULL;
    }

    if (MapEntry const* mapEntry = sMapStore.LookupEntry(mapId))
    {
        if (uint32(mapEntry->Instanceable()) != trans->GetGOInfo()->moTransport.inInstance)
        {
            sLog->outError("Transport %u (name: %s) attempted creation in instance map (id: %u) but it is not an instanced transport!", entry, trans->GetName(), mapId);
            delete trans;
            return NULL;
        }
    }

    // use preset map for instances (need to know which instance)
    trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, trans, 0));
    trans->SetZoneScript();

    // Get all spawns on Transport map
    if (uint32 mapId = trans->GetGOInfo()->moTransport.mapID)
    {
        CellObjectGuidsMap const& cells = sObjectMgr->GetMapObjectGuids(mapId, REGULAR_DIFFICULTY);
        CellGuidSet::const_iterator guidEnd;
        for (CellObjectGuidsMap::const_iterator cellItr = cells.begin(); cellItr != cells.end(); ++cellItr)
        {
            // Creatures on transport
            guidEnd = cellItr->second.creatures.end();
            for (CellGuidSet::const_iterator guidItr = cellItr->second.creatures.begin(); guidItr != guidEnd; ++guidItr)
            {
                CreatureData const* data = sObjectMgr->GetCreatureData(*guidItr);
                trans->CreateNPCPassenger(data->id, data->posX, data->posY, data->posZ, data->orientation, data);
            }

            // GameObjects on transport
        }
    }

    // register in container for updates
    _transportUpdates.insert(trans);

    // and in container designed for quicker access by mapId
    for (std::set<uint32>::const_iterator i = tInfo->mapsUsed.begin(); i != tInfo->mapsUsed.end(); ++i)
        _transportMap[*i].insert(trans);

    trans->AddToWorld();
    if (map)
        trans->UpdateForMap(map);

    return trans;
}
Example #21
0
int64_t HHVM_FUNCTION(hphp_thread_type) {
  Transport *transport = g_context->getTransport();
  return transport ? static_cast<int64_t>(transport->getThreadType()) : -1;
}
        bool CheckPlayerOnTransport()
        {
            Transport * pTransport = NULL;

            if (!pInstance)
                return false;

            if (IsFriendlyCommander)
                return false; // Le commandant ami ne doit pas check les joueurs sur le transport

            pTransport = GetTransportByGUID(me, pInstance->GetData64(DATA_GUNSHIP_TRANSPORT_SECOND));

            if (!pTransport)
                return false;

            std::set<Player*> pSet = pTransport->GetPassengers();


            if(pSet.empty()) // Stop l'attaque si personne sur le transport
            {
                if (me->isInCombat())
                    EnterEvadeMode();

                return false;
            }

            bool checkPassed = true;

            if (!me->isInCombat()) // Débute l'attaque si un joueur arrive sur le transport
            {
                checkPassed = false;
            }
            else
            {
                if (Unit * victim = me->getVictim())
                {
                    if (victim->GetTypeId() != TYPEID_PLAYER)
                    {
                        checkPassed = false;
                    }
                    else if (victim->GetTransport())
                    {
                        if (victim->GetTransport()->GetGUID() != pInstance->GetData64(DATA_GUNSHIP_TRANSPORT_SECOND))
                            checkPassed = false;

                        if (victim->GetVehicle())
                            checkPassed = false;

                        if (!victim->isAlive())
                            checkPassed = false;
                    }
                    else
                        checkPassed = false;
                }
                else
                    checkPassed = false;
            }

            if (!checkPassed)
            {
                Player * pPassenger = MistCore::Containers::SelectRandomContainerElement(pSet);

                if (!pPassenger)
                    if (me->isInCombat())
                        EnterEvadeMode();

                if(!pPassenger->IsHostileTo(me))
                    if (me->isInCombat())
                        EnterEvadeMode();

                me->CombatStop();
                AttackStart(pPassenger);
                return false;
            }

            return true;
        }
Example #23
0
void MapManager::LoadTransports()
{
    QueryResult *result = WorldDatabase.Query("SELECT entry, name, period FROM transports");

    uint32 count = 0;

    if( !result )
    {
        barGoLink bar( 1 );
        bar.step();

        sLog.outString();
        sLog.outString( ">> Loaded %u transports", count );
        return;
    }

    barGoLink bar( result->GetRowCount() );

    do
    {
        bar.step();

        Transport *t = new Transport;

        Field *fields = result->Fetch();

        uint32 entry = fields[0].GetUInt32();
        std::string name = fields[1].GetCppString();
        t->m_period = fields[2].GetUInt32();

        const GameObjectInfo *goinfo = objmgr.GetGameObjectInfo(entry);

        if(!goinfo)
        {
            sLog.outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template missing", entry, name.c_str());
            delete t;
            continue;
        }

        if(goinfo->type != GAMEOBJECT_TYPE_MO_TRANSPORT)
        {
            sLog.outErrorDb("Transport ID:%u, Name: %s, will not be loaded, gameobject_template type wrong", entry, name.c_str());
            delete t;
            continue;
        }

        // sLog.outString("Loading transport %d between %s, %s", entry, name.c_str(), goinfo->name);

        std::set<uint32> mapsUsed;

        if(!t->GenerateWaypoints(goinfo->moTransport.taxiPathId, mapsUsed))
            // skip transports with empty waypoints list
        {
            sLog.outErrorDb("Transport (path id %u) path size = 0. Transport ignored, check DBC files or transport GO data0 field.",goinfo->moTransport.taxiPathId);
            delete t;
            continue;
        }

        float x, y, z, o;
        uint32 mapid;
        x = t->m_WayPoints[0].x; y = t->m_WayPoints[0].y; z = t->m_WayPoints[0].z; mapid = t->m_WayPoints[0].mapid; o = 1;

                                                            // creates the Gameobject
        if(!t->Create(entry, mapid, x, y, z, o, 100, 0))
        {
            delete t;
            continue;
        }

        m_Transports.insert(t);

        for (std::set<uint32>::iterator i = mapsUsed.begin(); i != mapsUsed.end(); ++i)
            m_TransportsByMap[*i].insert(t);

        //If we someday decide to use the grid to track transports, here:
        //MapManager::Instance().LoadGrid(mapid,x,y,true);
        //t->GetMap()->Add<GameObject>((GameObject *)t);
        ++count;
    } while(result->NextRow());
    delete result;

    sLog.outString();
    sLog.outString( ">> Loaded %u transports", count );

    // check transport data DB integrity
    result = WorldDatabase.Query("SELECT gameobject.guid,gameobject.id,transports.name FROM gameobject,transports WHERE gameobject.id = transports.entry");
    if(result)                                              // wrong data found
    {
        do
        {
            Field *fields = result->Fetch();

            uint32 guid  = fields[0].GetUInt32();
            uint32 entry = fields[1].GetUInt32();
            std::string name = fields[2].GetCppString();
            sLog.outErrorDb("Transport %u '%s' have record (GUID: %u) in `gameobject`. Transports DON'T must have any records in `gameobject` or its behavior will be unpredictable/bugged.",entry,name.c_str(),guid);
        }
        while(result->NextRow());

        delete result;
    }
}
// This method is used when something needs to find out the details about one of the commands
// that this object can perform..
void HostFilterComponent::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
{
    const int none = 0;
    const int cmd = ModifierKeys::commandModifier;
    // const int shift = ModifierKeys::shiftModifier;

    GraphComponent* graph = main->getGraph ();
    Transport* transport = getFilter()->getTransport();

    switch (commandID)
    {
    //----------------------------------------------------------------------------------------------
    case CommandIDs::pluginOpen:
        result.setInfo (T("Open Plugin..."), T("Open a plugin"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('l'), cmd);
        result.setActive (true);
        break;
    case CommandIDs::pluginClose:
        {
        result.setInfo (T("Close Plugins"), T("Close selected plugins"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('k'), cmd);
        // TODO - have to update this !
//        GraphComponent* track = tracks.getUnchecked (0);
//        result.setActive ((track ? (track->getSelectedPlugin () != -1) : false));
        result.setActive (false);
        break;
        }
    case CommandIDs::pluginClear:
        {
        result.setInfo (T("Clear Plugins"), T("Close all plugins"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('j'), cmd);
        result.setActive ((graph ? (graph->getPluginsCount () > 2) : false));
        break;
        }
    case CommandIDs::showPluginListEditor:
        {
        result.setInfo (T("Show Plugin List"), T("Show plugin list window"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('p'), cmd);
        result.setActive (true);
        break;
        }
    //----------------------------------------------------------------------------------------------
#ifndef JOST_VST_PLUGIN
    case CommandIDs::audioOptions:
        {
        result.setInfo (T("Audio & MIDI Settings..."), T("Show device manager"), CommandCategories::audio, 0);
        // result.addDefaultKeypress (KeyPress::backspaceKey, none);
        result.setActive (true);
        break;
        }
#endif
    case CommandIDs::audioPlay:
        {
        result.setInfo (T("Play"), T("Play sequencers"), CommandCategories::audio, 0);
        if (! transport->isPlaying())
            result.addDefaultKeypress (KeyPress::spaceKey, none);
        result.setActive (! transport->isPlaying());
        break;
        }
    case CommandIDs::audioPlayPause:
        {
        if (transport->isPlaying())
            result.setInfo (T("Pause"), T("Pause sequencers"), CommandCategories::audio, 0);
        else
            result.setInfo (T("Play"), T("Play sequencers"), CommandCategories::audio, 0);
         result.addDefaultKeypress (KeyPress::spaceKey, none);
        break;
        }
    case CommandIDs::audioStop:
        {
        result.setInfo (T("Stop"), T("Stop sequencers"), CommandCategories::audio, 0);
        if (transport->isPlaying())
            result.addDefaultKeypress (KeyPress::spaceKey, none);
        result.setActive (transport->isPlaying());
        break;
        }
    case CommandIDs::audioRecord:
        {
        result.setInfo (T("Record"), T("Activate recording"), CommandCategories::audio, 0);
        result.addDefaultKeypress (T('r'), cmd);
        result.setTicked (transport->isRecording());
        result.setActive (true);
        break;
        }
    case CommandIDs::audioRewind:
        {
        result.setInfo (T("Rewind"), T("Rewind sequencers"), CommandCategories::audio, 0);
        result.addDefaultKeypress (KeyPress::backspaceKey, none);
        result.setActive (transport->getPositionInFrames() != 0);
        break;
        }
    case CommandIDs::audioLoop:
        {
        result.setInfo (T("Looping"), T("Loop sequencers"), CommandCategories::audio, 0);
        result.addDefaultKeypress (T('l'), cmd);
        result.setTicked (transport->isLooping());
        result.setActive (true);
        break;
        }
    //----------------------------------------------------------------------------------------------
    case CommandIDs::audioStemsStartStop:
        {
        int renderNumber = 0;
        if (getHost()->isStemRenderingActive(renderNumber))
         result.setInfo (T("Stop rendering stems (" + String(renderNumber) + String(")")), T("Stop rendering stems"), CommandCategories::audio, 0);
        else
         result.setInfo (T("Start rendering stems (" + String(renderNumber) + String(")")), T("Start rendering stems"), CommandCategories::audio, 0);
   
        result.setActive (true);
        break;
        }
    case CommandIDs::audioStemsSetup:
        {
        result.setInfo (T("Setup stem render..."), T("Stem Setup"), CommandCategories::audio, 0);
        result.setActive (true);
        break;
        }
    //----------------------------------------------------------------------------------------------
    case CommandIDs::sessionNew:
        {
        result.setInfo (T("New Session"), T("New session"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('n'), cmd);
        result.setActive (true);
        break;
        }
    case CommandIDs::sessionLoad:
        result.setInfo (T("Open Session..."), T("Open a session"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('a'), cmd);
        result.setActive (true);
        break;
    case CommandIDs::sessionSave:
        {
        result.setInfo (T("Save Session As..."), T("Save a session to a specified file"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('s'), ModifierKeys::commandModifier | ModifierKeys::shiftModifier);
        result.setActive ((graph ? (graph->getPluginsCount () > 0) : false));
        break;
        }
    case CommandIDs::sessionSaveNoPrompt:
        {
        result.setInfo (T("Save Session"), T("Save session to existing file"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('s'), cmd);
        result.setActive ((graph ? (graph->getPluginsCount () > 0) : false));
        break;
        }
    //----------------------------------------------------------------------------------------------
    case CommandIDs::appToolbar:
        result.setInfo (T("Edit toolbar"), T("Edit toolbar items"), CommandCategories::about, 0);
        result.setActive (toolbar != 0);
        break;
    case CommandIDs::appBrowser:
        result.setInfo (T("Show/Hide browser"), T("Show or hide the file browser"), CommandCategories::about, 0);
        result.setActive (true);
        break;
    case CommandIDs::appFullScreen:
        result.setInfo (T("Full Screen"), T("Set main window full screen"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('t'), cmd);
        result.setActive (true);
        break;
    case CommandIDs::appExit:
        result.setInfo (T("Quit"), T("Quit Jive"), CommandCategories::file, 0);
        result.addDefaultKeypress (T('q'), cmd);
        result.setActive (true);
        break;
    case CommandIDs::appAbout:
        result.setInfo (T("About..."), T("About Jive"), CommandCategories::about, 0);
        result.setActive (true);
        break;
    //----------------------------------------------------------------------------------------------
    default:
        break;
    }
}
Example #25
0
void WorldSession::HandlePlayerLoginOpcode( WorldPacket & recv_data )
{
    m_playerLoading = true;
    uint64 playerGuid = 0;

    DEBUG_LOG( "WORLD: Recvd Player Logon Message" );

    recv_data >> playerGuid;

    Player* plr = new Player(this);
    ASSERT(plr);

    plr->SetSession(this);
    // "GetAccountId()==db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools)
    if(!plr->LoadFromDB(GUID_LOPART(playerGuid)))
    {
        m_playerLoading = false;
        return;
    }
    //plr->_RemoveAllItemMods();

    //set a count of unread mails:
    QueryResult *resultMails = sDatabase.PQuery("SELECT COUNT(id) FROM `mail` WHERE `receiver` = '%u' AND `checked` = 0", GUID_LOPART(playerGuid));
    if (resultMails)
    {
        Field *fieldMail = resultMails->Fetch();
        plr->unReadMails = fieldMail[0].GetUInt8();
        delete resultMails;
    }
    else
        plr->unReadMails = 0;

    SetPlayer(plr);

    WorldPacket data( SMSG_ACCOUNT_DATA_MD5, (80) );

    for(int i = 0; i < 80; i++)
        data << uint8(0);

    SendPacket(&data);

    Player *pCurrChar = GetPlayer();

    pCurrChar->LoadIgnoreList();
    pCurrChar->SendFriendlist();
    pCurrChar->SendIgnorelist();

    sChatHandler.FillSystemMessageData(&data, this, sWorld.GetMotd());
    SendPacket( &data );

    DEBUG_LOG( "WORLD: Sent motd (SMSG_MESSAGECHAT)" );

    if(pCurrChar->GetGuildId() != 0)
    {
        Guild* guild = objmgr.GetGuildById(pCurrChar->GetGuildId());
        if(guild)
        {
            data.Initialize(SMSG_GUILD_EVENT, (2+guild->GetMOTD().size()+1));
            data << (uint8)GE_MOTD;
            data << (uint8)1;
            data << guild->GetMOTD();
            SendPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-motd (SMSG_GUILD_EVENT)" );

            data.Initialize(SMSG_GUILD_EVENT, (5+10));      // we guess size
            data<<(uint8)GE_SIGNED_ON;
            data<<(uint8)1;
            data<<pCurrChar->GetName();
            data<<(uint8)0<<(uint8)0<<(uint8)0;
            guild->BroadcastPacket(&data);
            DEBUG_LOG( "WORLD: Sent guild-signed-on (SMSG_GUILD_EVENT)" );
        }
        else
        {
            // remove wrong guild data
            sLog.outError("Player %s (GUID: %u) marked as member not existed guild (id: %u), removing guild membership for player.",pCurrChar->GetName(),pCurrChar->GetGUIDLow(),pCurrChar->GetGuildId());
            pCurrChar->SetUInt32Value(PLAYER_GUILDID,0);
            pCurrChar->SetUInt32ValueInDB(PLAYER_GUILDID,0,pCurrChar->GetGUID());
        }
    }

    // home bind stuff
    Field *fields;
    QueryResult *result7 = sDatabase.PQuery("SELECT COUNT(`guid`) FROM `character_homebind` WHERE `guid` = '%u'", GUID_LOPART(playerGuid));
    if (result7)
    {
        int cnt;
        fields = result7->Fetch();
        cnt = fields[0].GetUInt32();

        if ( cnt > 0 )
        {
            QueryResult *result4 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `character_homebind` WHERE `guid` = '%u'", GUID_LOPART(playerGuid));
            assert(result4);
            fields = result4->Fetch();
            data.Initialize (SMSG_BINDPOINTUPDATE, 5*4);
            data << fields[2].GetFloat() << fields[3].GetFloat() << fields[4].GetFloat();
            data << fields[0].GetUInt32();
            data << fields[1].GetUInt32();
            SendPacket (&data);
            DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",fields[0].GetUInt32(),fields[1].GetUInt32(),fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
            delete result4;
        }
        else
        {
            int plrace = GetPlayer()->getRace();
            int plclass = GetPlayer()->getClass();
            QueryResult *result5 = sDatabase.PQuery("SELECT `map`,`zone`,`position_x`,`position_y`,`position_z` FROM `playercreateinfo` WHERE `race` = '%u' AND `class` = '%u'", plrace, plclass);
            assert(result5);
            fields = result5->Fetch();
            // store and send homebind for player
            sDatabase.PExecute("INSERT INTO `character_homebind` (`guid`,`map`,`zone`,`position_x`,`position_y`,`position_z`) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GUID_LOPART(playerGuid), fields[0].GetUInt32(), fields[1].GetUInt32(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
            data.Initialize (SMSG_BINDPOINTUPDATE, 5*4);
            data << fields[2].GetFloat() << fields[3].GetFloat() << fields[4].GetFloat();
            data << fields[0].GetUInt32();
            data << fields[1].GetUInt32();
            SendPacket (&data);
            DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",fields[0].GetUInt32(),fields[1].GetUInt32(),fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat());
            delete result5;
        }
        delete result7;
    }

    data.Initialize( SMSG_TUTORIAL_FLAGS, 8*32 );

    for (int i = 0; i < 8; i++)
        data << uint32( GetPlayer()->GetTutorialInt(i) );

    SendPacket(&data);
    //sLog.outDebug( "WORLD: Sent tutorial flags." );

    GetPlayer()->SendInitialSpells();
    GetPlayer()->SendInitialActionButtons();

    /*if(GetPlayer()->getClass() == CLASS_HUNTER || GetPlayer()->getClass() == CLASS_ROGUE)
    {
        uint32 shiftdata=0x01;
        for(uint8 i=0;i<32;i++)
        {
            if ( 522753 & shiftdata )
            {
                data.Initialize(SMSG_SET_FLAT_SPELL_MODIFIER);
                data << uint8(i);
                data << uint8(5);
                data << uint16(1);
                data << uint16(0);
                SendPacket(&data);
            }
            shiftdata=shiftdata<<1;
        }
    }*/

    data.Initialize(SMSG_INITIALIZE_FACTIONS, (4+64*5));
    data << uint32 (0x00000040);
    for(uint32 a=0; a<64; a++)
    {
        if(GetPlayer()->FactionIsInTheList(a))
        {
            std::list<struct Factions>::iterator itr;
            for(itr = GetPlayer()->factions.begin(); itr != GetPlayer()->factions.end(); ++itr)
            {
                if(itr->ReputationListID == a)
                {
                    data << uint8  (itr->Flags);
                    data << uint32 (itr->Standing);
                    break;
                }
            }
        }
        else
        {
            data << uint8  (0x00);
            data << uint32 (0x00000000);
        }
    }
    SendPacket(&data);

    GetPlayer()->UpdateHonor();

    data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
    time_t gameTime = sWorld.GetGameTime();
    struct tm *lt = localtime(&gameTime);
    uint32 xmitTime = (lt->tm_year - 100) << 24 | lt->tm_mon  << 20 |
        (lt->tm_mday - 1) << 14 | lt->tm_wday << 11 |
        lt->tm_hour << 6 | lt->tm_min;
    data << xmitTime;
    data << (uint32)0x3C888889;                             //(float)0.017f;
    SendPacket( &data );

    //Show cinematic at the first time that player login
    if( !GetPlayer()->getCinematic() )
    {
        GetPlayer()->setCinematic(1);

        ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(GetPlayer()->getRace());
        if(rEntry)
        {
            data.Initialize( SMSG_TRIGGER_CINEMATIC,4 );
            data << uint32(rEntry->startmovie);
            SendPacket( &data );
        }
    }

    QueryResult *result = sDatabase.PQuery("SELECT `guildid`,`rank` FROM `guild_member` WHERE `guid` = '%u'",pCurrChar->GetGUIDLow());

    if(result)
    {
        Field *fields = result->Fetch();
        pCurrChar->SetInGuild(fields[0].GetUInt32());
        pCurrChar->SetRank(fields[1].GetUInt32());
        delete result;
    }

    MapManager::Instance().GetMap(pCurrChar->GetMapId())->Add(pCurrChar);
    ObjectAccessor::Instance().InsertPlayer(pCurrChar);
    //sLog.outDebug("Player %s added to Map.",pCurrChar->GetName());

    if (pCurrChar->m_transport)
    {
        Transport* curTrans = pCurrChar->m_transport;
        pCurrChar->TeleportTo(curTrans->GetMapId(), curTrans->GetPositionX(), curTrans->GetPositionY(), curTrans->GetPositionZ(), curTrans->GetOrientation(), true, false);
    }

    sDatabase.PExecute("UPDATE `character` SET `online` = 1 WHERE `guid` = '%u'", pCurrChar->GetGUIDLow());
    loginDatabase.PExecute("UPDATE `account` SET `online` = 1 WHERE `id` = '%u'", GetAccountId());
    plr->SetInGameTime( getMSTime() );

    data.Initialize(SMSG_FRIEND_STATUS, 19);
    data<<uint8(FRIEND_ONLINE);
    data<<pCurrChar->GetGUID();
    data<<uint8(1);
    data<<pCurrChar->GetAreaId();
    data<<pCurrChar->getLevel();
    data<<pCurrChar->getClass();
    pCurrChar->BroadcastPacketToFriendListers(&data);

    // setting new speed if dead
    if ( pCurrChar->m_deathState == DEAD )
    {
        pCurrChar->SetMovement(MOVE_WATER_WALK);

        if (pCurrChar->getRace() == RACE_NIGHTELF)
        {
            pCurrChar->SetSpeed(MOVE_RUN,  1.5f*1.2f, true);
            pCurrChar->SetSpeed(MOVE_SWIM, 1.5f*1.2f, true);
        }
        else
        {
            pCurrChar->SetSpeed(MOVE_RUN,  1.5f, true);
            pCurrChar->SetSpeed(MOVE_SWIM, 1.5f, true);
        }
    }

    pCurrChar->LoadEnchant();
    pCurrChar->_LoadSpellCooldowns();

    // Place charcter in world (and load zone) before some object loading
    pCurrChar->LoadCorpse();
    pCurrChar->LoadPet();
    // show time before shutdown if shudown planned.
    if(sWorld.IsShutdowning())
        sWorld.ShutdownMsg(true,pCurrChar);

    result = sDatabase.PQuery("SELECT `leaderGuid` FROM `raidgroup_member` WHERE `memberGuid`='%u'", GUID_LOPART(pCurrChar->GetGUID()));
    if(result)
    {
        uint64 leaderGuid = MAKE_GUID((*result)[0].GetUInt32(),HIGHGUID_PLAYER);
        delete result;

        pCurrChar->groupInfo.group = objmgr.GetGroupByLeader(leaderGuid);
        if(pCurrChar->groupInfo.group)
        {
            pCurrChar->groupInfo.group->SendInit(this);
            pCurrChar->groupInfo.group->SendUpdate();
        }
    }

    if(pCurrChar->isGameMaster())
        SendNotification("GM mode is ON");
    m_playerLoading = false;
}
Example #26
0
Transport* TransportFactory::newTransport(const std::string& transportModel,
        thermo_t* phase, int log_level, int ndim)
{
    if (transportModel == "") {
        return new Transport;
    }

    vector_fp state;
    Transport* tr = 0, *gastr = 0;
    DustyGasTransport* dtr = 0;
    phase->saveState(state);

    switch (m_models[transportModel]) {
    case None:
        tr = new Transport;
        break;
    case cMulticomponent:
        tr = new MultiTransport;
        tr->init(phase, 0, log_level);
        break;
    case CK_Multicomponent:
        tr = new MultiTransport;
        tr->init(phase, CK_Mode, log_level);
        break;
    case cMixtureAveraged:
        tr = new MixTransport;
        tr->init(phase, 0, log_level);
        break;
    case CK_MixtureAveraged:
        tr = new MixTransport;
        tr->init(phase, CK_Mode, log_level);
        break;
    case cHighP:
        tr = new HighPressureGasTransport;
        tr->init(phase, 0, log_level);
        break;
    case cSolidTransport:
        tr = new SolidTransport;
        initSolidTransport(tr, phase, log_level);
        tr->setThermo(*phase);
        break;
    case cDustyGasTransport:
        tr = new DustyGasTransport;
        gastr = new MultiTransport;
        gastr->init(phase, 0, log_level);
        dtr = (DustyGasTransport*)tr;
        dtr->initialize(phase, gastr);
        break;
    case cSimpleTransport:
        tr = new SimpleTransport();
        initLiquidTransport(tr, phase, log_level);
        tr->setThermo(*phase);
        break;
    case cLiquidTransport:
        tr = new LiquidTransport(phase, ndim);
        initLiquidTransport(tr, phase, log_level);
        tr->setThermo(*phase);
        break;
    default:
        throw CanteraError("newTransport","unknown transport model: " + transportModel);
    }
    phase->restoreState(state);
    return tr;
}