Ejemplo n.º 1
0
void GuardedMemory::print_on(outputStream* st) const {
  if (_base_addr == NULL) {
    st->print_cr("GuardedMemory(" PTR_FORMAT ") not associated to any memory", p2i(this));
    return;
  }
  st->print_cr("GuardedMemory(" PTR_FORMAT ") base_addr=" PTR_FORMAT
      " tag=" PTR_FORMAT " user_size=" SIZE_FORMAT " user_data=" PTR_FORMAT,
      p2i(this), p2i(_base_addr), p2i(get_tag()), get_user_size(), p2i(get_user_ptr()));

  Guard* guard = get_head_guard();
  st->print_cr("  Header guard @" PTR_FORMAT " is %s", p2i(guard), (guard->verify() ? "OK" : "BROKEN"));
  guard = get_tail_guard();
  st->print_cr("  Trailer guard @" PTR_FORMAT " is %s", p2i(guard), (guard->verify() ? "OK" : "BROKEN"));

  u_char udata = *get_user_ptr();
  switch (udata) {
  case uninitBlockPad:
    st->print_cr("  User data appears unused");
    break;
  case freeBlockPad:
    st->print_cr("  User data appears to have been freed");
    break;
  default:
    st->print_cr("  User data appears to be in use");
    break;
  }
}
Ejemplo n.º 2
0
void mainloop()
{
	setup();

	for (; is_run(); delay_fps(60))
	{
		cleardevice();

		while (kbhit())
		{
			int key = getch();
			if (key == 'a')
				guard.moveLeft();
			else if (key == 'd')
				guard.moveRight();
		}

		while (mousemsg())
		{
			mouse_msg mouse = getmouse();
			if (mouse.is_move())
			{
				guard.set_position(mouse.x);
			}
		}

		updateStatus();
		updateScene();
	}
}
Ejemplo n.º 3
0
list<vector<Element> > Guard::getAssymetry (Variable *v) {

  EnsureUnicity();
  list<vector<Element> > lcall ;
  list<vector<Element> > lcallres;
  list<Guard *>::iterator it;
  list<Guard *> &l = this->FindPredOnVar (*v);  

  if (! l.empty() ) {
    Guard * g = CanonizePredTree (this,v);
    l = g->FindPredOnVar (*v); 
    for (it = l.begin();it != l.end() ; it++ )
      lcall.push_back( (*it) -> set);
  }
  lcall.push_back(v->PClass()->Elts());

  lcallres = calcSub::uniquePartition (lcall);

  
//  for (it = l.begin();it != l.end() ; it++ )
//    (*it)->RewritePredWithPart (lcallres);
  
//  cerr << endl << "Get Assymetry over variable " << *v << " for guard g=" << *this << endl;
//  calcSub::print(cerr,lcallres);
  return lcallres;

}
Ejemplo n.º 4
0
Archivo: core.c Proyecto: heirecka/lgi
static int
guard_gc (lua_State *L)
{
  Guard *guard = lua_touserdata (L, 1);
  if (guard->data != NULL)
    guard->destroy (guard->data);
  return 0;
}
Ejemplo n.º 5
0
//---------------------------------------------------------------------
// reload the config
size_t Server::loadServers() {
	Guard guard;
	if (guard.isLoaded()) {
		serverInfos.clear();
		guard.mapper->import_putty_sessions(serverInfos);
	}
	return serverInfos.size();
}
Ejemplo n.º 6
0
 bool
 Routing_Slip_Queue::dispatch_one (Guard & guard)
 {
   bool ok = false;
   Routing_Slip_Ptr routing_slip;
   if (this->queue_.dequeue_head (routing_slip) == 0)
   {
     ++this->active_;
     guard.release ();
     routing_slip->at_front_of_persist_queue ();
     guard.acquire ();
   }
   return ok;
 }
Ejemplo n.º 7
0
void ProcessVariable::unsubscribe(Guard &guard)
{
    guard.check(__FILE__, __LINE__, mutex);
    // See comments in stop(): this->id is already 0, state==INIT.
    if (isSubscribed(guard))
    {
#ifdef CHECK_EVID
        void *user = peek_evid_userptr(ev_id);
        LOG_ASSERT(user == this);
#endif
        evid _ev_id = ev_id;
        ev_id = 0;
        GuardRelease release(__FILE__, __LINE__, guard);
        {
            Guard ctx_guard(__FILE__, __LINE__, ctx);
            LOG_ASSERT(ctx.isAttached(ctx_guard));
        }
        try
        {
            ca_clear_subscription(_ev_id);
        }
        catch (std::exception &e)
        {
            LOG_MSG("ProcessVariable::unsubscribe(%s): %s\n",
                    getName().c_str(), e.what());
        }
        catch (...)
        {
            LOG_MSG("ProcessVariable::unsubscribe(%s): Unknown Exception\n",
                    getName().c_str());
        }    
    }    
}
Ejemplo n.º 8
0
void ProcessVariable::getValue(Guard &guard)
{
    guard.check(__FILE__, __LINE__, mutex);
    if (state != CONNECTED)
        return; // Can't get
    ++outstanding_gets;
    chid _id = id;
    GuardRelease release(__FILE__, __LINE__, guard); // Unlock while in CAC.
    {
        int status;
        try
        {
            status = ca_array_get_callback(dbr_type, dbr_count,
                                           _id, value_callback, this);
        }
        catch (std::exception &e)
        {
            LOG_MSG("ProcessVariable::getValue(%s): %s\n",
                    getName().c_str(), e.what());
        }
        catch (...)
        {
            LOG_MSG("ProcessVariable::getValue(%s): Unknown Exception\n",
                    getName().c_str());
        }                          
        if (status != ECA_NORMAL)
        {
            LOG_MSG("%s: ca_array_get_callback failed: %s\n",
                    getName().c_str(), ca_message(status));
            return;
        }
        Guard ctx_guard(__FILE__, __LINE__, ctx);
        ctx.requestFlush(ctx_guard);
    }    
}
Ejemplo n.º 9
0
int main() {
    Player player;
    Witch witch;
    witch.setName("Lucia");
    Guard guard;
    guard.setName("Sam");

    std::cout << "|Player walks around the town and talks with some npcs" << std::endl;
    witch.interact(&player);
    guard.interact(&player);

    std::cout << "|Player goes on a great adventure!" << std::endl;
    std::cout << "|but gets beaten up by some foes..." << std::endl;
    player.setHp(player.getHp() - 5);
    std::cout << "|Back to the town... Let's talk to the witch" << std::endl;
    witch.interact(&player);
}
Ejemplo n.º 10
0
void updateScene()
{
	for (int i = 0; i < WINDOW_WIDTH; i++)
	for (int j = 0; j < WINDOW_HEIGHT; j++)
	if (pixelType[i][j] != 0)
		putpixel(i, j, pixelColor[i][j]);

	guard.draw();
}
Ejemplo n.º 11
0
void GroupInfo::addChannel(Guard &group_guard, ArchiveChannel *channel)
{
    group_guard.check(__FILE__, __LINE__, mutex);
    // Is Channel already in group?
    stdList<ArchiveChannel *>::iterator i;
    for (i=channels.begin(); i!=channels.end(); ++i)
        if (*i == channel)
            return;
    channels.push_back(channel);
}
Ejemplo n.º 12
0
// called by ArchiveChannel    
void GroupInfo::decConnected(Guard &group_guard, ArchiveChannel &pv)
{
    group_guard.check(__FILE__, __LINE__, mutex);
    if (num_connected <= 0)
        throw GenericException(__FILE__, __LINE__,
                               "Group %s connect count runs below 0 "
                               "on decrement from '%s'",
                               getName().c_str(), pv.getName().c_str());
     --num_connected;
}
/*! \internal

    \a n is in the signal index range (see QObjectPrivate::signalIndex()).
*/
void QQmlJavaScriptExpression::GuardCapture::captureProperty(QObject *o, int c, int n)
{
    if (watcher->wasDeleted())
        return;

    Q_ASSERT(expression);
    if (n == -1) {
        if (!errorString) {
            errorString = new QStringList;
            QString preamble = QLatin1String("QQmlExpression: Expression ") +
                    expression->m_vtable->expressionIdentifier(expression) +
                    QLatin1String(" depends on non-NOTIFYable properties:");
            errorString->append(preamble);
        }

        const QMetaObject *metaObj = o->metaObject();
        QMetaProperty metaProp = metaObj->property(c);

        QString error = QLatin1String("    ") +
                QString::fromUtf8(metaObj->className()) +
                QLatin1String("::") +
                QString::fromUtf8(metaProp.name());
        errorString->append(error);
    } else {

        // Try and find a matching guard
        while (!guards.isEmpty() && !guards.first()->isConnected(o, n))
            guards.takeFirst()->Delete();

        Guard *g = 0;
        if (!guards.isEmpty()) {
            g = guards.takeFirst();
            g->cancelNotify();
            Q_ASSERT(g->isConnected(o, n));
        } else {
            g = Guard::New(expression, engine);
            g->connect(o, n, engine);
        }

        expression->activeGuards.prepend(g);
    }
}
template<ACE_SYNCH_DECL> void
Log_Message_Receiver_Impl<ACE_SYNCH_USE>::detach (Log_Message_Receiver_Impl<ACE_SYNCH_USE> *body)
{
  ACE_ASSERT (body != 0);

#if defined (ACE_HAS_THREADS)
#  if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES)
  Guard guard (copy_lock_);
  if (guard.locked () == 0)
    return;
#  else
  // Use the "body"s print lock as copy lock.
  ACE_GUARD (ACE_SYNCH_MUTEX,
             guard,
             global_copy_lock_);
#  endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */
#endif /* ACE_HAS_THREADS */
  if (body->count_-- == 0)
    delete body;
}
Ejemplo n.º 15
0
CURRINT_REPOSITORY_TEMPL_
void RepositoryBase<CURRINT_REPOSITORY_T_>
//
::delete_object (Guard<Obj,wait_m>& obj/*, bool freeMemory*/)
{
  assert (obj);
  const ObjId objId = fromString<ObjId> 
    (obj->universal_id());
//    (obj.operator->()->universal_id());

  delete_object_by_id (objId/*, freeMemory*/);
}
Ejemplo n.º 16
0
void QQmlJavaScriptExpression::GuardCapture::captureProperty(QQmlNotifier *n)
{
    if (expression) {

        // Try and find a matching guard
        while (!guards.isEmpty() && !guards.first()->isConnected(n))
            guards.takeFirst()->Delete();

        Guard *g = 0;
        if (!guards.isEmpty()) {
            g = guards.takeFirst();
            g->cancelNotify();
            Q_ASSERT(g->isConnected(n));
        } else {
            g = Guard::New(expression, engine);
            g->connect(n);
        }

        expression->activeGuards.prepend(g);
    }
}
Log_Message_Receiver_Impl<ACE_SYNCH_USE> *
Log_Message_Receiver_Impl<ACE_SYNCH_USE>::attach (Log_Message_Receiver_Impl<ACE_SYNCH_USE> *body)
{
  ACE_ASSERT (body != 0);

#if defined (ACE_HAS_THREADS)
#  if !defined (ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES)
  Guard guard (copy_lock_);
  if (guard.locked () == 0)
    return 0;
#  else
  // Use the "body"s print lock as copy lock.
  ACE_GUARD_RETURN (ACE_SYNCH_MUTEX,
                    guard,
                    global_copy_lock_,
                    0);
#  endif /* ACE_LACKS_STATIC_DATA_MEMBER_TEMPLATES */
#endif /* ACE_HAS_THREADS */
  ++body->count_;
  return body;
}
Ejemplo n.º 18
0
// called by ArchiveChannel
void GroupInfo::incConnected(Guard &group_guard, ArchiveChannel &pv)
{
    group_guard.check(__FILE__, __LINE__, mutex);
    ++num_connected;
    if (num_connected > channels.size())
        throw GenericException(__FILE__, __LINE__,
                               "Group %s connect count is %zu out of %zu "
                               "on increment from '%s'",
                               getName().c_str(),
                               (size_t)num_connected,
                               (size_t)channels.size(),
                               pv.getName().c_str());    
}
Ejemplo n.º 19
0
// called by ArchiveChannel
void GroupInfo::disable(Guard &group_guard,
                        ArchiveChannel *cause, const epicsTime &when)
{
    group_guard.check(__FILE__, __LINE__, mutex);
    LOG_MSG("'%s' disables group '%s'\n",
            cause->getName().c_str(), getName().c_str());
    ++disable_count;
    if (disable_count != 1) // Was already disabled?
        return;
    // Disable all channels in this group
    stdList<ArchiveChannel *>::iterator ci;
    for (ci = channels.begin(); ci != channels.end(); ++ci)
    {
        ArchiveChannel *c = *ci;
        Guard guard(__FILE__, __LINE__, *c);
        c->disable(guard, when);
    }
}
Ejemplo n.º 20
0
void ProcessVariable::stop(Guard &guard)
{
#   ifdef DEBUG_PV
    printf("stop ProcessVariable(%s)\n", getName().c_str());
#   endif
    guard.check(__FILE__, __LINE__, mutex);
    LOG_ASSERT(isRunning(guard));
    // We'll unlock in unsubscribe(), and then for the ca_clear_channel.
    // At those times, an ongoing connection could invoke the connection_handler,
    // control_callback or subscribe.
    // Setting all indicators back to INIT state will cause those to bail.
    chid _id = id;
    id = 0;
    bool was_connected = (state == CONNECTED);
    state = INIT;
    outstanding_gets = 0;
    unsubscribe(guard);
    // Unlock around CA lib. calls to prevent deadlocks.
    {
        GuardRelease release(__FILE__, __LINE__, guard);
        {   // If we were subscribed, this was already checked in unsubscribe()...
            Guard ctx_guard(__FILE__, __LINE__, ctx);
            LOG_ASSERT(ctx.isAttached(ctx_guard));
        }
        try
        {
            ca_clear_channel(_id);
        }
        catch (std::exception &e)
        {
            LOG_MSG("ProcessVariable::stop(%s): %s\n",
                    getName().c_str(), e.what());
        }
        catch (...)
        {
            LOG_MSG("ProcessVariable::stop(%s): Unknown Exception\n",
                    getName().c_str());
        }
        // If there are listeners, tell them that we are disconnected.
        if (was_connected)
            firePvDisconnected();
    }
}
Ejemplo n.º 21
0
void ProcessVariable::start(Guard &guard)
{
    guard.check(__FILE__, __LINE__, mutex);
#   ifdef DEBUG_PV
    printf("start ProcessVariable(%s)\n", getName().c_str());
#   endif
    LOG_ASSERT(! isRunning(guard));
    LOG_ASSERT(state == INIT);
    state = DISCONNECTED;
    // Unlock around CA lib. calls to prevent deadlocks in callbacks.
    int status;
    chid _id;
    {
        GuardRelease release(__FILE__, __LINE__, guard);
        {
            try
            {
       	        status = ca_create_channel(getName().c_str(),
                                           connection_handler,
                                           this, CA_PRIORITY_ARCHIVE, &_id);
            }
            catch (std::exception &e)
            {
                LOG_MSG("ProcessVariable::start(%s): %s\n",
                        getName().c_str(), e.what());
            }
            catch (...)
            {
                LOG_MSG("ProcessVariable::start(%s): Unknown Exception\n",
                        getName().c_str());
            }                          
            Guard ctx_guard(__FILE__, __LINE__, ctx);
            ctx.requestFlush(ctx_guard);
        }
    }
    id = _id;
    if (status != ECA_NORMAL)
        LOG_MSG("'%s': ca_create_channel failed, status %s\n",
                getName().c_str(), ca_message(status));
}
Ejemplo n.º 22
0
// called by ArchiveChannel
void GroupInfo::enable(Guard &group_guard,
                       ArchiveChannel *cause, const epicsTime &when)
{
    group_guard.check(__FILE__, __LINE__, mutex);
    LOG_MSG("'%s' enables group '%s'\n",
            cause->getName().c_str(), getName().c_str());
    if (disable_count <= 0)
    {
        LOG_MSG("Group %s is not disabled, ERROR!\n", getName().c_str());
        return;
    }
    --disable_count;
    if (disable_count > 0) // Still disabled?
        return;
    // Enable all channels in this group
    stdList<ArchiveChannel *>::iterator ci;
    for (ci = channels.begin(); ci != channels.end(); ++ci)
    {
        ArchiveChannel *c = *ci;
        Guard guard(__FILE__, __LINE__, *c);
        c->enable(guard, when);
    }
}
Ejemplo n.º 23
0
/*****************************************convol_fun*********************************************************/
BaseGDL* convol_fun( EnvT* e)
{
    SizeT nParam=e->NParam( 2);

    /************************************Checking_parameters************************************************/

    BaseGDL* p0 = e->GetNumericParDefined( 0);
    if( p0->Rank() == 0)
        e->Throw( "Expression must be an array in this context: "+
                  e->GetParString(0));

    BaseGDL* p1 = e->GetNumericParDefined( 1);
    if( p1->Rank() == 0)
        e->Throw( "Expression must be an array in this context: "+
                  e->GetParString(1));

    if( p0->N_Elements() < p1->N_Elements())
        e->Throw( "Incompatible dimensions for Array and Kernel.");

    // rank 1 for kernel works always
    if( p1->Rank() != 1)
    {
        SizeT rank = p0->Rank();
        if( rank != p1->Rank())
            e->Throw( "Incompatible dimensions for Array and Kernel.");

        for( SizeT r=0; r<rank; ++r)
            if( p0->Dim( r) < p1->Dim( r))
                e->Throw( "Incompatible dimensions for Array and Kernel.");
    }


    /***************************************Preparing_matrices*************************************************/
    // convert kernel to array type
    Guard<BaseGDL> p1Guard;
    if( p0->Type() == GDL_BYTE)
    {
        if( p1->Type() != GDL_INT)
        {
            p1 = p1->Convert2( GDL_INT, BaseGDL::COPY);
            p1Guard.Reset( p1);
        }
    }
    else if( p0->Type() != p1->Type())
    {
        p1 = p1->Convert2( p0->Type(), BaseGDL::COPY);
        p1Guard.Reset( p1);
    }

    BaseGDL* scale;
    Guard<BaseGDL> scaleGuard;
    if( nParam > 2)
    {
        scale = e->GetParDefined( 2);
        if( scale->Rank() > 0)
            e->Throw( "Expression must be a scalar in this context: "+
                      e->GetParString(2));

        // p1 here handles GDL_BYTE case also
        if( p1->Type() != scale->Type())
        {
            scale = scale->Convert2( p1->Type(),BaseGDL::COPY);
            scaleGuard.Reset( scale);
        }
    }
    else
    {
        scale = p1->New( dimension(), BaseGDL::ZERO);
    }
    /********************************************Arguments_treatement***********************************/
    bool center = true;
    static int centerIx = e->KeywordIx( "CENTER");
    if( e->KeywordPresent( centerIx))
    {
        DLong c;
        e->AssureLongScalarKW( centerIx, c);
        center = (c != 0);
    }

    // overrides EDGE_TRUNCATE
    static int edge_wrapIx = e->KeywordIx( "EDGE_WRAP");
    bool edge_wrap = e->KeywordSet( edge_wrapIx);
    static int edge_truncateIx = e->KeywordIx( "EDGE_TRUNCATE");
    bool edge_truncate = e->KeywordSet( edge_truncateIx);
    static int edge_zeroIx = e->KeywordIx( "EDGE_ZERO");
    bool edge_zero = e->KeywordSet( edge_zeroIx);
    int edgeMode = 0;
    if( edge_wrap)
        edgeMode = 1;
    else if( edge_truncate)
        edgeMode = 2;
    else if( edge_zero)
        edgeMode = 3;

    // p0, p1 and scale have same type
    // p1 has rank of 1 or same rank as p0 with each dimension smaller than p0
    // scale is a scalar

    /***********************************Parameter_BIAS**************************************/
    static int biasIx = e->KeywordIx("BIAS");
    bool statusBias = e->KeywordPresent( biasIx );
    //    DLong bias=0;
    BaseGDL* bias;
    if(statusBias)
    {
        bias=e->GetKW( biasIx);

        if( p0->Type() != bias->Type())
        {
            bias = bias->Convert2( p0->Type(), BaseGDL::COPY);
        }
    }
    else bias=p1->New( 1,BaseGDL::ZERO);

    /***********************************Parameter_Normalize**********************************/

    static int normalIx = e->KeywordIx( "NORMALIZE");
    bool normalize = e->KeywordPresent( normalIx);

    /***********************************Parameter NAN****************************************/

    static int nanIx = e->KeywordIx( "NAN");
    bool doNan = e->KeywordPresent( nanIx);

    /***********************************Parameter MISSING************************************/
    static int missingIx = e->KeywordIx("MISSING");
    bool doMissing = e->KeywordPresent( missingIx );
    BaseGDL* missing;
    if (p0->Type() != GDL_BYTE) {
        if (doMissing) {
            missing = e->GetKW(missingIx);
            if (p0->Type() != missing->Type()) {
                missing = missing->Convert2(p0->Type(), BaseGDL::COPY);
            }
        } else missing = p1->New(1, BaseGDL::ZERO);
    } else {
        if (doMissing) {
            missing = e->GetKW(missingIx);
        } else missing = p1->New(1, BaseGDL::ZERO);
        missing = missing->Convert2(GDL_LONG, BaseGDL::COPY);
    }
    /***********************************Parameter INVALID************************************/
    static int invalidIx = e->KeywordIx("INVALID");
    bool doInvalid = e->KeywordPresent( invalidIx );
    BaseGDL* invalid;
    if (p0->Type() != GDL_BYTE) {
        if (doInvalid) {
            invalid = e->GetKW(invalidIx);
            if (p0->Type() != invalid->Type()) {
                invalid = invalid->Convert2(p0->Type(), BaseGDL::COPY);
            }
        } else invalid = p1->New(1, BaseGDL::ZERO);
    } else {
        if (doInvalid) {
            invalid = e->GetKW(invalidIx);
        } else invalid = p1->New(1, BaseGDL::ZERO);
        invalid = invalid->Convert2(GDL_LONG, BaseGDL::COPY);
    }
    if (!doNan && !doInvalid) doMissing=false;
    if (!doMissing && (p0->Type()==GDL_FLOAT ||p0->Type()==GDL_COMPLEX))
        missing = SysVar::Values()->GetTag(SysVar::Values()->Desc()->TagIndex("F_NAN"), 0);
    if (!doMissing && (p0->Type()==GDL_DOUBLE ||p0->Type()==GDL_COMPLEXDBL))
        missing = SysVar::Values()->GetTag(SysVar::Values()->Desc()->TagIndex("D_NAN"), 0);

    return p0->Convol( p1, scale, bias, center, normalize, edgeMode, doNan, missing, doMissing, invalid,doInvalid);
} //end of convol_fun
Ejemplo n.º 24
0
void AttackState::Update(double dt)
{
	FSMState::Update(dt);

	Guard* g = dynamic_cast<Guard*>(m_FSMOwner);

	// Check if the NPC is legit
	if (!g)
	{
		return;
	}

	if (g->GetAttacked() && g->GetKnockedOut())
	{
		if (g->GetLastTarget())
		{
			g->GetLastTarget()->SetTargetted(false); // Tell spy that guard no longer has sight on it
		}
		else if (g->GetTarget())
		{
			g->GetTarget()->SetTargetted(false); // Tell spy that guard no longer has sight on it
		}
		g->SetMoveSpeed(Guard::S_GUARD_PATROL_SPEED);
		changeState(new AttackedState());
		return;
	}

	if (!g->GetTarget()) // Target missing
	{
		m_missingTimer += dt;
		if (g->GetLastTarget())
		{
			//g->GetLastTarget()->SetTargetted(false); // Tell spy that guard no longer has sight on it
		}
		if (!m_reached)
		{
			if (m_recordPoint)
			{
				g->AddToFallback(g->GetTransform().Translation);
				m_recordPoint = false;
			}
			moveToLastSeen(dt);
		}
		else
		{
			g->SetMoveSpeed(Guard::S_GUARD_PATROL_SPEED);
			g->GetView()->SetScale(Vector2(g->GetDefaultViewRadius() * 2.f, g->GetDefaultViewRadius() * 2.f));
			g->UpdateViewPosition();
			changeState(new PatrolState());
			return;
		}
	}
	else // Target still in sight
	{
		m_missingTimer = 0.f;
		m_recordPoint = true;
		g->GetTarget()->SetTargetted(true); // Tell spy that guard spotted it
		m_attackTimer += dt;
		if (m_attackTimer >= S_TIME_TILL_ATTACK)
		{
			int killChance = Math::RandIntMinMax(1, 100);
			if (killChance < 70) // % chance to kill spy
			{
				g->GetTarget()->Kill();
				g->GetTarget()->SetTargetted(false);
				g->SetMoveSpeed(Guard::S_GUARD_PATROL_SPEED);
				g->GetView()->SetScale(Vector2(g->GetDefaultViewRadius() * 2.f, g->GetDefaultViewRadius() * 2.f));
				g->UpdateViewPosition();

				changeState(new PatrolState());
				return;
			}
			m_attackTimer = 0.f;
		}
	}

	if (m_missingTimer >= S_MISSING_TIMER) // Can't find target for a period of time
	{
		if (g->GetLastTarget())
		{
			g->GetLastTarget()->SetTargetted(false); // Tell spy that guard no longer has sight on it
		}
		changeState(new PatrolState());
		g->GetView()->SetScale(Vector2(g->GetDefaultViewRadius() * 2.f, g->GetDefaultViewRadius() * 2.f));
		g->UpdateViewPosition();
		return;
	}
}
Ejemplo n.º 25
0
void AttackState::moveToLastSeen(double dt)
{
	Guard* g = dynamic_cast<Guard*>(m_FSMOwner);

	// Check if the NPC is legit
	if (!g)
	{
		return;
	}

	g->SetLookDir((g->GetLastSeen() - g->GetTransform().Translation).Normalized());

	float distFromLastSeen = (g->GetTransform().Translation - g->GetLastSeen()).LengthSquared();
	float movement = g->GetMoveSpeed() * dt;
	float movementSquared = movement * movement;

	if (movementSquared > distFromLastSeen) // Walk past waypoint
	{
		g->SetPos(g->GetLastSeen());
		g->UpdateViewPosition();
		m_reached = true;
	}
	else
	{
		g->SetPos(g->GetTransform().Translation + (g->GetLookDir() * movement));
		g->UpdateViewPosition();
	}
}
Ejemplo n.º 26
0
ProcessVariable::State ProcessVariable::getState(Guard &guard) const
{
    guard.check(__FILE__, __LINE__, mutex);
    return state;
}
Ejemplo n.º 27
0
	void GameState::init()
	{
		if (m_xLevel != nullptr)
		{
			delete m_xLevel;
			m_xLevel = nullptr;
		}

		m_xLevel = new Level("../resources/level/", m_xSpriteManager, m_xGameObjectManager);

		m_xLevel->loadColorCodes("colorcodes.txt");
		m_xLevel->loadFloorColorCodes("floorcolorcodes.txt");
		m_xLevel->getRotationsPaths("rotate.txt");
		m_xLevel->create("level.png", "patrol.txt");
		m_xLevel->createFloor("FirstFloor.png");

		sf::Clock *xTimer = new sf::Clock;
		m_cClock = sf::Clock();
		//m_xPlayer = m_xGameObjectManager->createPlayer(m_xSpriteManager->loadSprite("spy.txt"), sf::Vector2f(64 * 48, 64 * 8), m_xEngine->m_window, 1, m_xLevel, xTimer);
		m_xPlayer = m_xGameObjectManager->createPlayer(new Animator(m_xSpriteManager, "../resources/Spritesheets/"), m_xSpriteManager->loadAnimatedSprite("Spy_walk.txt"), sf::Vector2f(64 * 48, 64 * 8), m_xEngine->m_window, 1, m_xLevel, xTimer, m_xStateManager);
		m_vGameObjects[MAIN].push_back(m_xPlayer);

		m_vGameObjects[MAIN].insert(m_vGameObjects[MAIN].end(), m_xLevel->getObjects()->begin(), m_xLevel->getObjects()->end());

		m_xView = new sf::View();
		//kommentar
		m_xView->reset(sf::FloatRect(0, 0, 1920 * 1, 1080 * 1));

		/*m_xPlayer->m_xWeapon = new Gun(true, 2, 1.f, 1.f, &m_vGameObjects[MAIN], m_xGameObjectManager, m_xSpriteManager);
		m_xPlayer->m_xWeapon->setAttachedObject(m_xPlayer);*/

		/*m_xPlayer->m_xWeapon = new Baton(true, 10, 1.f, 1.f, &m_vGameObjects[MAIN], m_xLevel, m_xGameObjectManager, m_xSpriteManager);
		m_xPlayer->m_xWeapon->setAttachedObject(m_xPlayer);*/

		m_xPlayer->m_xWeapon = new Garrote(1.f, 2.5f, &m_vGameObjects[MAIN]);
		m_xPlayer->m_xWeapon->setAttachedObject(m_xPlayer);

		SoundManager soundmanager("../resources/Music/");
		m_sIngame = soundmanager.getMusic("Ingame.ogg");
		m_sIngame->setVolume(40.0f);
		m_sIngame->setLoop(true);
		m_sIngame->play();

		hud = new HUD(m_xView, m_xSpriteManager, m_xPlayer);

		PathFind *path = new PathFind(m_xLevel);

		for (auto obj : m_vGameObjects[MAIN])
		{
			if (obj->getType() == PATROLLINGGUARD || obj->getType() == STATIONARYGUARD)
			{
				Guard *guard = static_cast<Guard*>(obj);

				guard->attachAi(new AIManager(guard, m_xLevel, m_xPlayer));

				guard->attachAnimator(new Animator(m_xSpriteManager, "../resources/Spritesheets/"));

				if (guard->getIsRotating())
					guard->m_xAIManager->forceCurrentState(AIManager::STATIONARY);
				else if (guard->getIsPatrolling())
					guard->m_xAIManager->forceCurrentState(AIManager::PATROLLING);
			}
		}

		m_xPlayer->setStateObjects(&m_vGameObjects[MAIN]);
	}
Ejemplo n.º 28
0
BaseGDL* _GDL_OBJECT_OverloadBracketsRightSide( EnvUDT* e)
{
//   // debug/check
//   std::cout << "_GDL_OBJECT_OverloadBracketsRightSide called" << std::endl;

  SizeT nParam = e->NParam(); // number of parameters actually given
//   int envSize = e->EnvSize(); // number of parameters + keywords 'e' (pro) has defined
  if( nParam < 3) // consider implicit SELF
    ThrowFromInternalUDSub( e, "At least 2 parameters are needed: ISRANGE, SUB1 [, ...].");

  // default behavior: Exact like scalar indexing
  BaseGDL* isRange = e->GetKW(1);
  if( isRange == NULL)
    ThrowFromInternalUDSub( e, "Parameter 1 (ISRANGE) is undefined.");
  if( isRange->Rank() == 0)
    ThrowFromInternalUDSub( e, "Parameter 1 (ISRANGE) must be an array in this context: " + e->Caller()->GetString(e->GetKW(1)));
  SizeT nIsRange = isRange->N_Elements();
  if( nIsRange > (nParam - 2)) //- SELF and ISRANGE
    ThrowFromInternalUDSub( e, "Parameter 1 (ISRANGE) must have "+i2s(nParam-2)+" elements.");
  Guard<DLongGDL> isRangeLongGuard;
  DLongGDL* isRangeLong;
  if( isRange->Type() == GDL_LONG)
    isRangeLong = static_cast<DLongGDL*>( isRange);
  else
  {
    try{
      isRangeLong = static_cast<DLongGDL*>( isRange->Convert2( GDL_LONG, BaseGDL::COPY));
    }
    catch( GDLException& ex)
    {
      ThrowFromInternalUDSub( e, ex.ANTLRException::getMessage());
    }
    isRangeLongGuard.Reset( isRangeLong);
  }

  ArrayIndexVectorT ixList;
//   IxExprListT exprList;
  try {
    for( int p=0; p<nIsRange; ++p)
    {
      BaseGDL* parX = e->GetKW( p + 2); // implicit SELF, ISRANGE, par1..par8
      if( parX == NULL)
	ThrowFromInternalUDSub( e, "Parameter is undefined: "  + e->Caller()->GetString(e->GetKW( p + 2)));

      DLong isRangeX = (*isRangeLong)[p];
      if( isRangeX != 0 && isRangeX != 1)
      {
	ThrowFromInternalUDSub( e, "Value of parameter 1 (ISRANGE["+i2s(p)+"]) is out of allowed range.");
      }
      if( isRangeX == 1)
      {
	if( parX->N_Elements() != 3)
	{
	  ThrowFromInternalUDSub( e, "Range vector must have 3 elements: " + e->Caller()->GetString(e->GetKW( p + 2)));
	}
	DLongGDL* parXLong;
	Guard<DLongGDL> parXLongGuard;
	if( parX->Type() != GDL_LONG)
	{
	  try{
	    parXLong = static_cast<DLongGDL*>( parX->Convert2( GDL_LONG, BaseGDL::COPY));
	    parXLongGuard.Reset( parXLong);
	  }
	  catch( GDLException& ex)
	  {
	    ThrowFromInternalUDSub( e, ex.ANTLRException::getMessage());
	  }
	}
	else
	{
	  parXLong = static_cast<DLongGDL*>( parX);
	}
	// negative end ix is fine -> CArrayIndexRangeS can handle [b:*:s] ([b,-1,s])
	ixList.push_back(new CArrayIndexRangeS( (*parXLong)[0], (*parXLong)[1], (*parXLong)[2]));
      }
      else // non-range
      {
	// ATTENTION: These two grab c1 (all others don't)
	// a bit unclean, but for maximum efficiency
	if( parX->Rank() == 0)
	  ixList.push_back( new CArrayIndexScalar( parX->Dup()));
	else
	  ixList.push_back( new CArrayIndexIndexed( parX->Dup()));
      }
    } // for
  }
  catch( GDLException& ex)
  {
    ixList.Destruct(); // ixList is not valid afterwards, but as we throw this is ok
    throw ex;
  }
  
  ArrayIndexListT* aL;
  MakeArrayIndex( &ixList, &aL, NULL); // important to get the non-NoAssoc ArrayIndexListT
  // because only they clean up ixList on destruction
  Guard< ArrayIndexListT> aLGuard( aL);

  IxExprListT ixL;
  return aL->Index( e->GetKW( 0), ixL); // index SELF
}
Ejemplo n.º 29
0
void ProcessVariable::subscribe(Guard &guard)
{
    guard.check(__FILE__, __LINE__, mutex);
    if (dbr_type == 0)
        throw GenericException(__FILE__, __LINE__,
                               "Cannot subscribe to %s, never connected",
                               getName().c_str());
    // Prevent multiple subscriptions
    if (isSubscribed(guard))
        return;
    // While we were unlocked, a disconnect or stop() could have happend,
    // in which case we need to bail out.
    if (id == 0 || state != CONNECTED)
    {
        LOG_MSG("'%s': Skipped subscription, state %s, id 0x%lu.\n",
                getName().c_str(),  getStateStr(guard), (unsigned long) id);
        return;
    }
    chid     _id    = id;
    evid     _ev_id = 0;
    DbrType  _type  = dbr_type;
    DbrCount _count = dbr_count;
    {   // Release around CA call??
        // --  GuardRelease release(__FILE__, __LINE__, guard);
        // Right now, could a stop() and ca_clear_channel(id) happen,
        // so that ca_create_subscription() uses an invalid id?
        //
        // Task A, CAC client:
        // control_callback, pvConnected, subscribe
        //
        // Task B, Engine or HTTPD:
        // stop, clear_channel
        //
        // LockTest.cpp indicates that the clear_channel() will wait
        // for the CAC library to leabe the control_callback.
        // So even though we unlock the ProcessVariable and somebody
        // could invoke stop() and set id=0, we have the copied _id,
        // and the ca_clear_channel(id) won't happen until we leave
        // the control_callback.
        // This of course only handles the use case of the engine
        // where subscribe is invoked from control_callback & pvConnected.
        // to be on the safe side, we keep the guard and prevent a stop(),
        // until we find a deadlock that forces us to reconsider....
        {
            int status;
            try
            {
                status = ca_create_subscription(_type, _count, _id,
                                                DBE_LOG | DBE_ALARM,
                                                value_callback, this, &_ev_id);
            }
            catch (std::exception &e)
            {
                LOG_MSG("ProcessVariable::subscribe(%s): %s\n",
                        getName().c_str(), e.what());
            }
            catch (...)
            {
                LOG_MSG("ProcessVariable::subscribe(%s): Unknown Exception\n",
                        getName().c_str());
            } 
            if (status != ECA_NORMAL)
            {
                LOG_MSG("%s: ca_create_subscription failed: %s\n",
                        getName().c_str(), ca_message(status));
                return;
            }
            Guard ctx_guard(__FILE__, __LINE__, ctx);
            ctx.requestFlush(ctx_guard);
        }
    }
    ev_id = _ev_id;
    LOG_ASSERT(ev_id != 0);
#ifdef CHECK_EVID
    void *user = peek_evid_userptr(ev_id);
    LOG_ASSERT(user == this);
#endif
}
Ejemplo n.º 30
0
bool ProcessVariable::isRunning(Guard &guard)
{
    guard.check(__FILE__, __LINE__, mutex);
    return id != 0;
}