Ejemplo n.º 1
0
int ShaderBinder::create(lua_State* L)
{
	StackChecker checker(L, "ShaderBinder::create", 1);

    Binder binder(L);

	const char* vs = luaL_checkstring(L, 1);
	const char* ps = luaL_checkstring(L, 2);
	int flags=luaL_checkinteger(L,3);
    luaL_checktype(L, 4, LUA_TTABLE);
    luaL_checktype(L, 5, LUA_TTABLE);

	std::vector<ShaderProgram::ConstantDesc> constants;
	std::vector<ShaderProgram::DataDesc> datas;

    int n = luaL_getn(L, 4);  /* get size of table */
    for (int i=1; i<=n; i++) {
    	ShaderProgram::ConstantDesc cst={"",ShaderProgram::CINT,1,ShaderProgram::SysConst_None,false,0,NULL};
        lua_rawgeti(L, 4, i);  /* push t[i] */
        luaL_checktype(L,-1,LUA_TTABLE); //Check table
        lua_getfield(L,-1,"name");
        cst.name=luaL_checkstring(L,-1);
        lua_getfield(L,-2,"type");
        cst.type=(ShaderProgram::ConstantType)luaL_checkinteger(L,-1);
        lua_getfield(L,-3,"vertex");
        cst.vertexShader=lua_toboolean(L,-1);
        lua_getfield(L,-4,"sys");
        cst.sys=(ShaderProgram::SystemConstant) luaL_optinteger(L,-1,0);
        lua_getfield(L,-5,"mult");
        cst.mult=luaL_optinteger(L,-1,1);
        lua_pop(L,6);
    	constants.push_back(cst);
      }

    n = luaL_getn(L, 5);  /* get size of table */
    for (int i=1; i<=n; i++) {
    	ShaderProgram::DataDesc cst={"",ShaderProgram::DFLOAT,0,0,0};
        lua_rawgeti(L, 5, i);  /* push t[i] */
        luaL_checktype(L,-1,LUA_TTABLE); //Check table
        lua_getfield(L,-1,"name");
        cst.name=luaL_checkstring(L,-1);
        lua_getfield(L,-2,"type");
        cst.type=(ShaderProgram::DataType)luaL_checkinteger(L,-1);
        lua_getfield(L,-3,"mult");
        cst.mult=luaL_checkinteger(L,-1);
        lua_getfield(L,-4,"slot");
        cst.slot=luaL_optinteger(L,-1,0);
        lua_getfield(L,-5,"offset");
        cst.offset=luaL_optinteger(L,-1,0);
        lua_pop(L,6);
    	datas.push_back(cst);
      }


	ShaderProgram::ConstantDesc clast={"",ShaderProgram::CINT,1,ShaderProgram::SysConst_None,false,0,NULL};
	ShaderProgram::DataDesc dlast={"",ShaderProgram::DFLOAT,0,0,0};
	constants.push_back(clast);
	datas.push_back(dlast);
    ShaderProgram *shader=ShaderEngine::Engine->createShaderProgram(vs,ps,flags,&(constants[0]),&(datas[0]));
    if (!shader->isValid())
    {
    	lua_pushstring(L,shader->compilationLog());
    	lua_error(L);
    }
    binder.pushInstance("Shader", shader);
	return 1;
}
Ejemplo n.º 2
0
bool BfCapturePoint::Update(uint32 diff)
{
    if (!m_capturePointGUID)
        return false;

    if (GameObject* capturePoint = m_Bf->GetGameObject(m_capturePointGUID))
    {
        float radius = capturePoint->GetGOInfo()->capturePoint.radius;

        for (uint8 team = 0; team < 2; ++team)
        {
            for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end();)
            {
                if (Player* player = sObjectAccessor->FindPlayer(*itr))
                {
                    if (!capturePoint->IsWithinDistInMap(player, radius) || !player->IsOutdoorPvPActive())
                        itr = HandlePlayerLeave(player);
                    else
                        ++itr;
                }
                else
                    ++itr;
            }
        }

        std::list<Player*> players;
        Trinity::AnyPlayerInObjectRangeCheck checker(capturePoint, radius);
        Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(capturePoint, players, checker);
        capturePoint->VisitNearbyWorldObject(radius, searcher);

        for (std::list<Player*>::iterator itr = players.begin(); itr != players.end(); ++itr)
            if ((*itr)->IsOutdoorPvPActive())
                if (m_activePlayers[(*itr)->GetTeamId()].insert((*itr)->GetGUID()).second)
                    HandlePlayerEnter(*itr);
    }

    // get the difference of numbers
    float fact_diff = ((float) m_activePlayers[0].size() - (float) m_activePlayers[1].size()) * diff / BATTLEFIELD_OBJECTIVE_UPDATE_INTERVAL;
    if (G3D::fuzzyEq(fact_diff, 0.0f))
        return false;

    uint32 Challenger = 0;
    float maxDiff = m_maxSpeed * diff;

    if (fact_diff < 0)
    {
        // horde is in majority, but it's already horde-controlled -> no change
        if (m_State == BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE && m_value <= -m_maxValue)
            return false;

        if (fact_diff < -maxDiff)
            fact_diff = -maxDiff;

        Challenger = HORDE;
    }
    else
    {
        // ally is in majority, but it's already ally-controlled -> no change
        if (m_State == BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE && m_value >= m_maxValue)
            return false;

        if (fact_diff > maxDiff)
            fact_diff = maxDiff;

        Challenger = ALLIANCE;
    }

    float oldValue = m_value;
    TeamId oldTeam = m_team;

    m_OldState = m_State;

    m_value += fact_diff;

    if (m_value < -m_minValue)                              // red
    {
        if (m_value < -m_maxValue)
            m_value = -m_maxValue;
        m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE;
        m_team = TEAM_HORDE;
    }
    else if (m_value > m_minValue)                          // blue
    {
        if (m_value > m_maxValue)
            m_value = m_maxValue;
        m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE;
        m_team = TEAM_ALLIANCE;
    }
    else if (oldValue * m_value <= 0)                       // grey, go through mid point
    {
        // if challenger is ally, then n->a challenge
        if (Challenger == ALLIANCE)
            m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE;
        // if challenger is horde, then n->h challenge
        else if (Challenger == HORDE)
            m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE;
        m_team = TEAM_NEUTRAL;
    }
    else                                                    // grey, did not go through mid point
    {
        // old phase and current are on the same side, so one team challenges the other
        if (Challenger == ALLIANCE && (m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE || m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE))
            m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE;
        else if (Challenger == HORDE && (m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE || m_OldState == BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE))
            m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE;
        m_team = TEAM_NEUTRAL;
    }

    if (G3D::fuzzyNe(m_value, oldValue))
        SendChangePhase();

    if (m_OldState != m_State)
    {
        //sLog->outError(LOG_FILTER_BATTLEFIELD, "%u->%u", m_OldState, m_State);
        if (oldTeam != m_team)
            ChangeTeam(oldTeam);
        return true;
    }

    return false;
}
Ejemplo n.º 3
0
bool OPvPCapturePoint::Update(uint32 diff)
{
    if (!m_capturePoint)
        return false;

    float radius = (float)m_capturePoint->GetGOInfo()->capturePoint.radius;

    for (uint32 team = 0; team < 2; ++team)
    {
        for (PlayerSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end();)
        {
            Player* player = *itr;
            ++itr;
            if (!m_capturePoint->IsWithinDistInMap(player, radius) || !player->IsOutdoorPvPActive())
                HandlePlayerLeave(player);
        }
    }

    std::list<Player*> players;
    SkyFire::AnyPlayerInObjectRangeCheck checker(m_capturePoint, radius);
    SkyFire::PlayerListSearcher<SkyFire::AnyPlayerInObjectRangeCheck> searcher(m_capturePoint, players, checker);
    m_capturePoint->VisitNearbyWorldObject(radius, searcher);

    for (std::list<Player*>::iterator itr = players.begin(); itr != players.end(); ++itr)
    {
        if ((*itr)->IsOutdoorPvPActive())
        {
            if (m_activePlayers[(*itr)->GetTeamId()].insert(*itr).second)
                HandlePlayerEnter(*itr);
        }
    }

    // get the difference of numbers
    float fact_diff = ((float)m_activePlayers[0].size() - (float)m_activePlayers[1].size()) * diff / OUTDOORPVP_OBJECTIVE_UPDATE_INTERVAL;
    if (!fact_diff)
        return false;

    uint32 Challenger = 0;
    float maxDiff = m_maxSpeed * diff;

    if (fact_diff < 0)
    {
        // horde is in majority, but it's already horde-controlled -> no change
        if (m_State == OBJECTIVESTATE_HORDE && m_value <= -m_maxValue)
            return false;

        if (fact_diff < -maxDiff)
            fact_diff = -maxDiff;

        Challenger = HORDE;
    }
    else
    {
        // ally is in majority, but it's already ally-controlled -> no change
        if (m_State == OBJECTIVESTATE_ALLIANCE && m_value >= m_maxValue)
            return false;

        if (fact_diff > maxDiff)
            fact_diff = maxDiff;

        Challenger = ALLIANCE;
    }

    float oldValue = m_value;
    TeamId oldTeam = _team;

    m_OldState = m_State;

    m_value += fact_diff;

    if (m_value < -m_minValue) // red
    {
        if (m_value < -m_maxValue)
            m_value = -m_maxValue;
        m_State = OBJECTIVESTATE_HORDE;
        _team = TEAM_HORDE;
    }
    else if (m_value > m_minValue) // blue
    {
        if (m_value > m_maxValue)
            m_value = m_maxValue;
        m_State = OBJECTIVESTATE_ALLIANCE;
        _team = TEAM_ALLIANCE;
    }
    else if (oldValue * m_value <= 0) // grey, go through mid point
    {
        // if challenger is ally, then n->a challenge
        if (Challenger == ALLIANCE)
            m_State = OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE;
        // if challenger is horde, then n->h challenge
        else if (Challenger == HORDE)
            m_State = OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE;
        _team = TEAM_NEUTRAL;
    }
    else // grey, did not go through mid point
    {
        // old phase and current are on the same side, so one team challenges the other
        if (Challenger == ALLIANCE && (m_OldState == OBJECTIVESTATE_HORDE || m_OldState == OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE))
            m_State = OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE;
        else if (Challenger == HORDE && (m_OldState == OBJECTIVESTATE_ALLIANCE || m_OldState == OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE))
            m_State = OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE;
        _team = TEAM_NEUTRAL;
    }

    if (m_value != oldValue)
        SendChangePhase();

    if (m_OldState != m_State)
    {
        //sLog->outError("%u->%u", m_OldState, m_State);
        if (oldTeam != _team)
            ChangeTeam(oldTeam);
        ChangeState();
        return true;
    }

    return false;
}
Ejemplo n.º 4
0
void TotemAI::UpdateAI(const uint32 /*diff*/)
{
    if (i_totem.GetTotemType() != TOTEM_ACTIVE)
        return;

    i_totem.SetSelection(0);

    if (!i_totem.isAlive() || i_totem.IsNonMeleeSpellCasted(false))
        return;

    // Search spell
    SpellEntry const *spellInfo = sSpellStore.LookupEntry(i_totem.GetSpell());
    if (!spellInfo)
        return;

    // Get spell rangy
    SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
    float max_range = SpellMgr::GetSpellMaxRange(srange);

    // SPELLMOD_RANGE not applied in this place just because not existence range mods for attacking totems

    // pointer to appropriate target if found any
    Unit* victim = i_victimGuid ? i_totem.GetMap()->GetUnit(i_victimGuid) : NULL;

    if (!max_range)
        victim = &i_totem;

    // Search victim if no, not attackable, or out of range, or friendly (possible in case duel end)
    if (!victim || (!SpellMgr::SpellIgnoreLOS(spellInfo, 0) && !i_totem.IsWithinLOSInMap(victim)) ||
        !victim->isTargetableForAttack() || !i_totem.IsWithinDistInMap(victim, max_range) ||
        (i_totem.IsFriendlyTo(victim) && victim != &i_totem) || !victim->isVisibleForOrDetect(&i_totem, &i_totem, false))
    {
        victim = NULL;

        Looking4group::NearestAttackableUnitInObjectRangeCheck u_check(&i_totem, &i_totem, max_range);
        Looking4group::UnitLastSearcher<Looking4group::NearestAttackableUnitInObjectRangeCheck> checker(victim, u_check);

        Cell::VisitAllObjects(m_creature, checker, max_range);
    }

    // If have target
    if (victim)
    {
        //this should prevent target-type totems from attacking from unattackable zones and attacking while being unattackable
        if ((i_totem.isInSanctuary() || victim->isInSanctuary()) && victim->GetCharmerOrOwnerPlayerOrPlayerItself())
            return;
        // remember
        i_victimGuid = victim->GetGUID();

        // attack
        i_totem.CastSpell(victim, i_totem.GetSpell(), false, NULL, NULL, i_totem.GetOwner()->GetGUID());
    }
    else
        i_victimGuid = 0;

    //i_totem.SetFacingToObject(&i_totem);
}
Ejemplo n.º 5
0
boolean testInsertBIG (tree *tr, nodeptr p, nodeptr q)
{
  double  qz[NUM_BRANCHES], pz[NUM_BRANCHES];
  nodeptr  r;
  boolean doIt = TRUE;
  double startLH = tr->endLH;
  int i;
  
  r = q->back; 
  for(i = 0; i < tr->numBranches; i++)
    {
      qz[i] = q->z[i];
      pz[i] = p->z[i];
    }
  
  if(tr->grouped)
    {
      int rNumber, qNumber, pNumber;
      
      doIt = FALSE;
      
      rNumber = tr->constraintVector[r->number];
      qNumber = tr->constraintVector[q->number];
      pNumber = tr->constraintVector[p->number];
      
      if(pNumber == -9)
	pNumber = checker(tr, p->back);
      if(pNumber == -9)
	doIt = TRUE;
      else
	{
	  if(qNumber == -9)
	    qNumber = checker(tr, q);
	  
	  if(rNumber == -9)
	    rNumber = checker(tr, r);
	  
	  if(pNumber == rNumber || pNumber == qNumber)
	    doIt = TRUE;    	  
	}
    }
  
  if(doIt)
    {     
      if (! insertBIG(tr, p, q, tr->numBranches))       return FALSE;         
      
      evaluateGeneric(tr, p->next->next);   
       
      if(tr->likelihood > tr->bestOfNode)
	{
	  tr->bestOfNode = tr->likelihood;
	  tr->insertNode = q;
	  tr->removeNode = p;   
	  for(i = 0; i < tr->numBranches; i++)
	    {
	      tr->currentZQR[i] = tr->zqr[i];           
	      tr->currentLZR[i] = tr->lzr[i];
	      tr->currentLZQ[i] = tr->lzq[i];
	      tr->currentLZS[i] = tr->lzs[i];      
	    }
	}
      
      if(tr->likelihood > tr->endLH)
	{			  
	  tr->insertNode = q;
	  tr->removeNode = p;   
	  for(i = 0; i < tr->numBranches; i++)
	    tr->currentZQR[i] = tr->zqr[i];      
	  tr->endLH = tr->likelihood;                      
	}        
      
      hookup(q, r, qz, tr->numBranches);
      
      p->next->next->back = p->next->back = (nodeptr) NULL;
      
      if(Thorough)
	{
	  nodeptr s = p->back;
	  hookup(p, s, pz, tr->numBranches);      
	} 
      
      if((tr->doCutoff) && (tr->likelihood < startLH))
	{
	  tr->lhAVG += (startLH - tr->likelihood);
	  tr->lhDEC++;
	  if((startLH - tr->likelihood) >= tr->lhCutoff)
	    return FALSE;	    
	  else
	    return TRUE;
	}
      else
	return TRUE;
    }
  else
    return TRUE;  
}
Ejemplo n.º 6
0
	virtual void visit(TouchEvent* v)
	{
		StackChecker checker(L, "visit(TouchEvent* v)", 0);

		Binder binder(L);

		// get closure
		luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_eventClosures);
		lua_pushlightuserdata(L, bridge_);
		lua_rawget(L, -2);
		lua_remove(L, -2);		// remove env["eventClosures"]

		luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_TouchEvent);

		lua_getfield(L, -1, "__uniqueid");

		if (lua_isnil(L, -1) || lua_tointeger(L, -1) != v->uniqueid())
		{
			lua_pop(L, 1);

			lua_pushinteger(L, v->uniqueid());
			lua_setfield(L, -2, "__uniqueid");

			binder.setInstance(-1, v);

			lua_pushstring(L, v->type()); // TODO: buna artik ihtiyac yok. direk Event'te getType() fonksiyonu var
			lua_setfield(L, -2, "type");

            // touch
            getOrCreateTouch(&v->event->touch, v->sx, v->sy, v->tx, v->ty);
            lua_setfield(L, -2, "touch");

            // touches (it has only 1 element)
			lua_getfield(L, -1, "touches");
			if (lua_isnil(L, -1))
			{
				lua_pop(L, 1);
				lua_newtable(L);
			}
			else
			{
				int n = lua_objlen(L, -1);
				for (int i = n; i >= 1; --i)
				{
					lua_pushnil(L);
					lua_rawseti(L, -2, i);
				}
			}
            getOrCreateTouch(&v->event->touch, v->sx, v->sy, v->tx, v->ty);
            lua_rawseti(L, -2, 1);
			lua_setfield(L, -2, "touches");

            // allTouches
			lua_getfield(L, -1, "allTouches");
			if (lua_isnil(L, -1))
			{
				lua_pop(L, 1);
				lua_newtable(L);
			}
			else
			{
				int n = lua_objlen(L, -1);
				for (int i = n; i >= 1; --i)
				{
					lua_pushnil(L);
					lua_rawseti(L, -2, i);
				}
			}
            for (std::size_t i = 0; i < v->event->allTouchesCount; ++i)
			{
                getOrCreateTouch(&v->event->allTouches[i], v->sx, v->sy, v->tx, v->ty);
                lua_rawseti(L, -2, i + 1);
			}
			lua_setfield(L, -2, "allTouches");
		}
		else
		{
			lua_pop(L, 1);
		}
		
		lua_call(L, 1, 0);
	}
Ejemplo n.º 7
0
IGL_INLINE bool igl::copyleft::boolean::mesh_boolean(
    const Eigen::PlainObjectBase<DerivedVA> & VA,
    const Eigen::PlainObjectBase<DerivedFA> & FA,
    const Eigen::PlainObjectBase<DerivedVB> & VB,
    const Eigen::PlainObjectBase<DerivedFB> & FB,
    const WindingNumberOp& wind_num_op,
    const KeepFunc& keep,
    const ResolveFunc& resolve_fun,
    Eigen::PlainObjectBase<DerivedVC > & VC,
    Eigen::PlainObjectBase<DerivedFC > & FC,
    Eigen::PlainObjectBase<DerivedJ > & J) 
{

#ifdef MESH_BOOLEAN_TIMING
  const auto & tictoc = []() -> double
  {
    static double t_start = igl::get_seconds();
    double diff = igl::get_seconds()-t_start;
    t_start += diff;
    return diff;
  };
  const auto log_time = [&](const std::string& label) -> void {
    std::cout << "mesh_boolean." << label << ": "
      << tictoc() << std::endl;
  };
  tictoc();
#endif

  typedef typename DerivedVC::Scalar Scalar;
  //typedef typename DerivedFC::Scalar Index;
  typedef CGAL::Epeck Kernel;
  typedef Kernel::FT ExactScalar;
  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,3> MatrixX3S;
  //typedef Eigen::Matrix<Index,Eigen::Dynamic,Eigen::Dynamic> MatrixXI;
  typedef Eigen::Matrix<typename DerivedJ::Scalar,Eigen::Dynamic,1> VectorXJ;

  // Generate combined mesh.
  typedef Eigen::Matrix<
    ExactScalar,
    Eigen::Dynamic,
    Eigen::Dynamic,
    DerivedVC::IsRowMajor> MatrixXES;
  MatrixXES V;
  DerivedFC F;
  VectorXJ  CJ;
  {
      DerivedVA VV(VA.rows() + VB.rows(), 3);
      DerivedFC FF(FA.rows() + FB.rows(), 3);
      VV << VA, VB;
      FF << FA, FB.array() + VA.rows();
      //// Handle annoying empty cases
      //if(VA.size()>0)
      //{
      //  VV<<VA;
      //}
      //if(VB.size()>0)
      //{
      //  VV<<VB;
      //}
      //if(FA.size()>0)
      //{
      //  FF<<FA;
      //}
      //if(FB.size()>0)
      //{
      //  FF<<FB.array()+VA.rows();
      //}
      resolve_fun(VV, FF, V, F, CJ);
  }
#ifdef MESH_BOOLEAN_TIMING
  log_time("resolve_self_intersection");
#endif

  // Compute winding numbers on each side of each facet.
  const size_t num_faces = F.rows();
  Eigen::MatrixXi W;
  Eigen::VectorXi labels(num_faces);
  std::transform(CJ.data(), CJ.data()+CJ.size(), labels.data(),
      [&](int i) { return i<FA.rows() ? 0:1; });
  bool valid = true;
  if (num_faces > 0) 
  {
    valid = valid & 
      igl::copyleft::cgal::propagate_winding_numbers(V, F, labels, W);
  } else 
  {
    W.resize(0, 4);
  }
  assert((size_t)W.rows() == num_faces);
  if (W.cols() == 2) 
  {
    assert(FB.rows() == 0);
    Eigen::MatrixXi W_tmp(num_faces, 4);
    W_tmp << W, Eigen::MatrixXi::Zero(num_faces, 2);
    W = W_tmp;
  } else {
    assert(W.cols() == 4);
  }
#ifdef MESH_BOOLEAN_TIMING
  log_time("propagate_input_winding_number");
#endif

  // Compute resulting winding number.
  Eigen::MatrixXi Wr(num_faces, 2);
  for (size_t i=0; i<num_faces; i++) 
  {
    Eigen::MatrixXi w_out(1,2), w_in(1,2);
    w_out << W(i,0), W(i,2);
    w_in  << W(i,1), W(i,3);
    Wr(i,0) = wind_num_op(w_out);
    Wr(i,1) = wind_num_op(w_in);
  }
#ifdef MESH_BOOLEAN_TIMING
  log_time("compute_output_winding_number");
#endif

  // Extract boundary separating inside from outside.
  auto index_to_signed_index = [&](size_t i, bool ori) -> int
  {
    return (i+1)*(ori?1:-1);
  };
  //auto signed_index_to_index = [&](int i) -> size_t {
  //    return abs(i) - 1;
  //};
  std::vector<int> selected;
  for(size_t i=0; i<num_faces; i++) 
  {
    auto should_keep = keep(Wr(i,0), Wr(i,1));
    if (should_keep > 0) 
    {
      selected.push_back(index_to_signed_index(i, true));
    } else if (should_keep < 0) 
    {
      selected.push_back(index_to_signed_index(i, false));
    }
  }

  const size_t num_selected = selected.size();
  DerivedFC kept_faces(num_selected, 3);
  DerivedJ  kept_face_indices(num_selected, 1);
  for (size_t i=0; i<num_selected; i++) 
  {
    size_t idx = abs(selected[i]) - 1;
    if (selected[i] > 0) 
    {
      kept_faces.row(i) = F.row(idx);
    } else 
    {
      kept_faces.row(i) = F.row(idx).reverse();
    }
    kept_face_indices(i, 0) = CJ[idx];
  }
#ifdef MESH_BOOLEAN_TIMING
  log_time("extract_output");
#endif

  // Finally, remove duplicated faces and unreferenced vertices.
  {
    DerivedFC G;
    DerivedJ JJ;
    igl::resolve_duplicated_faces(kept_faces, G, JJ);
    igl::slice(kept_face_indices, JJ, 1, J);

#ifdef DOUBLE_CHECK_EXACT_OUTPUT
    {
      // Sanity check on exact output.
      igl::copyleft::cgal::RemeshSelfIntersectionsParam params;
      params.detect_only = true;
      params.first_only = true;
      MatrixXES dummy_VV;
      DerivedFC dummy_FF, dummy_IF;
      Eigen::VectorXi dummy_J, dummy_IM;
      igl::copyleft::cgal::SelfIntersectMesh<
        Kernel,
        MatrixXES, DerivedFC,
        MatrixXES, DerivedFC,
        DerivedFC,
        Eigen::VectorXi,
        Eigen::VectorXi
      > checker(V, G, params,
          dummy_VV, dummy_FF, dummy_IF, dummy_J, dummy_IM);
      if (checker.count != 0) 
      {
        throw "Self-intersection not fully resolved.";
      }
    }
#endif

    MatrixX3S Vs(V.rows(), V.cols());
    for (size_t i=0; i<(size_t)V.rows(); i++)
    {
      for (size_t j=0; j<(size_t)V.cols(); j++)
      {
        igl::copyleft::cgal::assign_scalar(V(i,j), Vs(i,j));
      }
    }
    Eigen::VectorXi newIM;
    igl::remove_unreferenced(Vs,G,VC,FC,newIM);
  }
#ifdef MESH_BOOLEAN_TIMING
  log_time("clean_up");
#endif
  return valid;
}
Ejemplo n.º 8
0
int AudioBinder::Sound_create(lua_State *L)
{
    StackChecker checker(L, "AudioBinder::Sound_create", 1);

    Binder binder(L);

    const char *fileName = luaL_checkstring(L, 1);

    std::vector<char> sig;
    int flags = gpath_getDriveFlags(gpath_getPathDrive(fileName));
    if (flags & GPATH_RO)
    {
        append(sig, fileName, strlen(fileName) + 1);
    }
    else
    {
        if (flags & GPATH_REAL)
        {
            append(sig, fileName, strlen(fileName) + 1);

            struct stat s;
            stat(gpath_transform(fileName), &s);
            append(sig, &s.st_mtime, sizeof(s.st_mtime));
        }
    }

    GGSound *sound = NULL;

    luaL_rawgetptr(L, LUA_REGISTRYINDEX, &keySound);

    if (sig.empty())
    {
        lua_pushnil(L);
    }
    else
    {
        lua_pushlstring(L, &sig[0], sig.size());
        lua_rawget(L, -2);
    }

    if (!lua_isnil(L, -1))
    {
        sound = static_cast<GGSound*>(lua_touserdata(L, -1));
        sound->ref();
    }
    else
    {
        gaudio_Error error;
        sound = new GGSound(L, fileName, &error, sig);

        switch (error)
        {
        case GAUDIO_NO_ERROR:
            break;
        case GAUDIO_CANNOT_OPEN_FILE:
            sound->unref();
            luaL_error(L, "%s: No such file or directory.", fileName);
            break;
        case GAUDIO_UNRECOGNIZED_FORMAT:
            sound->unref();
            luaL_error(L, "%s: Sound format is not recognized.", fileName);
            break;
        case GAUDIO_ERROR_WHILE_READING:
            sound->unref();
            luaL_error(L, "%s: Error while reading.", fileName);
            break;
        case GAUDIO_UNSUPPORTED_FORMAT:
            sound->unref();
            luaL_error(L, "%s: Sound format is not supported.", fileName);
            break;
        case GAUDIO_INTERNAL_ERROR:
            sound->unref();
            luaL_error(L, "%s: Sound internal error.", fileName);
            break;
        }
    }

    lua_pop(L, 2);

    binder.pushInstance("Sound", sound);

    return 1;
}
Ejemplo n.º 9
0
    void UpdateAI(const uint32 diff)
    {
        DoMeleeAttackIfReady();

        if(Timer < diff)
        {
            if(EventStartedPart1)
            {
                me->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
                if(Player* pPlayer = me->GetPlayer(*me, PlayerGuid))
                if(Creature* pCreature = me->FindNearestCreature(42852, 8.0f, true))
                {
                    switch(Phase)
                    {
                        case 0: me->MonsterSay("Mekgineer Thermaplugg refuses to acknowledge that his defeat is imminent! He has sent Razlo Crushcog to prevent us from rebuilding our beloved Gnomeregan!", 0, 0); Timer = 5000; Phase++; break;
                        case 1: me->MonsterSay("But $N has thwarted his plans at every turn, and the dwarves of Ironforge stand with us!", 0, PlayerGuid); Timer = 5000; Phase++; break;
                        case 2: me->MonsterSay("Let's send him crawling back to his master in defeat!", 0, 0); Timer = 3000; Phase++; break;
                        case 3:
                        {
                            me->AddUnitMovementFlag(MOVEMENTFLAG_WALKING);
                            pCreature->AddUnitMovementFlag(MOVEMENTFLAG_WALKING);
                            pCreature->MonsterSay("Aye, let's teach this addle-brained gnome a lesson!", 0, 0);
                            Timer = 500; Phase++;
                        } break;
                        case 4:
                        {
                            me->GetMotionMaster()->MovePoint(1, -5294.91f, 134.433f, 386.11f);
                            pCreature->GetMotionMaster()->MovePoint(2, -5291.88f, 138.85f, 386.11f);
                            SummonCrushcogAndHisAdds();
                            Timer = 10000;
                            Phase++;
                        } break;
                        case 5: AddRemoveFlagsFromAdds(); Phase++; Timer = 250; break;
                        case 6:
                        {
                            me->GetMotionMaster()->MovePoint(1, -5261.2f, 119.33f, 393.79f);
                            pCreature->GetMotionMaster()->MovePoint(2, -5260.88f, 123.25f, 393.88f);
                            Timer = 16000;
                            Phase++;
                        } break;
                        case 7: EventStartedPart1 = false; EventStartedPart2 = true; Phase = 8; break;
                        default: break;
                    }
                }
            }
            if(EventStartedPart2)
            {
                if(Player* pPlayer = me->GetPlayer(*me, PlayerGuid))
                if(Creature* pCreature = me->FindNearestCreature(42852, 40.0f, true))
                if(Creature* pCrushcog = me->FindNearestCreature(42839, 40.0f, true))
                {
                    switch(Phase)
                    {
                        case 8: pCrushcog->MonsterSay("You! How did you escape detection by my sentry-bots?", 0, 0); Timer = 3000; Phase++; break;
                        case 9: pCrushcog->MonsterSay("No matter! My guardians and I will make short work of you. To arms, men!", 0, 0); Timer = 2000; Phase++; break;
                        case 10: AttackPhase = true; Phase++; Timer = 250; break;
                        case 11:
                        {
                            AddRemoveFlagsFromAdds();
                            pCrushcog->MonsterSay("You will never defeat the true sons of Gnomergan", 0, 0);
                            pCrushcog->SetReactState(REACT_AGGRESSIVE);
                            pCrushcog->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
                            pCrushcog->CombatStart(me, true);
                            me->Attack(pCrushcog, true);
                            Phase = 12;
                        } break;
                        default: break;
                    }
                    if(pCrushcog)
                        Timer = 7000;
                }
                if(Creature* pCreature = me->FindNearestCreature(42852, 40.0f, true))
                if(Creature* pCrushcog = me->FindNearestCreature(42839, 40.0f, false))
                {
                    switch(Phase)
                    {
                        case 12:
                        {
                            RemoveCrushcogAdds();
                            pCreature->MonsterSay("That'll teach you to mess with the might of Ironforge and Gnomeregan!", 0, 0);
                            Timer = 1500; Phase++;
                        } break;
                        case 13: me->MonsterSay("We've done it! We're victorious!", 0, 0); Timer = 4500; Phase++; break;
                        case 14: me->MonsterSay("With Crushcog defeated. Thermaplugg is sure to be quaking in his mechano-tank, and rightly so. You're next Thermaplugg. You're next!", 0, 0); Phase++; Timer = 4000; break;
                        case 15:
                        {
                            AddQuestComplete();
                            me->GetMotionMaster()->MovePoint(1, -5261.2f, 119.33f, 393.79f);
                            pCreature->GetMotionMaster()->MovePoint(2, -5260.88f, 123.25f, 393.88f);
                            Phase++;
                            Timer = 16000;
                        }
                        case 16:
                        {
                            me->GetMotionMaster()->MoveTargetedHome();
                            pCreature->GetMotionMaster()->MoveTargetedHome();
                            me->AI()->Reset();
                            pCreature->AI()->Reset();
                        } break;
                        default: break;
                    }
                }
                if(Creature* pCrushcog = me->FindNearestCreature(42839, 10.0f, true))
                if(Creature* pRayTarget = me->FindNearestCreature(42929, 50.0f, true))
                {
                    //Niestety Spelle jeszcze niedzia?aj? wiec work-around
                    //me->CastSpell(pRayTarget, RayType[urand(0,3)], true);
                    me->MonsterYell("Mekkatorque-Ray!", 0, 0);

                    std::list<Unit*> BeamTarget;
                    Trinity::AnyUnitInObjectRangeCheck checker(me, 15);
                    Trinity::UnitListSearcher<Trinity::AnyUnitInObjectRangeCheck> searcher(me, BeamTarget, checker);
                    me->VisitNearbyWorldObject(15.0f, searcher);

                    for (std::list<Unit*>::iterator itr = BeamTarget.begin(); itr != BeamTarget.end(); ++itr)
                    {
                        if((*itr)->GetTypeId() == TYPEID_PLAYER)
                            return;

                        me->CastSpell((*itr), RayType[urand(0,3)], true);
                        me->DealDamage((*itr), ((*itr)->GetHealth()*0.15), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
                    }
                    me->CastSpell(pCrushcog, RayType[urand(0,3)], true);
                    me->DealDamage(pCrushcog, (pCrushcog->GetHealth()*0.15), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
                    pRayTarget->DespawnOrUnsummon();
                }
            //I know it's imposible but...
                if(Creature* pCreature = me->FindNearestCreature(42852, 40.0f, false))
                    me->AI()->Reset();

                if(me->isDead())
                {
                    Creature* pCreature = me->FindNearestCreature(42852, 40.0f, false);
                    if(pCreature)
                        pCreature->AI()->Reset();
                }
            }
        } else Timer -= diff;
    }
Ejemplo n.º 10
0
void PropagateNoContraction(const glslang::TIntermediate& intermediate)
{
    // First, traverses the AST, records symbols with their defining operations
    // and collects the initial set of precise symbols (symbol nodes that marked
    // as 'noContraction') and precise return nodes.
    auto mappings_and_precise_objects =
        getSymbolToDefinitionMappingAndPreciseSymbolIDs(intermediate);

    // The mapping of symbol node IDs to their defining nodes. This enables us
    // to get the defining node directly from a given symbol ID without
    // traversing the tree again.
    NodeMapping& symbol_definition_mapping = std::get<0>(mappings_and_precise_objects);

    // The mapping of object nodes to their access chains recorded.
    AccessChainMapping& accesschain_mapping = std::get<1>(mappings_and_precise_objects);

    // The initial set of 'precise' objects which are represented as the
    // access chain toward them.
    ObjectAccesschainSet& precise_object_accesschains = std::get<2>(mappings_and_precise_objects);

    // The set of 'precise' return nodes.
    ReturnBranchNodeSet& precise_return_nodes = std::get<3>(mappings_and_precise_objects);

    // Second, uses the initial set of precise objects as a work list, pops an
    // access chain, extract the symbol ID from it. Then:
    //  1) Check the assignee object, see if it is 'precise' object node or
    //  contains 'precise' object. Obtain the incremental access chain from the
    //  assignee node to its nested 'precise' node (if any).
    //  2) If the assignee object node is 'precise' or it contains 'precise'
    //  objects, traverses the right side of the assignment operation
    //  expression to mark arithmetic operations as 'noContration' and update
    //  'precise' access chain work list with new found object nodes.
    // Repeat above steps until the work list is empty.
    TNoContractionAssigneeCheckingTraverser checker(accesschain_mapping);
    TNoContractionPropagator propagator(&precise_object_accesschains, accesschain_mapping);

    // We have two initial precise work lists to handle:
    //  1) precise return nodes
    //  2) precise object access chains
    // We should process the precise return nodes first and the involved
    // objects in the return expression should be added to the precise object
    // access chain set.
    while (!precise_return_nodes.empty()) {
        glslang::TIntermBranch* precise_return_node = *precise_return_nodes.begin();
        propagator.propagateNoContractionInReturnNode(precise_return_node);
        precise_return_nodes.erase(precise_return_node);
    }

    while (!precise_object_accesschains.empty()) {
        // Get the access chain of a precise object from the work list.
        ObjectAccessChain precise_object_accesschain = *precise_object_accesschains.begin();
        // Get the symbol id from the access chain.
        ObjectAccessChain symbol_id = getFrontElement(precise_object_accesschain);
        // Get all the defining nodes of that symbol ID.
        std::pair<NodeMapping::iterator, NodeMapping::iterator> range =
            symbol_definition_mapping.equal_range(symbol_id);
        // Visits all the assignment nodes of that symbol ID and
        //  1) Check if the assignee node is 'precise' or contains 'precise'
        //  objects.
        //  2) Propagate the 'precise' to the top layer object nodes
        //  in the right side of the assignment operation, update the 'precise'
        //  work list with new access chains representing the new 'precise'
        //  objects, and mark arithmetic operations as 'noContraction'.
        for (NodeMapping::iterator defining_node_iter = range.first;
             defining_node_iter != range.second; defining_node_iter++) {
            TIntermOperator* defining_node = defining_node_iter->second;
            // Check the assignee node.
            auto checker_result = checker.getPrecisenessAndRemainedAccessChain(
                defining_node, precise_object_accesschain);
            bool& contain_precise = std::get<0>(checker_result);
            ObjectAccessChain& remained_accesschain = std::get<1>(checker_result);
            // If the assignee node is 'precise' or contains 'precise', propagate the
            // 'precise' to the right. Otherwise just skip this assignment node.
            if (contain_precise) {
                propagator.propagateNoContractionInOneExpression(defining_node,
                                                                 remained_accesschain);
            }
        }
        // Remove the last processed 'precise' object from the work list.
        precise_object_accesschains.erase(precise_object_accesschain);
    }
}
Ejemplo n.º 11
0
void cbHintAnimationPlugin::DoDrawHintRect( wxRect& rect, bool isInClientRect)
{
    wxRect scrRect;

    RectToScr( rect, scrRect );

    int prevLF = mpScrDc->GetLogicalFunction();

    mpScrDc->SetLogicalFunction( wxXOR );

    if ( isInClientRect )
    {
        // BUG BUG BUG (wx):: somehow stippled brush works only
        //                      when the bitmap created on stack, not
        //                      as a member of the class

        wxBitmap checker( (const char*)_gCheckerImg, 8,8 );

        wxBrush checkerBrush( checker );

        mpScrDc->SetPen( mpLayout->mNullPen );
        mpScrDc->SetBrush( checkerBrush );

        int half = mInClientHintBorder / 2;

        mpScrDc->DrawRectangle( scrRect.x - half, scrRect.y - half,
                                scrRect.width + 2*half, mInClientHintBorder );

        mpScrDc->DrawRectangle( scrRect.x - half, scrRect.y + scrRect.height - half,
                                scrRect.width + 2*half, mInClientHintBorder );

        mpScrDc->DrawRectangle( scrRect.x - half, scrRect.y + half - 1,
                                mInClientHintBorder, scrRect.height - 2*half + 2);

        mpScrDc->DrawRectangle( scrRect.x + scrRect.width - half,
                                scrRect.y + half - 1,
                                mInClientHintBorder, scrRect.height - 2*half + 2);

        mpScrDc->SetBrush( wxNullBrush );
    }
    else
    {
        // otherwise draw 1-pixel thin borders

        mpScrDc->SetPen( mpLayout->mBlackPen );

        mpScrDc->DrawLine( scrRect.x, scrRect.y,
                           scrRect.x + scrRect.width, scrRect.y );

        mpScrDc->DrawLine( scrRect.x, scrRect.y + 1,
                           scrRect.x, scrRect.y + scrRect.height );

        mpScrDc->DrawLine( scrRect.x+1, scrRect.y + scrRect.height,
                           scrRect.x + scrRect.width, scrRect.y + scrRect.height );

        mpScrDc->DrawLine( scrRect.x + scrRect.width , scrRect.y,
                           scrRect.x + scrRect.width, scrRect.y + scrRect.height + 1);
    }

    mpScrDc->SetLogicalFunction( prevLF );
}
glm::vec3 BoundingBoxMesh::getColor(const glm::vec3& position) const {

  if( equalsEpsilon(position.z, zLimits_.y) ) {
    return glm::vec3(0.5f, 0.8f, 0.5f);
  }

  if( equalsEpsilon(position.x, xLimits_.x) ) {
    glm::vec2 len{zLimits_.y - zLimits_.x, 
                  yLimits_.y - yLimits_.x};

    glm::vec2 uv{(zLimits_.y - position.z) / len.x, 
                 (yLimits_.y - position.y) / len.y};

    uv.y = 1.0f - uv.y;
    unsigned int row = uv.y * bitmapHeight_;
    unsigned int col = uv.x * bitmapWidth_;

    // std::cout << "width: " << bitmapHeight_ << std::endl;
    // std::cout << "height: " << bitmapWidth_ << std::endl;
    // std::cout << "size: " << bitmapSize_ << std::endl;
    // std::cout << "pos: " << row << " " << col << std::endl;

    unsigned int index = (row * bitmapWidth_ + col) * bitmapChannels_;
    // std::cout << "index: " << index << std::endl;
    // unsigned char alfa = bitmapData_[index];
    unsigned char red;   
    unsigned char green;
    unsigned char blue;

    // if( bitmapChannels_ == 3 ) {
      red = bitmapData_[index];
      green = bitmapData_[index + 1];
      blue = bitmapData_[index + 2];
    // } else {
    //   red = bitmapData_[index + 3];
    //   green = bitmapData_[index + 2];
    //   blue = bitmapData_[index + 1];
    // }

    glm::vec3 color{(float)red/(float)255, (float)green/(float)255, (float)blue/(float)255};
    // std::cout << "uv: " << uv.x << " " << uv.y << std::endl;
    // return glm::vec3(uv.y, 1.0f - uv.y, 0.0f);
    return color;
    // return glm::vec3(0.1f, 0.12f, 1.0f);
  }

  if( equalsEpsilon(position.x, xLimits_.y) ) {
    return glm::vec3(1.0f, 0.1f, 0.12f);
  }

  if( equalsEpsilon(position.y, yLimits_.x) ) {
    // glm::vec2 len{zLimits_.y - zLimits_.x, xLimits_.y - xLimits_.x};
    // glm::vec2 uv{(position.z / len.x), (position.x / len.y)};
    const glm::vec3 color1 = glm::vec3{0.9f, 0.9, 0.9f};
    const glm::vec3 color2 = glm::vec3{0.1f, 0.1f, 0.1f};
    return checker(position, color1, color2);
  }

  if( equalsEpsilon(position.y, yLimits_.y) ) {
    return glm::vec3(1.0f, 0.968627451f, 0.8f);
  }

  // return glm::vec3(0.1f, 0.12f, 1.0f);
  return glm::vec3(1.0f, 1.0f, 0.1f);

}
Ejemplo n.º 13
0
void genCode(astree* root, SymbolTable* table){
   if (root == NULL) {
	  return;
   }
   
   string currsym = get_yytname(root->symbol);

   if (currsym == "program") {
      for (size_t child = 0; child < root->children.size(); ++child) {
         string currsymbol = get_yytname(root->children[child]->symbol);
		 
         if (currsymbol == "vardecl") {
            string child2 = get_yytname(root->children[child]->children[2]->symbol);
            string ident = root->children[child]->children[1]->lexinfo->c_str();
            string declt = root->children[child]->children[0]->children[0]->children[0]->lexinfo->c_str();
            string newtype = converter(declt);
			
            if(root->children[child]->children[0]->children.size() == 2){
               declt = declt + "[]";
               newtype = converter(declt);
               fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
            } else {
               fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
            }
         }
         if (currsymbol == "struct_") {
			genCode(root->children[child], table);
		 }
      }

      fprintf(oilFile, "void __ocmain ()\n{\n");

      for (size_t child = 0; child < root->children.size(); ++child) {
         string currsymbol = get_yytname(root->children[child]->symbol);
         if (currsymbol != "vardecl" && currsymbol != "struct_") {
			genCode(root->children[child], table);
		 }
      }
      fprintf(oilFile, "}\n");
   }

   if (currsym == "vardecl") {
      string ident = root->children[1]->lexinfo->c_str();
      string dect = checker(root->children[1], table);
      if (root->children[0]->children.size() == 2) dect = dect + "[]";
      dect = converter(dect);
      string child2 = get_yytname(root->children[2]->symbol);
      if (child2 == "constant") {
         fprintf(oilFile, "%s_%d_%s = __%s\n", dect.c_str(),table->numBack(), ident.c_str(), root->children[2]->children[0]->lexinfo->c_str());
	  }
      if (child2 == "variable") {
         fprintf(oilFile, "%s_%d_%s = _%d_%s\n", dect.c_str(),table->numBack(), ident.c_str(), table->numBack(), root->children[2]->children[0]->lexinfo->c_str());
	  }
   }

   if (currsym == "binop") {
      string op = root->children[1]->lexinfo->c_str();
      if (op == "+" || op == "-" || op == "/" || op == "%" || op == "*") {
         int counter = icount++;
         string child0 = get_yytname(root->children[0]->symbol);
         string child2 = get_yytname(root->children[2]->symbol);
         if (child0 != "constant" && child0 != "constant") {
            genCode(root->children[0], table);
            fprintf(oilFile, "i%d = i%d ", counter, counter-1);
         }
         else if (child2 != "constant" && child2 != "constant") {
            genCode(root->children[2], table);
            fprintf(oilFile, "i%d = i%d ", counter, counter-1);
         } else {
			fprintf(oilFile, "i%d = ", counter);
		 }

         if(child0 == "constant") {
			fprintf(oilFile, "%s ", root->children[0]->children[0]->lexinfo->c_str());
		 }
         if(child0 == "variable") {
			fprintf(oilFile, "_%d_%s ", table->numBack(), root->children[0]->children[0]->lexinfo->c_str());
		 }
         fprintf(oilFile, "%s ", root->children[1]->lexinfo->c_str());
         if(child2 == "constant") {
			fprintf(oilFile, "%s;\n", root->children[2]->children[0]->lexinfo->c_str());
		 }
         if(child2 == "variable") {
			fprintf(oilFile, "_%d_%s;\n", table->numBack(), root->children[2]->children[0]->lexinfo->c_str());
		 }      
      }
	  
      if (op == ">" || op == "<" || op == ">=" || op == "<=" || op == "!=" || op == "==") {
         int counter = bcount++;
         string child0 = get_yytname(root->children[0]->symbol);
         string child2 = get_yytname(root->children[2]->symbol);
         if (child0 != "constant" && child0 != "constant") {
            genCode(root->children[0], table);
            fprintf(oilFile, "b%d = b%d ", counter, counter-1);
         }
         else if (child2 != "constant" && child2 != "constant") {
            genCode(root->children[2], table);
            fprintf(oilFile, "b%d = b%d ", counter, counter-1);
         } else {
			fprintf(oilFile, "b%d = ", counter);
		 }

         if(child0 == "constant") {
			fprintf(oilFile, "%s ", root->children[0]->children[0]->lexinfo->c_str());
		 }
         if(child0 == "variable") {
			fprintf(oilFile, "_%d_%s ", table->numBack(), root->children[0]->children[0]->lexinfo->c_str());
		 }
         fprintf(oilFile, "%s ", root->children[1]->lexinfo->c_str());
         if(child2 == "constant") {
			fprintf(oilFile, "%s;\n", root->children[2]->children[0]->lexinfo->c_str());
		 }
         if(child2 == "variable") { 
			fprintf(oilFile, "_%d_%s;\n", table->numBack(), root->children[2]->children[0]->lexinfo->c_str());
		 }
      }
   }

   if (currsym == "while_") {
      int currb = bcount;
      int currcount = controlcount++;
      fprintf(oilFile, "while_%d:;\n", currcount);
      genCode(root->children[0], table);
      fprintf(oilFile, "if(!b%d) goto break_%d;\n", currb, currcount);
      genCode(root->children[1],table);
      fprintf(oilFile, "goto while_%d;\n", currcount);
      fprintf(oilFile, "break_%d:;\n", currcount);
   }

   if (currsym == "if_") {
      int currb = bcount;
      int currcount = controlcount++;
      genCode(root->children[0],table);
      fprintf(oilFile, "if(!b%d) goto else_%d;\n", currb, currcount);
      genCode(root->children[1],table);
      fprintf(oilFile, "goto fi_%d;\n", currcount);
      fprintf(oilFile, "else_%d:;\n", currcount);
      if(root->children.size() == 3) genCode(root->children[2],table);
      fprintf(oilFile, "fi_%d:;\n", currcount);
   }

   if (currsym == "block") {
      SymbolTable* currblock = root->blockpt;
      for(size_t child = 0; child < root->children.size(); ++child){
         genCode(root->children[child], currblock);
      }
   }

   if (currsym == "struct_") {
      string structname;
      for (size_t child = 0; child < root->children.size(); ++child) {
         string currchild = get_yytname(root->children[child]->symbol);  
         if (currchild == "TOK_IDENT") {
            structname = root->children[child]->lexinfo->c_str();
         }
      }
      fprintf(oilFile, "struct %s{\n", structname.c_str());

      for (size_t child = 0; child < root->children.size(); ++child) {
         string currchild = get_yytname(root->children[child]->symbol);
         if (currchild == "decl") {
            string ident = root->children[child]->children[1]->lexinfo->c_str();
            string declt = root->children[child]->children[0]->children[0]->children[0]->lexinfo->c_str();
            string newtype = converter(declt);
            if (root->children[child]->children[0]->children.size() == 2) {
               declt = declt + "[]";
               newtype = converter(declt);
               fprintf(oilFile, "        %s%s;\n", newtype.c_str(), ident.c_str());
            } else {
               fprintf(oilFile, "        %s%s;\n", newtype.c_str(), ident.c_str());
            }
         }
      }
      fprintf(oilFile, "};\n");
   }

   if (currsym == "decl") {
      string ident = root->children[1]->lexinfo->c_str();
      string declt = root->children[0]->children[0]->children[0]->lexinfo->c_str();
      string newtype = converter(declt);
      if (root->children[0]->children.size() == 2) {
         declt = declt + "[]";
         newtype = converter(declt);
         fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
      } else {
         fprintf(oilFile, "%s__%s;\n", newtype.c_str(), ident.c_str());
      }
   }

   if (currsym == "function") {
      string funcname;
      string rettype;
      SymbolTable* currblock;
      astree* blockroot;
      for (size_t child = 0; child < root->children.size(); ++child) {
         string currchild = get_yytname(root->children[child]->symbol);
         if (currchild == "TOK_IDENT") {
            funcname = root->children[child]->lexinfo->c_str();
            rettype = checker(root->children[child], table);
            int firstparen = rettype.find_first_of('(',0);
            rettype = rettype.substr(0,firstparen);
         }
         if (currchild == "block") {
            currblock = root->children[child]->blockpt;
            blockroot = root->children[child];
            if (blockroot->children.size() == 0) return;
         }
      }
      fprintf(oilFile, "%s\n__%s(", converter(rettype).c_str(), funcname.c_str());

      for (size_t child = 0; child < root->children.size(); ++child) {
         int counter = 0;
         string currchild = get_yytname(root->children[child]->symbol);
         if (currchild == "decl") {
            string ident = root->children[child]->children[1]->lexinfo->c_str();
            string dectype = checker(root->children[child]->children[1], currblock);
            if (root->children[child]->children[0]->children.size() == 2) {
				dectype = dectype + "[]";
			}
            dectype = converter(dectype);
            if (counter != 0) {
				fprintf(oilFile, ",");
			}
            fprintf(oilFile, "\n   %s_%d_%s", dectype.c_str(), currblock->numBack(), ident.c_str());
         }
      }
      fprintf(oilFile, ")\n");
      genCode(blockroot, table);
   }
}
Ejemplo n.º 14
0
string checker(astree* root, SymbolTable* table){
   if(root == NULL) return NULL;
   string names = get_yytname(root->symbol);

   if(names == "TOK_INT" || names == "TOK_INTCON") return "int";
   if(names == "TOK_CHAR" || names == "TOK_CHARCON") return "char";
   if(names == "TOK_STRING" || names == "TOK_STRINGCON") return "string";
   if(names == "TOK_BOOL" || names == "TOK_TRUE" || names == "TOK_FALSE") return "bool";
   if(names == "TOK_NULL") return "null";

   if(names == "TOK_IDENT") return table->lookup(root->lexinfo->c_str());
   if(names == "constant") return checker(root->children[0], table);
   if(names == "type"){
      if(root->children.size() == 2){
         string type = checker(root->children[0],table);
         type = type + "[]";
         return type;
      }
    return checker(root->children[0], table);
   }
   if(names == "basetype"){
      string offSpr = get_yytname(root->children[0]->symbol);
      string ident = root->children[0]->lexinfo->c_str();
      if(offSpr == "TOK_IDENT"){
         if (strSym->lookup2(ident) != NULL) return ident;
      }
      return checker(root->children[0], table);

   }
   if(names == "variable") {
      if(root->children.size() == 1) return checker(root->children[0], table);
      if(root->children.size() == 2){
         string offSpr2 = get_yytname(root->children[1]->symbol);
         SymbolTable* curnt;
         if(offSpr2 == "TOK_IDENT"){
            string offSpr = checker(root->children[0],table);
            string ident = root->children[1]->lexinfo->c_str();
            if(strSym->lookup2(offSpr) != NULL){
               curnt = strSym->lookup2(offSpr);
               if (curnt == NULL){ 
                  errprintf("Not a variable of this struct!\n");
                  return "";
               }
               return curnt->lookup(ident);
            }
         }else{
            if(checker(root->children[1],table) == "int" && checker(root->children[0],table) == "string") return "char"; 
            if(checker(root->children[1],table) == "int" && checker(root->children[0],table) == "int[]") return "int";
            if(checker(root->children[1],table) == "int" && checker(root->children[0],table) == "bool[]") return "bool";
            if(checker(root->children[1],table) == "int" && checker(root->children[0],table) == "char[]") return "char";
            if(checker(root->children[1],table) == "int" && checker(root->children[0],table) == "struct[]") return "struct";
            if(checker(root->children[1],table) == "int" && checker(root->children[0],table) == "string[]") return "string";
         }
      }

   }

   if(names == "call"){
      string funcoper = "(";
      string funcname;
      string funcops;
      size_t check = -1;
      int begin;
      int comcounter = 0;
      int firstparen;
      for(size_t child = 0; child < root->children.size(); ++child){
         string currchild = get_yytname(root->children[child]->symbol);
         if(currchild != "TOK_IDENT"){
            if (comcounter != 0) funcoper = funcoper + ",";
            string currop = checker(root->children[child], table);
            funcoper = funcoper + currop;
            comcounter++;
         }
         if(currchild == "TOK_IDENT") funcname = root->children[child]->lexinfo->c_str();
      }
      funcoper = funcoper + ")";
      funcops = table->lookup(funcname);
      begin = funcops.length() - funcoper.length();
      if(funcops.find(funcoper) == check)
         errprintf("Incorrect arguments passed to function!\n");
      firstparen = funcops.find_first_of('(', 0);
      return funcops.substr(0,firstparen);
   }


   if(names == "vardecl"){
      string c0 = checker(root->children[0],table);
      string c1 = checker(root->children[2],table);
      if(c0 != c1) errprintf("Declaring incorrect type!\n");
      return "";
   }
   if(names == "program"){
      for(size_t child = 0; child < root->children.size(); ++ child){
         checker(root->children[child], table);
      }
   }
   if(names == "while_" || names == "if_"){
      if(checker(root->children[0],table) != "bool") errprintf("Expression does not return a bool!\n");
      checker(root->children[1], table);
      if(root->children[2] != NULL) checker(root->children[2], table);
      return "";
   }
   if(names == "function"){
      SymbolTable* currblock;
      astree* blockroot;
      string funcreturn;
      for(size_t child = 0; child < root->children.size(); ++child){
         string currchild = get_yytname(root->children[child]->symbol);
         if(currchild == "type"){
            funcreturn = checker(root->children[child], table);
         }
         if(currchild == "block"){
            currblock = root->children[child]->blockpt;
            blockroot = root->children[child];
         }
      }
      if(!searcher(blockroot, funcreturn, currblock)) errprintf("Incorrect return type!\n");
   }
   if(names == "block"){
      SymbolTable* currtable = root->blockpt;
      for(size_t child = 0; child < root->children.size(); ++child){
         checker(root->children[child], currtable);
      }
   }
   if(names == "allocator_"){
      if(root->children.size() < 3) return checker(root->children[1],table);
      else{
         string bracket = get_yytname(root->children[3]->symbol);
         string result = checker(root->children[1],table);
         if(bracket == "'['"){
            if(checker(root->children[2],table) == "int"){
               result = result + "[]";
               return result;
            }else errprintf("Need int in brackets!\n");
         }else return result;
      }
   }
   if(names == "binop"){
      string offSpr2 = get_yytname(root->children[1]->symbol);
      if(offSpr2 == "'+'" || offSpr2 == "'-'" || offSpr2 == "'*'" || offSpr2 == "'/'" || offSpr2 == "'%'"){
         if(checker(root->children[0],table) == "int" && checker(root->children[0], table) == checker(root->children[2],table))
            return "int";
         else errprintf("One or more inputs is not of type int\n");
      }
      if(offSpr2 == "TOK_LT" || offSpr2 == "TOK_LE" || offSpr2 == "TOK_GT" || offSpr2 == "TOK_GE"){
         string c0 = checker(root->children[0], table);
         string c1 = checker(root->children[2], table);
         if((c0 == "int" || c0 == "char" || c0 == "bool") && c0 == c1 )
            return "bool";
         else
            errprintf("Comparison of different or incorrect types!\n");
      }
      if(offSpr2 == "TOK_NE" || offSpr2 == "TOK_EQ"){
         string c0 = checker(root->children[0], table);
         string c1 = checker(root->children[2], table);
         if(c0 == c1 || (c0 != "bool" && c0 != "int" && c0 != "char" && c1 == "null"))
            return "bool";
         else
            errprintf("Comparison of different types!\n");
      }
      if(offSpr2 == "'='"){
         string c0 = checker(root->children[0], table);
         string c1 = checker(root->children[2], table);
         if(c0 == c1 || (c0 != "bool" && c0 != "int" && c0 != "char" && c1 == "null"))
            return c0;
         else
            errprintf("Trying to set variable to different type!\n");
      }
   }

   if(names == "unop"){
      string offSpr = get_yytname(root->children[0]->symbol);
      if(offSpr == "TOK_POS" || offSpr == "TOK_NEG"){
         if(checker(root->children[0]->children[0], table) == "int") return "int";
         else errprintf("Tried adding sign to non-int type!\n");
      }
      if(offSpr == "'!'"){
         if(checker(root->children[0]->children[0], table) == "bool") return "bool";
         else errprintf("Tried negating a non-bool!\n");
      }
      if(offSpr == "TOK_ORD"){
         if(checker(root->children[0]->children[0], table) == "char") return "int";
         else errprintf("Tried using ord on non-char type!\n");
      }
      if(offSpr == "TOK_CHR"){
         if(checker(root->children[0]->children[0], table) == "int") return "char";
         else errprintf("Tried using chr on non-int type!\n");
      }
   }
   return ""; 

}
Ejemplo n.º 15
0
void
TotemAI::UpdateAI(const uint32 /*diff*/)
{
    if (i_totem.GetTotemType() != TOTEM_ACTIVE)
        return;

    if (!i_totem.isAlive() || i_totem.IsNonMeleeSpellCasted(false))
        return;

    // Search spell
    SpellEntry const *spellInfo = sSpellStore.LookupEntry(i_totem.GetSpell());
    if (!spellInfo)
        return;

    // Get spell rangy
    SpellRangeEntry const* srange = sSpellRangeStore.LookupEntry(spellInfo->rangeIndex);
    float max_range = GetSpellMaxRange(srange);

    // SPELLMOD_RANGE not applied in this place just because not existence range mods for attacking totems

    // pointer to appropriate target if found any
    Unit* victim = i_victimGuid ? ObjectAccessor::GetUnit(i_totem, i_victimGuid) : NULL;

    // Search victim if no, not attackable, or out of range, or friendly (possible in case duel end)
    if (!victim ||
        !victim->isTargetableForAttack() || !i_totem.IsWithinDistInMap(victim, max_range) ||
        i_totem.IsFriendlyTo(victim) || !victim->isVisibleForOrDetect(&i_totem,false))
    {
        CellPair p(BlizzLike::ComputeCellPair(i_totem.GetPositionX(),i_totem.GetPositionY()));
        Cell cell(p);
        cell.data.Part.reserved = ALL_DISTRICT;

        victim = NULL;

        BlizzLike::NearestAttackableUnitInObjectRangeCheck u_check(&i_totem, &i_totem, max_range);
        BlizzLike::UnitLastSearcher<BlizzLike::NearestAttackableUnitInObjectRangeCheck> checker(victim, u_check);

        TypeContainerVisitor<BlizzLike::UnitLastSearcher<BlizzLike::NearestAttackableUnitInObjectRangeCheck>, GridTypeMapContainer > grid_object_checker(checker);
        TypeContainerVisitor<BlizzLike::UnitLastSearcher<BlizzLike::NearestAttackableUnitInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);

        //TODO: Backport BLizzLike Add to CreatureAI field pointing to creature itself
        //cell.Visit(p, grid_object_checker,  *m_creature.GetMap(), *m_creature, max_range);
        //cell.Visit(p, world_object_checker, *m_creature.GetMap(), *m_creature, max_range);
        cell.Visit(p, grid_object_checker,  *i_totem.GetMap());
        cell.Visit(p, world_object_checker, *i_totem.GetMap());
    }

    // If have target
    if (victim)
    {
        // remember
        i_victimGuid = victim->GetGUID();

        // attack
        i_totem.SetInFront(victim);                         // client change orientation by self
        i_totem.CastSpell(victim, i_totem.GetSpell(), false);
    }
    else
        i_victimGuid = 0;
}
Ejemplo n.º 16
0
EventBinder::EventBinder(lua_State* L)
{
	StackChecker checker(L, "EventBinder::EventBinder", 0);

	Binder binder(L);

	static const luaL_Reg functionList[] = {
		{"getType", &EventBinder::getType},
		{"getTarget", &EventBinder::getTarget},
		{"stopPropagation", &EventBinder::stopPropagation},
		{NULL, NULL},
	};

	binder.createClass("Event", NULL, create, 0, functionList);

	lua_getglobal(L, "Event");	// get metatable

	lua_pushstring(L, OpenUrlEvent::OPEN_URL.type());
	lua_setfield(L, -2, "OPEN_URL");

	lua_pushstring(L, Event::ENTER_FRAME.type());
	lua_setfield(L, -2, "ENTER_FRAME");

	lua_pushstring(L, Event::SOUND_COMPLETE.type());
	lua_setfield(L, -2, "SOUND_COMPLETE");
	
	lua_pushstring(L, Event::ADDED_TO_STAGE.type());
	lua_setfield(L, -2, "ADDED_TO_STAGE");

	lua_pushstring(L, Event::REMOVED_FROM_STAGE.type());
	lua_setfield(L, -2, "REMOVED_FROM_STAGE");

/*
	lua_pushstring(L, Event::APPLICATION_DID_FINISH_LAUNCHING.type());
	lua_setfield(L, -2, "APPLICATION_DID_FINISH_LAUNCHING");

	lua_pushstring(L, Event::APPLICATION_WILL_TERMINATE.type());
	lua_setfield(L, -2, "APPLICATION_WILL_TERMINATE");
	*/

    lua_pushstring(L, CompleteEvent::COMPLETE.type());
	lua_setfield(L, -2, "COMPLETE");

	lua_pushstring(L, Event::APPLICATION_START.type());
	lua_setfield(L, -2, "APPLICATION_START");

	lua_pushstring(L, Event::APPLICATION_EXIT.type());
	lua_setfield(L, -2, "APPLICATION_EXIT");

	lua_pushstring(L, Event::APPLICATION_SUSPEND.type());
	lua_setfield(L, -2, "APPLICATION_SUSPEND");

	lua_pushstring(L, Event::APPLICATION_RESUME.type());
	lua_setfield(L, -2, "APPLICATION_RESUME");

    lua_pushstring(L, Event::APPLICATION_BACKGROUND.type());
    lua_setfield(L, -2, "APPLICATION_BACKGROUND");

    lua_pushstring(L, Event::APPLICATION_FOREGROUND.type());
    lua_setfield(L, -2, "APPLICATION_FOREGROUND");

    lua_pushstring(L, Event::APPLICATION_RESIZE.type());
    lua_setfield(L, -2, "APPLICATION_RESIZE");

    lua_pushstring(L, Event::MEMORY_WARNING.type());
    lua_setfield(L, -2, "MEMORY_WARNING");

	lua_pushstring(L, StageOrientationEvent::ORIENTATION_CHANGE.type());
	lua_setfield(L, -2, "ORIENTATION_CHANGE");

	lua_pushstring(L, MouseEvent::MOUSE_UP.type());
	lua_setfield(L, -2, "MOUSE_UP");

	lua_pushstring(L, MouseEvent::MOUSE_DOWN.type());
	lua_setfield(L, -2, "MOUSE_DOWN");

	lua_pushstring(L, MouseEvent::MOUSE_MOVE.type());
	lua_setfield(L, -2, "MOUSE_MOVE");

    lua_pushstring(L, MouseEvent::MOUSE_HOVER.type());
    lua_setfield(L, -2, "MOUSE_HOVER");

	lua_pushstring(L, MouseEvent::MOUSE_WHEEL.type());
	lua_setfield(L, -2, "MOUSE_WHEEL");


	lua_pushstring(L, TouchEvent::TOUCHES_BEGIN.type());
	lua_setfield(L, -2, "TOUCHES_BEGIN");

	lua_pushstring(L, TouchEvent::TOUCHES_MOVE.type());
	lua_setfield(L, -2, "TOUCHES_MOVE");

	lua_pushstring(L, TouchEvent::TOUCHES_END.type());
	lua_setfield(L, -2, "TOUCHES_END");

	lua_pushstring(L, TouchEvent::TOUCHES_CANCEL.type());
	lua_setfield(L, -2, "TOUCHES_CANCEL");



	lua_pushstring(L, TimerEvent::TIMER.type());
	lua_setfield(L, -2, "TIMER");

	lua_pushstring(L, TimerEvent::TIMER_COMPLETE.type());
	lua_setfield(L, -2, "TIMER_COMPLETE");

	lua_pushstring(L, ErrorEvent::ERROR.type());
	lua_setfield(L, -2, "ERROR");

	lua_pushstring(L, ProgressEvent::PROGRESS.type());
	lua_setfield(L, -2, "PROGRESS");

    lua_pushstring(L, LayoutEvent::RESIZED.type());
    lua_setfield(L, -2, "LAYOUT_RESIZED");

	lua_pushstring(L, KeyboardEvent::KEY_UP.type());
	lua_setfield(L, -2, "KEY_UP");

	lua_pushstring(L, KeyboardEvent::KEY_DOWN.type());
	lua_setfield(L, -2, "KEY_DOWN");

	lua_pushstring(L, KeyboardEvent::KEY_CHAR.type());
	lua_setfield(L, -2, "KEY_CHAR");

	lua_pop(L, 1);
}
Ejemplo n.º 17
0
int EventDispatcherBinder::removeEventListener(lua_State* L)
{
	StackChecker checker(L, "EventDispatcherBinder::removeEventListener", 0);

	Binder binder(L);
	EventDispatcher* eventDispatcher = static_cast<EventDispatcher*>(binder.getInstance("EventDispatcher"));

	luaL_checktype(L, 2, LUA_TSTRING);
	luaL_checktype(L, 3, LUA_TFUNCTION);

	bool hasData = lua_gettop(L) >= 4;

	createEventsTable(L, 1);	// create __events table if it's not created

	EventBinderMap& map = getOrCreateEventBinderMap(eventDispatcher);

	const char* event = lua_tostring(L, 2);
	int eventid = StringId::instance().id(event);

	const std::vector<CppLuaBridge*>& bridges = map[eventid]; 

	lua_getfield(L, 1, "__events");

	// check if the event is already registered
	CppLuaBridge* bridge = 0;
	for (std::size_t i = 0; i < bridges.size(); ++i)
	{
		lua_pushlightuserdata(L, bridges[i]);
		lua_rawget(L, -2);	// we get the event check closure
		if (hasData == false)
		{
			lua_pushvalue(L, 3);	// function
			lua_call(L, 1, 1);
		}
		else
		{
			lua_pushvalue(L, 3);	// function
			lua_pushvalue(L, 4);	// data
			lua_call(L, 2, 1);
		}

		if (lua_toboolean(L, -1))
		{
			bridge = bridges[i];
			lua_pop(L, 1);
			break;
		}
		else
			lua_pop(L, 1);
	}

	if (bridge == 0)	// event is not registered
	{
		lua_pop(L, 1);		// pop __events
		return 0;
	}

	luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_eventClosures);
	lua_pushlightuserdata(L, bridge);	// key=bridge
	lua_pushnil(L);						// value=nil
	lua_rawset(L, -3);					// envtable["eventClosures"][bridge] = nil
	lua_pop(L, 1);						// pop envtable["eventClosures"]

	lua_pushlightuserdata(L, bridge);	// key=bridge
	lua_pushnil(L);						// value = nil
	lua_settable(L, -3);				// __events[bridge] = nil

	eventDispatcher->removeEventListener(LuaEvent::Type(event), bridge, &CppLuaBridge::luaEvent);

	map.remove(eventid, bridge);
		
	lua_pop(L, 1);		// pop __events

	return 0;
}
Ejemplo n.º 18
0
void GameObject::Update(uint32 /*p_time*/)
{
    if (IS_MO_TRANSPORT(GetGUID()))
    {
        //((Transport*)this)->Update(p_time);
        return;
    }

    switch (m_lootState)
    {
        case GO_NOT_READY:
        {
            switch(GetGoType())
            {
                case GAMEOBJECT_TYPE_TRAP:
                {
                    // Arming Time for GAMEOBJECT_TYPE_TRAP (6)
                    Unit* owner = GetOwner();
                    if (owner && ((Player*)owner)->isInCombat())
                        m_cooldownTime = time(NULL) + GetGOInfo()->trap.startDelay;
                    m_lootState = GO_READY;
                    break;
                }
                case GAMEOBJECT_TYPE_FISHINGNODE:
                {
                    // fishing code (bobber ready)
                    if( time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME )
                    {
                        // splash bobber (bobber ready now)
                        Unit* caster = GetOwner();
                        if(caster && caster->GetTypeId()==TYPEID_PLAYER)
                        {
                            SetGoState(0);
                            SetUInt32Value(GAMEOBJECT_FLAGS, 32);

                            UpdateData udata;
                            WorldPacket packet;
                            BuildValuesUpdateBlockForPlayer(&udata,((Player*)caster));
                            udata.BuildPacket(&packet);
                            ((Player*)caster)->GetSession()->SendPacket(&packet);

                            WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM,8+4);
                            data << GetGUID();
                            data << (uint32)(0);
                            ((Player*)caster)->SendMessageToSet(&data,true);
                        }

                        m_lootState = GO_READY;                 // can be succesfully open with some chance
                    }
                    return;
                }
                default:
                    m_lootState = GO_READY;                         // for other GOis same switched without delay to GO_READY
                    break;
            }
            // NO BREAK for switch (m_lootState)
        }
        case GO_READY:
        {
            if (m_respawnTime > 0)                          // timer on
            {
                if (m_respawnTime <= time(NULL))            // timer expired
                {
                    m_respawnTime = 0;
                    m_SkillupList.clear();
                    m_usetimes = 0;

                    switch (GetGoType())
                    {
                        case GAMEOBJECT_TYPE_FISHINGNODE:   //  can't fish now
                        {
                            Unit* caster = GetOwner();
                            if(caster && caster->GetTypeId()==TYPEID_PLAYER)
                            {
                                if(caster->m_currentSpells[CURRENT_CHANNELED_SPELL])
                                {
                                    caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->SendChannelUpdate(0);
                                    caster->m_currentSpells[CURRENT_CHANNELED_SPELL]->finish(false);
                                }

                                WorldPacket data(SMSG_FISH_NOT_HOOKED,0);
                                ((Player*)caster)->GetSession()->SendPacket(&data);
                            }
                            // can be delete
                            m_lootState = GO_JUST_DEACTIVATED;
                            return;
                        }
                        case GAMEOBJECT_TYPE_DOOR:
                        case GAMEOBJECT_TYPE_BUTTON:
                            //we need to open doors if they are closed (add there another condition if this code breaks some usage, but it need to be here for battlegrounds)
                            if( !GetGoState() )
                                SwitchDoorOrButton(false);
                            //flags in AB are type_button and we need to add them here so no break!
                        default:
                            if(!m_spawnedByDefault)         // despawn timer
                            {
                                                            // can be despawned or destroyed
                                SetLootState(GO_JUST_DEACTIVATED);
                                return;
                            }
                                                            // respawn timer
                            MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
                            break;
                    }
                }
            }

            // traps can have time and can not have
            GameObjectInfo const* goInfo = GetGOInfo();
            if(goInfo->type == GAMEOBJECT_TYPE_TRAP)
            {
                // traps
                Unit* owner = GetOwner();
                Unit* ok = NULL;                            // pointer to appropriate target if found any

                if(m_cooldownTime >= time(NULL))
                    return;

                bool IsBattleGroundTrap = false;
                //FIXME: this is activation radius (in different casting radius that must be selected from spell data)
                //TODO: move activated state code (cast itself) to GO_ACTIVATED, in this place only check activating and set state
                float radius = goInfo->trap.radius;
                if(!radius)
                {
                    if(goInfo->trap.cooldown != 3)            // cast in other case (at some triggring/linked go/etc explicit call)
                        return;
                    else
                    {
                        if(m_respawnTime > 0)
                            break;

                        radius = goInfo->trap.cooldown;       // battlegrounds gameobjects has data2 == 0 && data5 == 3
                        IsBattleGroundTrap = true;
                    }
                }

                bool NeedDespawn = (goInfo->trap.charges != 0);

                CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
                Cell cell(p);
                cell.data.Part.reserved = ALL_DISTRICT;

                // Note: this hack with search required until GO casting not implemented
                // search unfriendly creature
                if(owner && NeedDespawn)                    // hunter trap
                {
                    MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
                    MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(ok, u_check);

                    CellLock<GridReadGuard> cell_lock(cell, p);

                    TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_object_checker(checker);
                    cell_lock->Visit(cell_lock, grid_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));

                    // or unfriendly player/pet
                    if(!ok)
                    {
                        TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
                        cell_lock->Visit(cell_lock, world_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
                    }
                }
                else                                        // environmental trap
                {
                    // environmental damage spells already have around enemies targeting but this not help in case not existed GO casting support

                    // affect only players
                    Player* p_ok = NULL;
                    MaNGOS::AnyPlayerInObjectRangeCheck p_check(this, radius);
                    MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck>  checker(p_ok, p_check);

                    CellLock<GridReadGuard> cell_lock(cell, p);

                    TypeContainerVisitor<MaNGOS::PlayerSearcher<MaNGOS::AnyPlayerInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
                    cell_lock->Visit(cell_lock, world_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
                    ok = p_ok;
                }

                if (ok)
                {
                    Unit *caster =  owner ? owner : ok;

                    caster->CastSpell(ok, goInfo->trap.spellId, true);
                    m_cooldownTime = time(NULL) + 4;        // 4 seconds

                    if(NeedDespawn)
                        SetLootState(GO_JUST_DEACTIVATED);  // can be despawned or destroyed

                    if(IsBattleGroundTrap && ok->GetTypeId() == TYPEID_PLAYER)
                    {
                        //BattleGround gameobjects case
                        if(((Player*)ok)->InBattleGround())
                            if(BattleGround *bg = ((Player*)ok)->GetBattleGround())
                                bg->HandleTriggerBuff(GetGUID());
                    }
                }
            }

            if (m_charges && m_usetimes >= m_charges)
                SetLootState(GO_JUST_DEACTIVATED);          // can be despawned or destroyed

            break;
        }
        case GO_ACTIVATED:
        {
            switch(GetGoType())
            {
                case GAMEOBJECT_TYPE_DOOR:
                case GAMEOBJECT_TYPE_BUTTON:
                    if(GetAutoCloseTime() && (m_cooldownTime < time(NULL)))
                    {
                        SwitchDoorOrButton(false);
                        SetLootState(GO_JUST_DEACTIVATED);
                    }
                    break;
            }
            break;
        }
        case GO_JUST_DEACTIVATED:
        {
            //if Gameobject should cast spell, then this, but some GOs (type = 10) should be destroyed
            if (GetGoType() == GAMEOBJECT_TYPE_GOOBER)
            {
                uint32 spellId = GetGOInfo()->goober.spellId;

                if(spellId)
                {
                    std::set<uint32>::iterator it = m_unique_users.begin();
                    std::set<uint32>::iterator end = m_unique_users.end();
                    for (; it != end; it++)
                    {
                        Unit* owner = Unit::GetUnit(*this, uint64(*it));
                        if (owner) owner->CastSpell(owner, spellId, false);
                    }

                    m_unique_users.clear();
                    m_usetimes = 0;
                }
                //any return here in case battleground traps
            }

            if(GetOwnerGUID())
            {
                m_respawnTime = 0;
                Delete();
                return;
            }

            //burning flags in some battlegrounds, if you find better condition, just add it
            if (GetGoAnimProgress() > 0)
            {
                SendObjectDeSpawnAnim(this->GetGUID());
                //reset flags
                SetUInt32Value(GAMEOBJECT_FLAGS, GetGOInfo()->flags);
            }

            loot.clear();
            SetLootState(GO_READY);

            if(!m_respawnDelayTime)
                return;

            if(!m_spawnedByDefault)
            {
                m_respawnTime = 0;
                return;
            }

            m_respawnTime = time(NULL) + m_respawnDelayTime;

            // if option not set then object will be saved at grid unload
            if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
                SaveRespawnTime();

            ObjectAccessor::UpdateObjectVisibility(this);

            break;
        }
    }
}
Ejemplo n.º 19
0
int EventDispatcherBinder::addEventListener(lua_State* L)
{
	StackChecker checker(L, "EventDispatcherBinder::addEventListener", 0);

	Binder binder(L);
	EventDispatcher* eventDispatcher = static_cast<EventDispatcher*>(binder.getInstance("EventDispatcher", 1));

	luaL_checktype(L, 2, LUA_TSTRING);
	luaL_checktype(L, 3, LUA_TFUNCTION);

    bool hasData = !lua_isnoneornil(L, 4);

	createEventsTable(L, 1);	// create self.__events table if it's not created

	EventBinderMap& map = getOrCreateEventBinderMap(eventDispatcher);

	const char* event = lua_tostring(L, 2);
	int eventid = StringId::instance().id(event);

	const std::vector<CppLuaBridge*>& bridges = map[eventid]; 

	lua_getfield(L, 1, "__events");		// key is CppLuaBridge*, value is 'event check closure'

	// check if the event is already registered
	bool isFound = false;
	for (std::size_t i = 0; i < bridges.size(); ++i)
	{
		lua_pushlightuserdata(L, bridges[i]);
		lua_rawget(L, -2);	// we get the event check closure
		if (hasData == false)
		{
			lua_pushvalue(L, 3);	// function
			lua_call(L, 1, 1);
		}
		else
		{
			lua_pushvalue(L, 3);	// function
			lua_pushvalue(L, 4);	// data
			lua_call(L, 2, 1);
		}

		if (lua_toboolean(L, -1))
		{
			lua_pop(L, 1);
			isFound = true;
			break;
		}
		else
			lua_pop(L, 1);
	}

	if (isFound == true)
	{
		lua_pop(L, 1);		// pop __events, leave stack as it is
		return 0;
	}

    LuaApplication *application = (LuaApplication*)luaL_getdata(L);
    lua_State *mainL = application->getLuaState();

    CppLuaBridge* bridge = new CppLuaBridge(mainL);

	// create event closure
	luaL_rawgetptr(L, LUA_REGISTRYINDEX, &key_eventClosures);
	lua_pushlightuserdata(L, bridge);	// key=bridge
	if (hasData == false)				// value=closure
	{
        // self ve function'in eventClosure'in icine upvalue olarak koyulmasi garbage collect edilmesini engelliyor
        // bu yuzden {self, function} seklinde bi weak table yaratip ilk upvalue olarak onu set ediyoruz
		luaL_newweaktable(L);

        lua_pushvalue(L, 1);	// self
		lua_rawseti(L, -2, 1);

		lua_pushvalue(L, 3);	// function
        lua_rawseti(L, -2, 2);

        lua_pushcclosure(L, &eventClosure, 1);
	}
	else
	{
        // self, function ve data'nin eventClosure'in icine upvalue olarak koyulmasi garbage collect edilmesini engelliyor
        // bu yuzden {self, function, data} seklinde bi weak table yaratip ilk upvalue olarak onu set ediyoruz
		luaL_newweaktable(L);

        lua_pushvalue(L, 1);	// self
		lua_rawseti(L, -2, 1);

        lua_pushvalue(L, 3);	// function
        lua_rawseti(L, -2, 2);

        lua_pushvalue(L, 4);	// data
        lua_rawseti(L, -2, 3);

        lua_pushcclosure(L, &eventClosureWithData, 1);
	}
	lua_rawset(L, -3);					// envtable["eventClosures"][bridge] = closure
	lua_pop(L, 1);						// pop envtable["eventClosures"]

	// create event check closure
	lua_pushlightuserdata(L, bridge);
	if (hasData == false)
	{
		lua_pushvalue(L, 3);	// function
		lua_pushcclosure(L, &eventCheckClosure, 1);
	}
	else
	{
		lua_pushvalue(L, 3);	// function
		lua_pushvalue(L, 4);	// data
		lua_pushcclosure(L, &eventCheckClosureWithData, 2);
	}
	lua_rawset(L, -3);
	
	map.push_back(eventid, bridge);

	bridge->unref();
	
	eventDispatcher->addEventListener(LuaEvent::Type(event), bridge, &CppLuaBridge::luaEvent);

	lua_pop(L, 1);			// pop __events, leave stack as it is

	return 0;
}
Ejemplo n.º 20
0
void GameObject::TriggeringLinkedGameObject( uint32 trapEntry, Unit* target)
{
    GameObjectInfo const* trapInfo = sGOStorage.LookupEntry<GameObjectInfo>(trapEntry);
    if(!trapInfo || trapInfo->type!=GAMEOBJECT_TYPE_TRAP)
        return;

    SpellEntry const* trapSpell = sSpellStore.LookupEntry(trapInfo->trap.spellId);
    if(!trapSpell)                                          // checked at load already
        return;

    float range = GetSpellMaxRange(sSpellRangeStore.LookupEntry(trapSpell->rangeIndex));

    // search nearest linked GO
    GameObject* trapGO = NULL;
    {
        // using original GO distance
        CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
        Cell cell(p);
        cell.data.Part.reserved = ALL_DISTRICT;

        MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*target,trapEntry,range);
        MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(trapGO,go_check);

        TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
        CellLock<GridReadGuard> cell_lock(cell, p);
        cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
    }

    // found correct GO
    // FIXME: when GO casting will be implemented trap must cast spell to target
    if(trapGO)
        target->CastSpell(target,trapSpell,true);
}
Ejemplo n.º 21
0
void GameObject::Update(uint32 p_time)
{
    if (GUID_HIPART(GetGUID()) == HIGHGUID_TRANSPORT)
    {
        //((Transport*)this)->Update(p_time);
        return;
    }

    switch (m_lootState)
    {
        case GO_NOT_READY:
            if (GetGoType()==17)
            {
                // fishing code (bobber ready)
                if( time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME )
                {
                    // splash bobber (bobber ready now)
                    Unit* caster = GetOwner();
                    if(caster && caster->GetTypeId()==TYPEID_PLAYER)
                    {
                        SetUInt32Value(GAMEOBJECT_STATE, 0);
                        SetUInt32Value(GAMEOBJECT_FLAGS, 32);

                        UpdateData udata;
                        WorldPacket packet;
                        BuildValuesUpdateBlockForPlayer(&udata,((Player*)caster));
                        udata.BuildPacket(&packet);
                        ((Player*)caster)->GetSession()->SendPacket(&packet);

                        WorldPacket data;
                        data.Initialize(SMSG_GAMEOBJECT_CUSTOM_ANIM);
                        data << GetGUID();
                        data << (uint32)(0);
                        ((Player*)caster)->SendMessageToSet(&data,true);
                    }

                    m_lootState = GO_CLOSED;                // can be succesfully open with some chance
                }
                return;
            }

            m_lootState = GO_CLOSED;                        // for not bobber is same as GO_CLOSED
            // NO BREAK
        case GO_CLOSED:
            if (m_respawnTime > 0)
                                                            // timer on
            {
                if (m_respawnTime <= time(NULL))            // timer expired
                {
                    m_respawnTime = 0;
                    m_SkillupList.clear();

                    switch (GetGoType())
                    {
                        case GAMEOBJECT_TYPE_FISHINGNODE:   //  can't fish now
                        {
                            Unit* caster = GetOwner();
                            if(caster && caster->GetTypeId()==TYPEID_PLAYER)
                            {
                                if(caster->m_currentSpell)
                                {
                                    caster->m_currentSpell->SendChannelUpdate(0);
                                    caster->m_currentSpell->finish(false);
                                }

                                WorldPacket data;
                                data.Initialize(SMSG_FISH_NOT_HOOKED);
                                ((Player*)caster)->GetSession()->SendPacket(&data);
                            }
                            m_lootState = GO_LOOTED;        // can be delete
                            return;
                        }
                        case GAMEOBJECT_TYPE_DOOR:
                            SetUInt32Value (GAMEOBJECT_FLAGS, m_flags);
                            SetUInt32Value (GAMEOBJECT_STATE, 1);
                            break;
                        case GAMEOBJECT_TYPE_TRAP:
                            break;
                        default:
                            if(GetOwnerGUID())              // despawn timer
                            {
                                m_respawnTime = 0;
                                Delete();
                                return;
                            }
                                                            // respawn timer
                            MapManager::Instance().GetMap(GetMapId(), this)->Add(this);
                            break;
                    }
                }
            }
            break;
        case GO_OPEN:
            break;
        case GO_LOOTED:
            if(GetOwnerGUID())
            {
                m_respawnTime = 0;
                Delete();
                return;
            }

            loot.clear();
            SetLootState(GO_CLOSED);

            SendDestroyObject(GetGUID());
            m_respawnTime = time(NULL) + m_respawnDelayTime;

            // if option not set then object will be ssaved at grif unload
            if(sWorld.getConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY))
                SaveRespawnTime();

            break;
    }

    SpellEntry const *createSpell = m_spellId ? sSpellStore.LookupEntry(m_spellId) : NULL;
    if (!createSpell)
        return;
    int i;
    for (i = 0; i < 3; i++)
        if (createSpell->Effect[i] == SPELL_EFFECT_SUMMON_OBJECT_SLOT1)
            break;
    if (i<3)
    {
        // traps
        CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
        Cell cell = RedZone::GetZone(p);
        cell.data.Part.reserved = ALL_DISTRICT;

        Unit* owner = GetOwner();
        if (!owner)
        {
            m_respawnTime = 0;                              // to prevent save respawn timer
            Delete();
            return;
        }

        Unit* ok = NULL;                                    // pointer to appropriate target if found any

        float radius = GetRadius(sSpellRadiusStore.LookupEntry(createSpell->EffectRadiusIndex[i]));
        MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck u_check(this, owner, radius);
        MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck> checker(ok, u_check);

        CellLock<GridReadGuard> cell_lock(cell, p);

        // search unfriedly creature
        {
            TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, GridTypeMapContainer > grid_object_checker(checker);
            cell_lock->Visit(cell_lock, grid_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
        }

        // or unfriendly player/pet
        if(!ok)
        {
            TypeContainerVisitor<MaNGOS::UnitSearcher<MaNGOS::AnyUnfriendlyUnitInObjectRangeCheck>, WorldTypeMapContainer > world_object_checker(checker);
            cell_lock->Visit(cell_lock, world_object_checker, *MapManager::Instance().GetMap(GetMapId(), this));
        }

        if (ok)
        {
            owner->CastSpell(ok, GetGOInfo()->sound3, true);
            m_respawnTime = 0;                              // to prevent save respawn timer
            Delete();
        }
    }

    if (m_usetimes >= 5)
    {
        m_respawnTime = 0;                                  // to prevent save respawn timer
        Delete();
    }

}
Ejemplo n.º 22
0
static int bindAll(lua_State* L)
{
	Application* application = static_cast<Application*>(lua_touserdata(L, 1));
	lua_pop(L, 1);

	StackChecker checker(L, "bindAll", 0);

	setEnvironTable(L);

	{
		lua_newtable(L);
		luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_touches);

		lua_newtable(L);
		luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_eventClosures);

		lua_newtable(L);
		luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_events);

		luaL_newweaktable(L);
		luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_b2);

		lua_newtable(L);
		luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_timers);
	}

    luaL_newmetatable(L, "Object");
    lua_setglobal(L, "Object");
	
	EventBinder eventBinder(L);
	EventDispatcherBinder eventDispatcherBinder(L);
	TimerBinder timerBinder(L);
	MatrixBinder matrixBinder(L);
	SpriteBinder spriteBinder(L);
	TextureBaseBinder textureBaseBinder(L);
	TextureBinder textureBinder(L);
	TexturePackBinder texturePackBinder(L);
	BitmapDataBinder bitmapDataBinder(L);
	BitmapBinder bitmapBinder(L);
	StageBinder stageBinder(L, application);
	FontBaseBinder fontBaseBinder(L);
	FontBinder fontBinder(L);
	TTFontBinder ttfontBinder(L);
	TextFieldBinder textFieldBinder(L);
    AccelerometerBinder accelerometerBinder(L);
	Box2DBinder2 box2DBinder2(L);
	DibBinder dibBinder(L);
	TileMapBinder tileMapBinder(L);
	ApplicationBinder applicationBinder(L);
	ShapeBinder shapeBinder(L);
	MovieClipBinder movieClipBinder(L);
    UrlLoaderBinder urlLoaderBinder(L);
	GeolocationBinder geolocationBinder(L);
	GyroscopeBinder gyroscopeBinder(L);
    AlertDialogBinder alertDialogBinder(L);
    TextInputDialogBinder textInputDialogBinder(L);
    MeshBinder meshBinder(L);
    AudioBinder audioBinder(L);
    RenderTargetBinder renderTargetBinder(L);

	PluginManager& pluginManager = PluginManager::instance();
	for (size_t i = 0; i < pluginManager.plugins.size(); ++i)
        pluginManager.plugins[i].main(L, 0);

	lua_getglobal(L, "Event");
	lua_getfield(L, -1, "new");
	lua_pushlightuserdata(L, NULL);
	lua_call(L, 1, 1);
	lua_remove(L, -2);
	luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_Event);

	lua_getglobal(L, "Event");
	lua_getfield(L, -1, "new");
	lua_pushlightuserdata(L, NULL);
	lua_call(L, 1, 1);
	lua_remove(L, -2);
	luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_EnterFrameEvent);

	lua_getglobal(L, "Event");
	lua_getfield(L, -1, "new");
	lua_pushlightuserdata(L, NULL);
	lua_call(L, 1, 1);
	lua_remove(L, -2);
	luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_MouseEvent);

	lua_getglobal(L, "Event");
	lua_getfield(L, -1, "new");
	lua_pushlightuserdata(L, NULL);
	lua_call(L, 1, 1);
	lua_remove(L, -2);
	luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_TouchEvent);


	lua_getglobal(L, "Event");
	lua_getfield(L, -1, "new");
	lua_pushlightuserdata(L, NULL);
	lua_call(L, 1, 1);
	lua_remove(L, -2);
	luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_TimerEvent);

	lua_getglobal(L, "Event");
	lua_getfield(L, -1, "new");
	lua_pushlightuserdata(L, NULL);
	lua_call(L, 1, 1);
	lua_remove(L, -2);
	luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_KeyboardEvent);

    lua_getglobal(L, "Event");
    lua_getfield(L, -1, "new");
    lua_pushlightuserdata(L, NULL);
    lua_call(L, 1, 1);
    lua_remove(L, -2);
    luaL_rawsetptr(L, LUA_REGISTRYINDEX, &key_CompleteEvent);

#include "property.c.in"
#include "texturepack.c.in"
#include "sprite.c.in"
#include "compatibility.c.in"

	lua_newtable(L);

    lua_pushinteger(L, GINPUT_KEY_BACK);
	lua_setfield(L, -2, "BACK");
    lua_pushinteger(L, GINPUT_KEY_SEARCH);
	lua_setfield(L, -2, "SEARCH");
    lua_pushinteger(L, GINPUT_KEY_MENU);
	lua_setfield(L, -2, "MENU");
    lua_pushinteger(L, GINPUT_KEY_CENTER);
	lua_setfield(L, -2, "CENTER");
    lua_pushinteger(L, GINPUT_KEY_SELECT);
	lua_setfield(L, -2, "SELECT");
    lua_pushinteger(L, GINPUT_KEY_START);
	lua_setfield(L, -2, "START");
    lua_pushinteger(L, GINPUT_KEY_L1);
	lua_setfield(L, -2, "L1");
    lua_pushinteger(L, GINPUT_KEY_R1);
	lua_setfield(L, -2, "R1");

    lua_pushinteger(L, GINPUT_KEY_LEFT);
	lua_setfield(L, -2, "LEFT");
    lua_pushinteger(L, GINPUT_KEY_UP);
	lua_setfield(L, -2, "UP");
    lua_pushinteger(L, GINPUT_KEY_RIGHT);
	lua_setfield(L, -2, "RIGHT");
    lua_pushinteger(L, GINPUT_KEY_DOWN);
	lua_setfield(L, -2, "DOWN");

    lua_pushinteger(L, GINPUT_KEY_A);
    lua_setfield(L, -2, "A");
    lua_pushinteger(L, GINPUT_KEY_B);
    lua_setfield(L, -2, "B");
    lua_pushinteger(L, GINPUT_KEY_C);
    lua_setfield(L, -2, "C");
    lua_pushinteger(L, GINPUT_KEY_D);
    lua_setfield(L, -2, "D");
    lua_pushinteger(L, GINPUT_KEY_E);
    lua_setfield(L, -2, "E");
    lua_pushinteger(L, GINPUT_KEY_F);
    lua_setfield(L, -2, "F");
    lua_pushinteger(L, GINPUT_KEY_G);
    lua_setfield(L, -2, "G");
    lua_pushinteger(L, GINPUT_KEY_H);
    lua_setfield(L, -2, "H");
    lua_pushinteger(L, GINPUT_KEY_I);
    lua_setfield(L, -2, "I");
    lua_pushinteger(L, GINPUT_KEY_J);
    lua_setfield(L, -2, "J");
    lua_pushinteger(L, GINPUT_KEY_K);
    lua_setfield(L, -2, "K");
    lua_pushinteger(L, GINPUT_KEY_L);
    lua_setfield(L, -2, "L");
    lua_pushinteger(L, GINPUT_KEY_M);
    lua_setfield(L, -2, "M");
    lua_pushinteger(L, GINPUT_KEY_N);
    lua_setfield(L, -2, "N");
    lua_pushinteger(L, GINPUT_KEY_O);
    lua_setfield(L, -2, "O");
    lua_pushinteger(L, GINPUT_KEY_P);
    lua_setfield(L, -2, "P");
    lua_pushinteger(L, GINPUT_KEY_Q);
    lua_setfield(L, -2, "Q");
    lua_pushinteger(L, GINPUT_KEY_R);
    lua_setfield(L, -2, "R");
    lua_pushinteger(L, GINPUT_KEY_S);
    lua_setfield(L, -2, "S");
    lua_pushinteger(L, GINPUT_KEY_T);
    lua_setfield(L, -2, "T");
    lua_pushinteger(L, GINPUT_KEY_U);
    lua_setfield(L, -2, "U");
    lua_pushinteger(L, GINPUT_KEY_V);
    lua_setfield(L, -2, "V");
    lua_pushinteger(L, GINPUT_KEY_W);
    lua_setfield(L, -2, "W");
    lua_pushinteger(L, GINPUT_KEY_X);
    lua_setfield(L, -2, "X");
    lua_pushinteger(L, GINPUT_KEY_Y);
    lua_setfield(L, -2, "Y");
    lua_pushinteger(L, GINPUT_KEY_Z);
    lua_setfield(L, -2, "Z");

    lua_pushinteger(L, GINPUT_KEY_0);
    lua_setfield(L, -2, "NUM_0");
    lua_pushinteger(L, GINPUT_KEY_1);
    lua_setfield(L, -2, "NUM_1");
    lua_pushinteger(L, GINPUT_KEY_2);
    lua_setfield(L, -2, "NUM_2");
    lua_pushinteger(L, GINPUT_KEY_3);
    lua_setfield(L, -2, "NUM_3");
    lua_pushinteger(L, GINPUT_KEY_4);
    lua_setfield(L, -2, "NUM_4");
    lua_pushinteger(L, GINPUT_KEY_5);
    lua_setfield(L, -2, "NUM_5");
    lua_pushinteger(L, GINPUT_KEY_6);
    lua_setfield(L, -2, "NUM_6");
    lua_pushinteger(L, GINPUT_KEY_7);
    lua_setfield(L, -2, "NUM_7");
    lua_pushinteger(L, GINPUT_KEY_8);
    lua_setfield(L, -2, "NUM_8");
    lua_pushinteger(L, GINPUT_KEY_9);
    lua_setfield(L, -2, "NUM_9");

	lua_setglobal(L, "KeyCode");


	// correct clock function which is wrong in iphone
	lua_getglobal(L, "os");
	lua_pushcfunction(L, os_timer);
	lua_setfield(L, -2, "timer");
	lua_pop(L, 1);

	// register collectgarbagelater
//	lua_pushcfunction(L, ::collectgarbagelater);
//	lua_setglobal(L, "collectgarbagelater");

	registerModules(L);

	return 0;
}
Ejemplo n.º 23
0
void KoColorSlider::drawContents( QPainter *painter )
{
    QPixmap checker(8, 8);
    QPainter p(&checker);
    p.fillRect(0, 0, 4, 4, Qt::lightGray);
    p.fillRect(4, 0, 4, 4, Qt::darkGray);
    p.fillRect(0, 4, 4, 4, Qt::darkGray);
    p.fillRect(4, 4, 4, 4, Qt::lightGray);
    p.end();
    QRect contentsRect_(contentsRect());
    painter->fillRect(contentsRect_, QBrush(checker));

    if( !d->upToDate || d->pixmap.isNull() || d->pixmap.width() != contentsRect_.width()
        || d->pixmap.height() != contentsRect_.height() )
    {
        KoColor c = d->minColor; // smart way to fetch colorspace
        QColor color;

        const quint8 *colors[2];
        colors[0] = d->minColor.data();
        colors[1] = d->maxColor.data();

        KoMixColorsOp * mixOp = c.colorSpace()->mixColorsOp();

        QImage image(contentsRect_.width(), contentsRect_.height(), QImage::Format_ARGB32 );

        if( orientation() == Qt::Horizontal ) {
            for (int x = 0; x < contentsRect_.width(); x++) {

                qreal t = static_cast<qreal>(x) / (contentsRect_.width() - 1);

                qint16 colorWeights[2];
                colorWeights[0] = static_cast<quint8>((1.0 - t) * 255 + 0.5);
                colorWeights[1] = 255 - colorWeights[0];

                mixOp->mixColors(colors, colorWeights, 2, c.data());

                c.toQColor(&color);

                for (int y = 0; y < contentsRect_.height(); y++)
                image.setPixel(x, y, color.rgba());
            }
        }
        else {
            for (int y = 0; y < contentsRect_.height(); y++) {

                qreal t = static_cast<qreal>(y) / (contentsRect_.height() - 1);

                qint16 colorWeights[2];
                colorWeights[0] = static_cast<quint8>((t) * 255 + 0.5);
                colorWeights[1] = 255 - colorWeights[0];

                mixOp->mixColors(colors, colorWeights, 2, c.data());

                c.toQColor(&color);

                for (int x = 0; x < contentsRect_.width(); x++)
                image.setPixel(x, y, color.rgba());
            }
        }
        d->pixmap = QPixmap::fromImage(image);
        d->upToDate = true;
    }
    painter->drawPixmap( contentsRect_, d->pixmap, QRect( 0, 0, d->pixmap.width(), d->pixmap.height()) );
}
Ejemplo n.º 24
0
            void UpdateAI(const uint32 diff)
            {
                if (!UpdateVictim() || !CheckInArea(diff, 5764))
                    return;

                events.Update(diff);

                if (me->HasUnitState(UNIT_STATE_CASTING))
                    return;

                while (uint32 eventId = events.ExecuteEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_CHECK_HIGH:
                        {
                            //if (!me->getVictim() || !me->IsWithinMeleeRange(me->getVictim()))
                            std::list<Player*> PlayerList;
                            PlayerPositionCheck checker(true);
							MoPCore::PlayerListSearcher<PlayerPositionCheck> searcher(me, PlayerList, checker);
                            me->VisitNearbyWorldObject(300.0f, searcher);
                            if (PlayerList.size() == 0)
                                DoCastAOE(SPELL_VENOM_RAIN);
                            events.ScheduleEvent(EVENT_CHECK_HIGH, 5000);
                            break;
                        }
                        case EVENT_EMBER_FLARE:
                            if (uiPhase == 0)
                            {
                                std::list<Player*> PlayerList;
                                PlayerPositionCheck checker(true);
								MoPCore::PlayerListSearcher<PlayerPositionCheck> searcher(me, PlayerList, checker);
                                me->VisitNearbyWorldObject(300.0f, searcher);
                                if (PlayerList.size() > 0)
                                    DoCastAOE(SPELL_EMBER_FLARE_1);
                            }
                            else
                            {
                                DoCastAOE(SPELL_EMBER_FLARE_2);
                            }
                            
                            events.ScheduleEvent(EVENT_EMBER_FLARE, urand(6000, 7000)); 
                            break;
                        case EVENT_FILAMENT:
                            for (uint8 i = 0; i < RAID_MODE(2, 4, 2, 4); i++)
                                if (Creature* pFilament = me->SummonCreature(NPC_SPIDERWEB_FILAMENT, addsPos[4].GetPositionX() + irand(-8, 8), addsPos[4].GetPositionY() + irand(-8, 8), addsPos[4].GetPositionZ(), 0.0f))
                                    pFilament->SetCanFly(true);
                            events.ScheduleEvent(EVENT_FILAMENT, urand(20000, 25000));
                            break;
                        case EVENT_SUMMON_DRONE:
                            if (Creature* pDrone = me->SummonCreature(NPC_CINDERWEB_DRONE, addsPos[3]))
                                //pDrone->GetMotionMaster()->MovePoint(0, addsPos[5]);
                                if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, PositionSelector(true, 0)))
                                    pDrone->GetMotionMaster()->MoveChase(pTarget);
                            events.ScheduleEvent(EVENT_SUMMON_DRONE, 60000);
                            break;
                        case EVENT_SUMMON_SPIDERLING:
                            uiSide = urand(0, 2);
                            for (uint8 i = 0; i < 8; i++)
                                events.ScheduleEvent(EVENT_SUMMON_SPIDERLING_1, i * 500);
                            if (IsHeroic())
                                for (uint8 i = 0; i < RAID_MODE(1, 2, 1, 2); ++i)
                                    events.ScheduleEvent(EVENT_SUMMON_BROODLING_1, i * 1000);
                            events.ScheduleEvent(EVENT_SUMMON_SPIDERLING, 30000);
                            break;
                        case EVENT_SUMMON_SPIDERLING_1:
                            if (Creature* pSpiderling = me->SummonCreature(NPC_CINDERWEB_SPIDERLING, addsPos[uiSide]))
                                pSpiderling->GetMotionMaster()->MovePoint(0, addsPos[5]);
                            break;
                        case EVENT_SUMMON_BROODLING_1:
                            if (Creature* pBroodling = me->SummonCreature(NPC_ENGORGED_BROODLING, addsPos[uiSide]))
                                if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, PositionSelector(true, 0)))
                                {
                                    pBroodling->CastSpell(pTarget, SPELL_FIXATE_BROODLING, true);
                                    pBroodling->ClearUnitState(UNIT_STATE_CASTING);
                                    pBroodling->GetMotionMaster()->MoveFollow(pTarget, 0.0f, 0.0f);
                                }
                            break;
                        case EVENT_ENERGY_2:
                            //me->SetPower(POWER_MANA, 9000);
                            break;
                        case EVENT_ENERGY:
                        {
                            uint32 energy = me->GetPower(POWER_MANA);
                            if (energy > 0)
                                me->SetPower(POWER_MANA, energy - 100);
                            if ((energy - 100) == 0)
                            {
                                uiCount++;
                                if (uiCount < 3)
                                {
                                    events.RescheduleEvent(EVENT_FILAMENT, 23000);
                                    events.RescheduleEvent(EVENT_CHECK_HIGH, 12000);
                                    events.RescheduleEvent(EVENT_EMBER_FLARE, 14000);
                                    events.ScheduleEvent(EVENT_ENERGY, 10000);
                                    events.ScheduleEvent(EVENT_ENERGY_2, 8000);
                                }
                                else
                                {
                                    events.CancelEvent(EVENT_ENERGY);
                                    events.CancelEvent(EVENT_FILAMENT);
                                    events.CancelEvent(EVENT_CHECK_HIGH);
                                    events.CancelEvent(EVENT_SUMMON_DRONE);
                                    events.CancelEvent(EVENT_SUMMON_SPIDERLING);
                                    events.RescheduleEvent(EVENT_EMBER_FLARE, 15000);
                                    events.ScheduleEvent(EVENT_GO_DOWN, 10000);
                                }
                                
                                DoCastAOE(SPELL_SMOLDERING_DEVASTATION);
                            }
                            else
                                events.ScheduleEvent(EVENT_ENERGY, 1000);
                            break;
                        }
                        case EVENT_GO_DOWN:
                        {
                            uiPhase = 1;
                            me->GetMotionMaster()->MoveJump(addsPos[5].GetPositionX(), addsPos[5].GetPositionY(), addsPos[5].GetPositionZ(), 40.0f, 40.0f);
                            events.ScheduleEvent(EVENT_FRENZY, 10000);
                            events.ScheduleEvent(EVENT_THE_WIDOW_KISS, 32000);
                            Map::PlayerList const &PlayerList = instance->instance->GetPlayers();
                            if (!PlayerList.isEmpty())
                            {
                                for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i)
                                    if (Player* player = i->getSource())
                                        if (player->GetPositionZ() > 100.0f)
                                            player->NearTeleportTo(addsPos[5].GetPositionX(), addsPos[5].GetPositionY(), addsPos[5].GetPositionZ(), 0.0f);
                            }
                            break;
                        }
                        case EVENT_FRENZY:
                            DoCast(me, SPELL_FRENZY);
                            events.ScheduleEvent(EVENT_FRENZY, 7000);
                            break;
                        case EVENT_THE_WIDOW_KISS:
                            DoCastVictim(SPELL_THE_WIDOW_KISS);
                            events.ScheduleEvent(EVENT_THE_WIDOW_KISS, 34000);
                            break;
                    }
                }
                
                DoMeleeAttackIfReady();
            }
            void UpdateAI(const uint32 diff)
            {
                if (!UpdateVictim() || !CheckInArea(diff, 5769))
                    return;

                events.Update(diff);

                if (me->HasUnitState(UNIT_STATE_CASTING))
                    return;

                if (me->GetPower(POWER_ENERGY) == 100)
                {
                    if (_currentPhase == PHASE_CAT)
                    {
                        DoCast(me, SPELL_LEAPING_FLAMES_SUMMON, true);
                        Unit* target = NULL;
                        target = SelectTarget(SELECT_TARGET_RANDOM, 1, -20.0f, true);
                        if (!target)
                            target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0.0f, true);
                        if (target)
                            DoCast(target, SPELL_LEAPING_FLAMES);
                        else
                            me->SetPower(POWER_ENERGY, 0);
                    }
                    else if (_currentPhase == PHASE_SCORPION)
                    {
                        DoCastVictim(SPELL_FLAME_SCYTHE);
                    }
                }

                while (uint32 eventId = events.ExecuteEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_CHECK_PHASE:
                        {
                            uint8 _phase = PHASE_CAT;
                            if (Unit* target = me->getVictim())
                            {
                                std::list<Player*> PlayerList;
                                TrinityCore::AnyPlayerInObjectRangeCheck checker(target, 10.0f);
                                TrinityCore::PlayerListSearcher<TrinityCore::AnyPlayerInObjectRangeCheck> searcher(target, PlayerList, checker);
                                target->VisitNearbyWorldObject(5.0f, searcher);
                                uint8 const minTargets = Is25ManRaid() ? 18 : 7;
                                if (PlayerList.size() >= minTargets)
                                    _phase = PHASE_SCORPION;
                            }

                            if (_currentPhase != _phase)
                            {
                                me->SetPower(POWER_ENERGY, 0);
                                me->RemoveAurasDueToSpell(SPELL_ADRENALINE);
                                _changePhaseNum++;
                                if (_changePhaseNum % 3 == 0)
                                {
                                    me->RemoveAurasDueToSpell(SPELL_CAT_FORM);
                                    me->RemoveAurasDueToSpell(SPELL_SCORPION_FORM);
                                    Talk(_currentPhase == PHASE_CAT ? SAY_HUMANOID_1 : SAY_HUMANOID_2);
                                    DoCastAOE(SPELL_FIERY_CYCLONE, true);
                                    DoCastAOE(_currentPhase == PHASE_CAT ? SPELL_SEARING_SEEDS : SPELL_BURNING_ORBS);
                                    // Delayed Transmormation
                                    events.ScheduleEvent(_currentPhase == PHASE_CAT ? EVENT_SCORPION_FORM : EVENT_CAT_FORM, 4500);
                                    events.ScheduleEvent(EVENT_CHECK_PHASE, 6000);
                                    return;
                                }
                                else
                                {
                                    // Normal Transformation
                                    if (_phase == PHASE_CAT)
                                    {
                                        _currentPhase = PHASE_CAT;
                                        Talk(SAY_TRANSFORM_2);
                                        me->SetPower(POWER_ENERGY, 0);
                                        DoCast(me, SPELL_CAT_FORM, true);
                                        DoCast(me, SPELL_FURY, true);
                                        
                                    }
                                    else if (_phase == PHASE_SCORPION)
                                    {
                                        _currentPhase = PHASE_SCORPION;
                                        Talk(SAY_TRANSFORM_1);
                                        me->SetPower(POWER_ENERGY, 0);
                                        DoCast(me, SPELL_SCORPION_FORM, true);
                                        DoCast(me, SPELL_FURY, true);
                                    }
                                }                                
                            }

                            events.ScheduleEvent(EVENT_CHECK_PHASE, 1000);
                            break;
                        }
                        case EVENT_CAT_FORM:
                            _currentPhase = PHASE_CAT;
                            Talk(SAY_TRANSFORM_2);
                            me->SetPower(POWER_ENERGY, 0);
                            DoCast(me, SPELL_CAT_FORM, true);
                            DoCast(me, SPELL_FURY, true);
                            break;
                        case EVENT_SCORPION_FORM:
                            _currentPhase = PHASE_SCORPION;
                            Talk(SAY_TRANSFORM_1);
                            me->SetPower(POWER_ENERGY, 0);
                            DoCast(me, SPELL_SCORPION_FORM, true);
                            DoCast(me, SPELL_FURY, true);
                            break;
                        case EVENT_BERSERK:
                            DoCast(me, SPELL_BERSERK);
                            break;
                    }
                }

                DoMeleeAttackIfReady();
            }
Ejemplo n.º 26
0
    void UpdateAI(const uint32 diff)
    {
        if (bCanEat || bIsEating)
        {
            if (EatTimer < diff)
            {
                if (bCanEat && !bIsEating)
                {

                    if (Unit* pUnit = Unit::GetUnit(*m_creature, uiPlayerGUID))
                    {
                        GameObject* pGo = NULL;

                        CellPair p(MaNGOS::ComputeCellPair(pUnit->GetPositionX(), pUnit->GetPositionY()));
                        Cell cell(p);
                        cell.data.Part.reserved = ALL_DISTRICT;
                        float range = pUnit->GetDistance(m_creature)+10;
                        MaNGOS::NearestGameObjectEntryInObjectRangeCheck go_check(*pUnit, ROCKNAIL_FLAYER_CARCASS,range);
                        MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck> checker(pGo,go_check);

                        TypeContainerVisitor<MaNGOS::GameObjectLastSearcher<MaNGOS::NearestGameObjectEntryInObjectRangeCheck>, GridTypeMapContainer > object_checker(checker);
                        CellLock<GridReadGuard> cell_lock(cell, p);
                        cell_lock->Visit(cell_lock, object_checker, *pUnit->GetMap(), *pUnit, range);

                        if (pGo)
                        {
                            if (m_creature->GetMotionMaster()->GetCurrentMovementGeneratorType() == WAYPOINT_MOTION_TYPE)
                                m_creature->GetMotionMaster()->MovementExpired();

                            m_creature->GetMotionMaster()->MoveIdle();
                            m_creature->StopMoving();

                            m_creature->GetMotionMaster()->MovePoint(POINT_ID, pGo->GetPositionX(), pGo->GetPositionY(), pGo->GetPositionZ());
                        }
                    }
                }
                if (bIsReach)
                {
                    bCanEat = false;
                    bIsEating = true;
                    DoCast(m_creature, SPELL_JUST_EATEN);
                    DoScriptText(SAY_JUST_EATEN, m_creature);

                    if (Player* pPlr = (Player*)Unit::GetUnit((*m_creature), uiPlayerGUID))
                    {
                        pPlr->KilledMonsterCredit(NPC_EVENT_PINGER, m_creature->GetGUID());
                    }

                    Reset();
                    m_creature->GetMotionMaster()->Clear();
                }
            EatTimer = 1000;
            }
            else
                EatTimer -= diff;

            return;
        }

        if (!m_creature->SelectHostileTarget() || !m_creature->getVictim() || m_creature->HasAura(SPELL_JUST_EATEN))
            return;

        if (CastTimer < diff)
        {
            DoCast(m_creature->getVictim(), SPELL_NETHER_BREATH);
            CastTimer = 5000;
        }else CastTimer -= diff;

        DoMeleeAttackIfReady();
    }
Ejemplo n.º 27
0
int main()
{
  Point p1(-253.357, -123.36);
  Point p2(-190.03, 216.606);
  Point p3(-343.349, 286.6);
  Point p4(141.604, 279.934);
  Point p5(276.591, -46.7012);
  Point p6(251.593, -263.347);
  Point p7(-3.38184, -343.339);
  Point p8(-380.012, -173.355);
  Point p9(-98.3726, 39.957);
  Point p10(133.271, 124.949);
  Point p11(289.923, 301.598);
  Point p12(421.577, 23.292);
  Point p13(79.9434, -93.3633);
  Point p14(-40.0449, 366.592);
  Point p15(311.587, 374.924);
  Point p16(431.576, 214.94);
  Point p17(426.576, -131.693);
  Point p18(-265.023, -285.011);
  Point p19(369.915, 89.9521);
  Point p20(368.249, -15.0376);
  Point p21(484.904, 18.2925);
  Point p22(-411.675, 283.267);
  Point p23(-250.024, 124.949);
  Point p24(-80.041, -78.3647);
  Point p25(-360.014, 31.6245);
  Point p26(-305.019, 356.593);
  
  // built Delaunay triangulation
  PS.insert(p1); PS.insert(p2); PS.insert(p3); PS.insert(p4);
  PS.insert(p5); PS.insert(p6); PS.insert(p7); PS.insert(p8);  
  PS.insert(p9); PS.insert(p10); PS.insert(p11); PS.insert(p12);
  PS.insert(p13); PS.insert(p14); PS.insert(p15); PS.insert(p16);  
  PS.insert(p17); PS.insert(p18); PS.insert(p19); PS.insert(p20);
  PS.insert(p21); PS.insert(p22); PS.insert(p23); PS.insert(p24);
  PS.insert(p25); PS.insert(p26);
  
  std::list<Vertex_handle> LV;
  
  bool correct = true;
  
  // circle emptiness check
  Circle cs1(Point(-23.3799, 108.284), 1124.78);
  check_empty checker(cs1);
  
  CGAL::range_search(PS,cs1,std::back_inserter(LV),checker,true);
   
  if (checker.get_result()) {
    std::cout << "circle not empty !\n";
    std::cout <<  "this is an error !\n"; correct=false;
  }
  else std::cout << "circle was empty !\n";  
  
  Circle cs2(Point(-255.024, -100.029), 23551);
  check_empty checker2(cs2);
  
  CGAL::range_search(PS,cs2,std::back_inserter(LV),checker2,true);
   
  if (checker2.get_result()) std::cout << "circle not empty !\n";
  else {
    std::cout << "circle was empty !\n";   
    std::cout <<  "this is an error !\n"; correct=false;
  } 
  
  // triangle check
  Triangle t1(Point(-21.7134, -123.36), Point(84.9429, 74.9536), Point(209.931, -161.69)); 
  Triangle t2(Point(-61.7095, 164.945), Point(-88.3735, 101.618), Point(49.9463, 101.618));
  
  check_empty_triangle tchecker1(t1);
  CGAL::range_search(PS,t1.vertex(0),t1.vertex(1),t1.vertex(2),std::back_inserter(LV),tchecker1,true);
   
  if (tchecker1.get_result()) std::cout << "triangle not empty !\n";
  else {
    std::cout << "triangle was empty !\n";   
    std::cout <<  "this is an error !\n"; correct=false;
  }
  
  check_empty_triangle tchecker2(t2);
  CGAL::range_search(PS,t2.vertex(0),t2.vertex(1),t2.vertex(2),std::back_inserter(LV),tchecker2,true);
   
  if (tchecker2.get_result()) {
     std::cout << "triangle not empty !\n";
     std::cout <<  "this is an error !\n"; correct=false;
  }
  else std::cout << "triangle was empty !\n";   
  
  // rectangle check
  Rectangle_2 r1(-290.021, -175.022, -125.037, -35.0356);       
  Rectangle_2 r2(-48.3774, 136.614, -23.3799, 251.603);   

  check_empty_rectangle rchecker1(r1);
  CGAL::range_search(PS,r1.vertex(0),r1.vertex(1),r1.vertex(2),r1.vertex(3),std::back_inserter(LV),rchecker1,true);
   
  if (rchecker1.get_result()) std::cout << "rectangle not empty !\n";
  else {
    std::cout << "rectangle was empty !\n";
    std::cout <<  "this is an error !\n"; correct=false;
  }
   
  check_empty_rectangle rchecker2(r2);
  CGAL::range_search(PS,r2.vertex(0),r2.vertex(1),r2.vertex(2),r2.vertex(3),std::back_inserter(LV),rchecker2,true);
   
  if (rchecker2.get_result()) {
    std::cout << "rectangle not empty !\n";
    std::cout <<  "this is an error !\n"; correct=false;
  }
  else std::cout << "rectangle was empty !\n";
 
  if (correct) return 0;
  
  return 1;
}
Ejemplo n.º 28
0
bool OPvPCapturePoint::Update(uint32 diff)
{
    if (!m_capturePoint)
        return false;

    float radius = (float)m_capturePoint->GetGOInfo()->capturePoint.radius;

    for (uint32 team = 0; team < 2; ++team)
    {
        for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end();)
        {
            ObjectGuid playerGuid = *itr;
            ++itr;

            if (Player* player = ObjectAccessor::FindPlayer(playerGuid))
                if (!m_capturePoint->IsWithinDistInMap(player, radius) || !player->IsOutdoorPvPActive())
                    HandlePlayerLeave(player);
        }
    }

    std::list<Player*> players;
    Trinity::AnyPlayerInObjectRangeCheck checker(m_capturePoint, radius);
    Trinity::PlayerListSearcher<Trinity::AnyPlayerInObjectRangeCheck> searcher(m_capturePoint, players, checker);
    m_capturePoint->VisitNearbyWorldObject(radius, searcher);

    for (std::list<Player*>::iterator itr = players.begin(); itr != players.end(); ++itr)
    {
        Player* const player = *itr;
        if (player->IsOutdoorPvPActive())
        {
            if (m_activePlayers[player->GetTeamId()].insert(player->GetGUID()).second)
                HandlePlayerEnter(*itr);
        }
    }

    // get the difference of numbers
    float fact_diff = ((float)m_activePlayers[0].size() - (float)m_activePlayers[1].size()) * diff / OUTDOORPVP_OBJECTIVE_UPDATE_INTERVAL;
    if (!fact_diff)
        return false;

    //npcbots - count bots as players but 2 times less affect and only if there is a players difference
    uint32 botsCount[2];

    for (uint8 team = 0; team != 2; ++team)
    {
        botsCount[team] = 0;

        for (GuidSet::iterator itr = m_activePlayers[team].begin(); itr != m_activePlayers[team].end(); ++itr)
        {
            if (Player* player = ObjectAccessor::FindPlayer(*itr))
                botsCount[team] += player->GetNpcBotsCount();
        }
    }

    fact_diff += 0.5f * float(botsCount[0] - botsCount[1]) * diff / OUTDOORPVP_OBJECTIVE_UPDATE_INTERVAL;
    //end npcbot

    uint32 Challenger = 0;
    float maxDiff = m_maxSpeed * diff;

    if (fact_diff < 0)
    {
        // horde is in majority, but it's already horde-controlled -> no change
        if (m_State == OBJECTIVESTATE_HORDE && m_value <= -m_maxValue)
            return false;

        if (fact_diff < -maxDiff)
            fact_diff = -maxDiff;

        Challenger = HORDE;
    }
    else
    {
        // ally is in majority, but it's already ally-controlled -> no change
        if (m_State == OBJECTIVESTATE_ALLIANCE && m_value >= m_maxValue)
            return false;

        if (fact_diff > maxDiff)
            fact_diff = maxDiff;

        Challenger = ALLIANCE;
    }

    float oldValue = m_value;
    TeamId oldTeam = m_team;

    m_OldState = m_State;

    m_value += fact_diff;

    if (m_value < -m_minValue) // red
    {
        if (m_value < -m_maxValue)
            m_value = -m_maxValue;
        m_State = OBJECTIVESTATE_HORDE;
        m_team = TEAM_HORDE;
    }
    else if (m_value > m_minValue) // blue
    {
        if (m_value > m_maxValue)
            m_value = m_maxValue;
        m_State = OBJECTIVESTATE_ALLIANCE;
        m_team = TEAM_ALLIANCE;
    }
    else if (oldValue * m_value <= 0) // grey, go through mid point
    {
        // if challenger is ally, then n->a challenge
        if (Challenger == ALLIANCE)
            m_State = OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE;
        // if challenger is horde, then n->h challenge
        else if (Challenger == HORDE)
            m_State = OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE;
        m_team = TEAM_NEUTRAL;
    }
    else // grey, did not go through mid point
    {
        // old phase and current are on the same side, so one team challenges the other
        if (Challenger == ALLIANCE && (m_OldState == OBJECTIVESTATE_HORDE || m_OldState == OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE))
            m_State = OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE;
        else if (Challenger == HORDE && (m_OldState == OBJECTIVESTATE_ALLIANCE || m_OldState == OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE))
            m_State = OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE;
        m_team = TEAM_NEUTRAL;
    }

    if (m_value != oldValue)
        SendChangePhase();

    if (m_OldState != m_State)
    {
        //TC_LOG_ERROR("outdoorpvp", "%u->%u", m_OldState, m_State);
        if (oldTeam != m_team)
            ChangeTeam(oldTeam);
        ChangeState();
        return true;
    }

    return false;
}
Ejemplo n.º 29
0
/// Process queued scripts
void Map::ScriptsProcess()
{
    if (m_scriptSchedule.empty())
        return;

    ///- Process overdue queued scripts
    ScriptScheduleMap::iterator iter = m_scriptSchedule.begin();
    // ok as multimap is a *sorted* associative container
    while (!m_scriptSchedule.empty() && (iter->first <= sWorld->GetGameTime()))
    {
        ScriptAction const& step = iter->second;

        Object* source = NULL;
        if (step.sourceGUID)
        {
            switch (GUID_HIPART(step.sourceGUID))
            {
                case HIGHGUID_ITEM: // as well as HIGHGUID_CONTAINER
                    if (Player* player = HashMapHolder<Player>::Find(step.ownerGUID))
                        source = player->GetItemByGuid(step.sourceGUID);
                    break;
                case HIGHGUID_UNIT:
                case HIGHGUID_VEHICLE:
                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_PET:
                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_PLAYER:
                    source = HashMapHolder<Player>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_TRANSPORT:
                case HIGHGUID_GAMEOBJECT:
                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_CORPSE:
                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
                    break;
                case HIGHGUID_MO_TRANSPORT:
                {
                    GameObject* go = HashMapHolder<GameObject>::Find(step.sourceGUID);
                    source = go ? go->ToTransport() : NULL;
                    break;
                }
                default:
                    TC_LOG_ERROR("scripts", "%s source with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).",
                        step.script->GetDebugInfo().c_str(), step.sourceGUID, GUID_HIPART(step.sourceGUID));
                    break;
            }
        }

        WorldObject* target = NULL;
        if (step.targetGUID)
        {
            switch (GUID_HIPART(step.targetGUID))
            {
                case HIGHGUID_UNIT:
                case HIGHGUID_VEHICLE:
                    target = HashMapHolder<Creature>::Find(step.targetGUID);
                    break;
                case HIGHGUID_PET:
                    target = HashMapHolder<Pet>::Find(step.targetGUID);
                    break;
                case HIGHGUID_PLAYER:                       // empty GUID case also
                    target = HashMapHolder<Player>::Find(step.targetGUID);
                    break;
                case HIGHGUID_TRANSPORT:
                case HIGHGUID_GAMEOBJECT:
                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
                    break;
                case HIGHGUID_CORPSE:
                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
                    break;
                case HIGHGUID_MO_TRANSPORT:
                {
                    GameObject* go = HashMapHolder<GameObject>::Find(step.targetGUID);
                    target = go ? go->ToTransport() : NULL;
                    break;
                }
                default:
                    TC_LOG_ERROR("scripts", "%s target with unsupported high guid (GUID: " UI64FMTD ", high guid: %u).",
                        step.script->GetDebugInfo().c_str(), step.targetGUID, GUID_HIPART(step.targetGUID));
                    break;
            }
        }

        switch (step.script->command)
        {
            case SCRIPT_COMMAND_TALK:
                if (step.script->Talk.ChatType > CHAT_TYPE_WHISPER && step.script->Talk.ChatType != CHAT_MSG_RAID_BOSS_WHISPER)
                {
                    TC_LOG_ERROR("scripts", "%s invalid chat type (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->Talk.ChatType);
                    break;
                }
                if (step.script->Talk.Flags & SF_TALK_USE_PLAYER)
                {
                    if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                    {
                        LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex();
                        std::string text(sObjectMgr->GetTrinityString(step.script->Talk.TextID, loc_idx));

                        switch (step.script->Talk.ChatType)
                        {
                            case CHAT_TYPE_SAY:
                                player->Say(text, LANG_UNIVERSAL);
                                break;
                            case CHAT_TYPE_YELL:
                                player->Yell(text, LANG_UNIVERSAL);
                                break;
                            case CHAT_TYPE_TEXT_EMOTE:
                            case CHAT_TYPE_BOSS_EMOTE:
                                player->TextEmote(text);
                                break;
                            case CHAT_TYPE_WHISPER:
                            case CHAT_MSG_RAID_BOSS_WHISPER:
                            {
                                uint64 targetGUID = target ? target->GetGUID() : 0;
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    TC_LOG_ERROR("scripts", "%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    player->Whisper(text, LANG_UNIVERSAL, targetGUID);
                                break;
                            }
                            default:
                                break;                              // must be already checked at load
                        }
                    }
                }
                else
                {
                    // Source or target must be Creature.
                    if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                    {
                        uint64 targetGUID = target ? target->GetGUID() : 0;
                        switch (step.script->Talk.ChatType)
                        {
                            case CHAT_TYPE_SAY:
                                cSource->MonsterSay(step.script->Talk.TextID, LANG_UNIVERSAL, target);
                                break;
                            case CHAT_TYPE_YELL:
                                cSource->MonsterYell(step.script->Talk.TextID, LANG_UNIVERSAL, target);
                                break;
                            case CHAT_TYPE_TEXT_EMOTE:
                                cSource->MonsterTextEmote(step.script->Talk.TextID, target);
                                break;
                            case CHAT_TYPE_BOSS_EMOTE:
                                cSource->MonsterTextEmote(step.script->Talk.TextID, target, true);
                                break;
                            case CHAT_TYPE_WHISPER:
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    TC_LOG_ERROR("scripts", "%s attempt to whisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    cSource->MonsterWhisper(step.script->Talk.TextID, target->ToPlayer());
                                break;
                            case CHAT_MSG_RAID_BOSS_WHISPER:
                                if (!targetGUID || !IS_PLAYER_GUID(targetGUID))
                                    TC_LOG_ERROR("scripts", "%s attempt to raidbosswhisper to non-player unit, skipping.", step.script->GetDebugInfo().c_str());
                                else
                                    cSource->MonsterWhisper(step.script->Talk.TextID, target->ToPlayer(), true);
                                break;
                            default:
                                break;                              // must be already checked at load
                        }
                    }
                }
                break;

            case SCRIPT_COMMAND_EMOTE:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    if (step.script->Emote.Flags & SF_EMOTE_USE_STATE)
                        cSource->SetUInt32Value(UNIT_FIELD_NPC_EMOTESTATE, step.script->Emote.EmoteID);
                    else
                        cSource->HandleEmoteCommand(step.script->Emote.EmoteID);
                }
                break;

            case SCRIPT_COMMAND_FIELD_SET:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FieldSet.FieldID <= OBJECT_FIELD_ENTRY_ID || step.script->FieldSet.FieldID >= cSource->GetValuesCount())
                        TC_LOG_ERROR("scripts", "%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FieldSet.FieldID,
                            cSource->GetValuesCount(), cSource->GetTypeId(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                        cSource->SetUInt32Value(step.script->FieldSet.FieldID, step.script->FieldSet.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_MOVE_TO:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    Unit* unit = (Unit*)cSource;
                    if (step.script->MoveTo.TravelTime != 0)
                    {
                        float speed = unit->GetDistance(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ) / ((float)step.script->MoveTo.TravelTime * 0.001f);
                        unit->MonsterMoveWithSpeed(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ, speed);
                    }
                    else
                        unit->NearTeleportTo(step.script->MoveTo.DestX, step.script->MoveTo.DestY, step.script->MoveTo.DestZ, unit->GetOrientation());
                }
                break;

            case SCRIPT_COMMAND_FLAG_SET:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY_ID || step.script->FlagToggle.FieldID >= cSource->GetValuesCount())
                        TC_LOG_ERROR("scripts", "%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID,
                            source->GetValuesCount(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                    else
                        cSource->SetFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_FLAG_REMOVE:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    // Validate field number.
                    if (step.script->FlagToggle.FieldID <= OBJECT_FIELD_ENTRY_ID || step.script->FlagToggle.FieldID >= cSource->GetValuesCount())
                        TC_LOG_ERROR("scripts", "%s wrong field %u (max count: %u) in object (TypeId: %u, Entry: %u, GUID: %u) specified, skipping.",
                            step.script->GetDebugInfo().c_str(), step.script->FlagToggle.FieldID,
                            source->GetValuesCount(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                    else
                        cSource->RemoveFlag(step.script->FlagToggle.FieldID, step.script->FlagToggle.FieldValue);
                }
                break;

            case SCRIPT_COMMAND_TELEPORT_TO:
                if (step.script->TeleportTo.Flags & SF_TELEPORT_USE_CREATURE)
                {
                    // Source or target must be Creature.
                    if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script, true))
                        cSource->NearTeleportTo(step.script->TeleportTo.DestX, step.script->TeleportTo.DestY, step.script->TeleportTo.DestZ, step.script->TeleportTo.Orientation);
                }
                else
                {
                    // Source or target must be Player.
                    if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                        player->TeleportTo(step.script->TeleportTo.MapID, step.script->TeleportTo.DestX, step.script->TeleportTo.DestY, step.script->TeleportTo.DestZ, step.script->TeleportTo.Orientation);
                }
                break;

            case SCRIPT_COMMAND_QUEST_EXPLORED:
            {
                if (!source)
                {
                    TC_LOG_ERROR("scripts", "%s source object is NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }
                if (!target)
                {
                    TC_LOG_ERROR("scripts", "%s target object is NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }

                // when script called for item spell casting then target == (unit or GO) and source is player
                WorldObject* worldObject;
                Player* player = target->ToPlayer();
                if (player)
                {
                    if (source->GetTypeId() != TYPEID_UNIT && source->GetTypeId() != TYPEID_GAMEOBJECT && source->GetTypeId() != TYPEID_PLAYER)
                    {
                        TC_LOG_ERROR("scripts", "%s source is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow());
                        break;
                    }
                    worldObject = dynamic_cast<WorldObject*>(source);
                }
                else
                {
                    player = source->ToPlayer();
                    if (player)
                    {
                        if (target->GetTypeId() != TYPEID_UNIT && target->GetTypeId() != TYPEID_GAMEOBJECT && target->GetTypeId() != TYPEID_PLAYER)
                        {
                            TC_LOG_ERROR("scripts", "%s target is not unit, gameobject or player (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                                step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                            break;
                        }
                        worldObject = dynamic_cast<WorldObject*>(target);
                    }
                    else
                    {
                        TC_LOG_ERROR("scripts", "%s neither source nor target is player (source: TypeId: %u, Entry: %u, GUID: %u; target: TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUIDLow(),
                            target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                        break;
                    }
                }

                // quest id and flags checked at script loading
                if ((worldObject->GetTypeId() != TYPEID_UNIT || ((Unit*)worldObject)->IsAlive()) &&
                    (step.script->QuestExplored.Distance == 0 || worldObject->IsWithinDistInMap(player, float(step.script->QuestExplored.Distance))))
                    player->AreaExploredOrEventHappens(step.script->QuestExplored.QuestID);
                else
                    player->FailQuest(step.script->QuestExplored.QuestID);

                break;
            }

            case SCRIPT_COMMAND_KILL_CREDIT:
                // Source or target must be Player.
                if (Player* player = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                {
                    if (step.script->KillCredit.Flags & SF_KILLCREDIT_REWARD_GROUP)
                        player->RewardPlayerAndGroupAtEvent(step.script->KillCredit.CreatureEntry, player);
                    else
                        player->KilledMonsterCredit(step.script->KillCredit.CreatureEntry, 0);
                }
                break;

            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
                if (!step.script->RespawnGameobject.GOGuid)
                {
                    TC_LOG_ERROR("scripts", "%s gameobject guid (datalong) is not specified.", step.script->GetDebugInfo().c_str());
                    break;
                }

                // Source or target must be WorldObject.
                if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script))
                {
                    GameObject* pGO = _FindGameObject(pSummoner, step.script->RespawnGameobject.GOGuid);
                    if (!pGO)
                    {
                        TC_LOG_ERROR("scripts", "%s gameobject was not found (guid: %u).", step.script->GetDebugInfo().c_str(), step.script->RespawnGameobject.GOGuid);
                        break;
                    }

                    if (pGO->GetGoType() == GAMEOBJECT_TYPE_FISHINGNODE ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_DOOR        ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_BUTTON      ||
                        pGO->GetGoType() == GAMEOBJECT_TYPE_TRAP)
                    {
                        TC_LOG_ERROR("scripts", "%s can not be used with gameobject of type %u (guid: %u).",
                            step.script->GetDebugInfo().c_str(), uint32(pGO->GetGoType()), step.script->RespawnGameobject.GOGuid);
                        break;
                    }

                    // Check that GO is not spawned
                    if (!pGO->isSpawned())
                    {
                        int32 nTimeToDespawn = std::max(5, int32(step.script->RespawnGameobject.DespawnDelay));
                        pGO->SetLootState(GO_READY);
                        pGO->SetRespawnTime(nTimeToDespawn);

                        pGO->GetMap()->AddToMap(pGO);
                    }
                }
                break;

            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
            {
                // Source must be WorldObject.
                if (WorldObject* pSummoner = _GetScriptWorldObject(source, true, step.script))
                {
                    if (!step.script->TempSummonCreature.CreatureEntry)
                        TC_LOG_ERROR("scripts", "%s creature entry (datalong) is not specified.", step.script->GetDebugInfo().c_str());
                    else
                    {
                        float x = step.script->TempSummonCreature.PosX;
                        float y = step.script->TempSummonCreature.PosY;
                        float z = step.script->TempSummonCreature.PosZ;
                        float o = step.script->TempSummonCreature.Orientation;

                        if (!pSummoner->SummonCreature(step.script->TempSummonCreature.CreatureEntry, x, y, z, o, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, step.script->TempSummonCreature.DespawnDelay))
                            TC_LOG_ERROR("scripts", "%s creature was not spawned (entry: %u).", step.script->GetDebugInfo().c_str(), step.script->TempSummonCreature.CreatureEntry);
                    }
                }
                break;
            }

            case SCRIPT_COMMAND_OPEN_DOOR:
            case SCRIPT_COMMAND_CLOSE_DOOR:
                _ScriptProcessDoor(source, target, step.script);
                break;

            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
                // Source must be Unit.
                if (Unit* unit = _GetScriptUnit(source, true, step.script))
                {
                    // Target must be GameObject.
                    if (!target)
                    {
                        TC_LOG_ERROR("scripts", "%s target object is NULL.", step.script->GetDebugInfo().c_str());
                        break;
                    }

                    if (target->GetTypeId() != TYPEID_GAMEOBJECT)
                    {
                        TC_LOG_ERROR("scripts", "%s target object is not gameobject (TypeId: %u, Entry: %u, GUID: %u), skipping.",
                            step.script->GetDebugInfo().c_str(), target->GetTypeId(), target->GetEntry(), target->GetGUIDLow());
                        break;
                    }

                    if (GameObject* pGO = target->ToGameObject())
                        pGO->Use(unit);
                }
                break;

            case SCRIPT_COMMAND_REMOVE_AURA:
            {
                // Source (datalong2 != 0) or target (datalong2 == 0) must be Unit.
                bool bReverse = step.script->RemoveAura.Flags & SF_REMOVEAURA_REVERSE;
                if (Unit* unit = _GetScriptUnit(bReverse ? source : target, bReverse, step.script))
                    unit->RemoveAurasDueToSpell(step.script->RemoveAura.SpellID);
                break;
            }

            case SCRIPT_COMMAND_CAST_SPELL:
            {
                /// @todo Allow gameobjects to be targets and casters
                if (!source && !target)
                {
                    TC_LOG_ERROR("scripts", "%s source and target objects are NULL.", step.script->GetDebugInfo().c_str());
                    break;
                }

                Unit* uSource = NULL;
                Unit* uTarget = NULL;
                // source/target cast spell at target/source (script->datalong2: 0: s->t 1: s->s 2: t->t 3: t->s
                switch (step.script->CastSpell.Flags)
                {
                    case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = target ? target->ToUnit() : NULL;
                        break;
                    case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = uSource;
                        break;
                    case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target
                        uSource = target ? target->ToUnit() : NULL;
                        uTarget = uSource;
                        break;
                    case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source
                        uSource = target ? target->ToUnit() : NULL;
                        uTarget = source ? source->ToUnit() : NULL;
                        break;
                    case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry
                        uSource = source ? source->ToUnit() : NULL;
                        uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : NULL;
                        break;
                }

                if (!uSource || !uSource->isType(TYPEMASK_UNIT))
                {
                    TC_LOG_ERROR("scripts", "%s no source unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID);
                    break;
                }

                if (!uTarget || !uTarget->isType(TYPEMASK_UNIT))
                {
                    TC_LOG_ERROR("scripts", "%s no target unit found for spell %u", step.script->GetDebugInfo().c_str(), step.script->CastSpell.SpellID);
                    break;
                }

                bool triggered = (step.script->CastSpell.Flags != 4) ?
                    step.script->CastSpell.CreatureEntry & SF_CASTSPELL_TRIGGERED :
                    step.script->CastSpell.CreatureEntry < 0;
                uSource->CastSpell(uTarget, step.script->CastSpell.SpellID, triggered);
                break;
            }

            case SCRIPT_COMMAND_PLAY_SOUND:
                // Source must be WorldObject.
                if (WorldObject* object = _GetScriptWorldObject(source, true, step.script))
                {
                    // PlaySound.Flags bitmask: 0/1=anyone/target
                    Player* player = NULL;
                    if (step.script->PlaySound.Flags & SF_PLAYSOUND_TARGET_PLAYER)
                    {
                        // Target must be Player.
                        player = _GetScriptPlayer(target, false, step.script);
                        if (!target)
                            break;
                    }

                    // PlaySound.Flags bitmask: 0/2=without/with distance dependent
                    if (step.script->PlaySound.Flags & SF_PLAYSOUND_DISTANCE_SOUND)
                        object->PlayDistanceSound(step.script->PlaySound.SoundID, player);
                    else
                        object->PlayDirectSound(step.script->PlaySound.SoundID, player);
                }
                break;

            case SCRIPT_COMMAND_CREATE_ITEM:
                // Target or source must be Player.
                if (Player* pReceiver = _GetScriptPlayerSourceOrTarget(source, target, step.script))
                {
                    ItemPosCountVec dest;
                    InventoryResult msg = pReceiver->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, step.script->CreateItem.ItemEntry, step.script->CreateItem.Amount);
                    if (msg == EQUIP_ERR_OK)
                    {
                        if (Item* item = pReceiver->StoreNewItem(dest, step.script->CreateItem.ItemEntry, true))
                            pReceiver->SendNewItem(item, step.script->CreateItem.Amount, false, true);
                    }
                    else
                        pReceiver->SendEquipError(msg, NULL, NULL, step.script->CreateItem.ItemEntry);
                }
                break;

            case SCRIPT_COMMAND_DESPAWN_SELF:
                // Target or source must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script, true))
                    cSource->DespawnOrUnsummon(step.script->DespawnSelf.DespawnDelay);
                break;

            case SCRIPT_COMMAND_LOAD_PATH:
                // Source must be Unit.
                if (Unit* unit = _GetScriptUnit(source, true, step.script))
                {
                    if (!sWaypointMgr->GetPath(step.script->LoadPath.PathID))
                        TC_LOG_ERROR("scripts", "%s source object has an invalid path (%u), skipping.", step.script->GetDebugInfo().c_str(), step.script->LoadPath.PathID);
                    else
                        unit->GetMotionMaster()->MovePath(step.script->LoadPath.PathID, step.script->LoadPath.IsRepeatable);
                }
                break;

            case SCRIPT_COMMAND_CALLSCRIPT_TO_UNIT:
            {
                if (!step.script->CallScript.CreatureEntry)
                {
                    TC_LOG_ERROR("scripts", "%s creature entry is not specified, skipping.", step.script->GetDebugInfo().c_str());
                    break;
                }
                if (!step.script->CallScript.ScriptID)
                {
                    TC_LOG_ERROR("scripts", "%s script id is not specified, skipping.", step.script->GetDebugInfo().c_str());
                    break;
                }

                Creature* cTarget = NULL;
                if (source) //using grid searcher
                {
                    WorldObject* wSource = dynamic_cast <WorldObject*> (source);

                    CellCoord p(Trinity::ComputeCellCoord(wSource->GetPositionX(), wSource->GetPositionY()));
                    Cell cell(p);

                    Trinity::CreatureWithDbGUIDCheck target_check(wSource, step.script->CallScript.CreatureEntry);
                    Trinity::CreatureSearcher<Trinity::CreatureWithDbGUIDCheck> checker(wSource, cTarget, target_check);

                    TypeContainerVisitor<Trinity::CreatureSearcher <Trinity::CreatureWithDbGUIDCheck>, GridTypeMapContainer > unit_checker(checker);
                    cell.Visit(p, unit_checker, *wSource->GetMap(), *wSource, wSource->GetGridActivationRange());
                }
                else //check hashmap holders
                {
                    if (CreatureData const* data = sObjectMgr->GetCreatureData(step.script->CallScript.CreatureEntry))
                        cTarget = ObjectAccessor::GetObjectInWorld<Creature>(data->mapid, data->posX, data->posY, MAKE_NEW_GUID(step.script->CallScript.CreatureEntry, data->id, HIGHGUID_UNIT), cTarget);
                }

                if (!cTarget)
                {
                    TC_LOG_ERROR("scripts", "%s target was not found (entry: %u)", step.script->GetDebugInfo().c_str(), step.script->CallScript.CreatureEntry);
                    break;
                }

                //Lets choose our ScriptMap map
                ScriptMapMap* datamap = GetScriptsMapByType(ScriptsType(step.script->CallScript.ScriptType));
                //if no scriptmap present...
                if (!datamap)
                {
                    TC_LOG_ERROR("scripts", "%s unknown scriptmap (%u) specified, skipping.", step.script->GetDebugInfo().c_str(), step.script->CallScript.ScriptType);
                    break;
                }

                // Insert script into schedule but do not start it
                ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, NULL);
                break;
            }

            case SCRIPT_COMMAND_KILL:
                // Source or target must be Creature.
                if (Creature* cSource = _GetScriptCreatureSourceOrTarget(source, target, step.script))
                {
                    if (cSource->isDead())
                        TC_LOG_ERROR("scripts", "%s creature is already dead (Entry: %u, GUID: %u)",
                            step.script->GetDebugInfo().c_str(), cSource->GetEntry(), cSource->GetGUIDLow());
                    else
                    {
                        cSource->setDeathState(JUST_DIED);
                        if (step.script->Kill.RemoveCorpse == 1)
                            cSource->RemoveCorpse();
                    }
                }
                break;

            case SCRIPT_COMMAND_ORIENTATION:
                // Source must be Unit.
                if (Unit* sourceUnit = _GetScriptUnit(source, true, step.script))
                {
                    if (step.script->Orientation.Flags & SF_ORIENTATION_FACE_TARGET)
                    {
                        // Target must be Unit.
                        Unit* targetUnit = _GetScriptUnit(target, false, step.script);
                        if (!targetUnit)
                            break;

                        sourceUnit->SetFacingToObject(targetUnit);
                    }
                    else
                        sourceUnit->SetFacingTo(step.script->Orientation.Orientation);
                }
                break;

            case SCRIPT_COMMAND_EQUIP:
                // Source must be Creature.
                if (Creature* cSource = _GetScriptCreature(source, true, step.script))
                    cSource->LoadEquipment(step.script->Equip.EquipmentID);
                break;

            case SCRIPT_COMMAND_MODEL:
                // Source must be Creature.
                if (Creature* cSource = _GetScriptCreature(source, true, step.script))
                    cSource->SetDisplayId(step.script->Model.ModelID);
                break;

            case SCRIPT_COMMAND_CLOSE_GOSSIP:
                // Source must be Player.
                if (Player* player = _GetScriptPlayer(source, true, step.script))
                    player->PlayerTalkClass->SendCloseGossip();
                break;

            case SCRIPT_COMMAND_PLAYMOVIE:
                // Source must be Player.
                if (Player* player = _GetScriptPlayer(source, true, step.script))
                    player->SendMovieStart(step.script->PlayMovie.MovieID);
                break;

            default:
                TC_LOG_ERROR("scripts", "Unknown script command %s.", step.script->GetDebugInfo().c_str());
                break;
        }

        m_scriptSchedule.erase(iter);
        iter = m_scriptSchedule.begin();
        sScriptMgr->DecreaseScheduledScriptCount();
    }
}
Ejemplo n.º 30
0
int ShaderBinder::setConstant(lua_State* L)
{
	StackChecker checker(L, "ShaderBinder::setConstant", 0);

	Binder binder(L);

	ShaderProgram* shd = static_cast<ShaderProgram*>(binder.getInstance("Shader", 1));

   // virtual void setConstant(int index,ConstantType type,const void *ptr);

	int idx=-1;
	if (lua_isstring(L,2))
	{
		idx=shd->getConstantByName(luaL_checkstring(L,2));
	}
	else
		idx = luaL_checknumber(L, 2);

	if (idx<0)
	{
		lua_pushstring(L,"Shader has no constant of that name/index");
		lua_error(L);
	}
	ShaderProgram::ConstantType type = (ShaderProgram::ConstantType) luaL_checkinteger(L, 3);
	int mult = luaL_checknumber(L, 4);
	int cm=1;
	switch (type)
	{
	case ShaderProgram::CFLOAT2: cm=2; break;
	case ShaderProgram::CFLOAT3: cm=3; break;
	case ShaderProgram::CFLOAT4: cm=4; break;
	case ShaderProgram::CMATRIX: cm=16; break;
	default: cm=1;
	}

	cm*=mult;
	switch (type)
	{
	case ShaderProgram::CINT:
	{
		int *m=(int *) malloc(sizeof(int)*cm);
		if (lua_istable(L,5))
		{
			for (int k=0;k<cm;k++)
			{
				lua_rawgeti(L, 5, k+1);
				m[k]=luaL_checkinteger(L,-1);
				lua_pop(L,1);
			}
		}
		else
		{
			for (int k=0;k<cm;k++)
				m[k]=luaL_checkinteger(L,5+k);
		}
		shd->setConstant(idx,type,mult,m);
		free(m);
		break;
	}
	case ShaderProgram::CFLOAT:
	case ShaderProgram::CFLOAT2:
	case ShaderProgram::CFLOAT3:
	case ShaderProgram::CFLOAT4:
	case ShaderProgram::CMATRIX:
	{
		float *m=(float *) malloc(sizeof(float)*cm);
		if (lua_istable(L,5))
		{
			for (int k=0;k<cm;k++)
			{
				lua_rawgeti(L, 5, k+1);
				m[k]=luaL_checknumber(L,-1);
				lua_pop(L,1);
			}
		}
		else
		{
			for (int k=0;k<cm;k++)
				m[k]=luaL_checknumber(L,5+k);
		}
		shd->setConstant(idx,type,mult,m);
		free(m);
		break;
	}
	case ShaderProgram::CTEXTURE:
		break;
	}

	return 0;
}