예제 #1
0
파일: Network.cpp 프로젝트: snikk/Junk
void RemoteEventSocket::VHandleInput() {
    NetSocket::VHandleInput();

    while (!m_InList.empty()) {
        std::shared_ptr<IPacket> packet = *m_InList.begin();
        m_InList.pop_front();
        const char* buf = packet->VGetData();
        int size = static_cast<int>(packet->VGetSize());

        std::istrstream in(buf + sizeof(u_long), (size - sizeof(u_long)));

        int type;
        in >> type;

        switch (type) {
            case NetMsg_Event:
                CreateEvent(in);
                break;

            case NetMsg_PlayerLoginOk:
            {
                int serverSockId, actorId;
                in >> serverSockId;
                in >> actorId;
                std::shared_ptr<EvtData_Network_Player_Actor_Assignment> pEvent(GCC_NEW EvtData_Network_Player_Actor_Assignment(actorId, serverSockId));
                IEventManager::Get()->VQueueEvent(pEvent);
                break;
            }
            default:
            GCC_ERROR("Unknown message type.\n");
        }
    }
}
예제 #2
0
//---------------------------------------------------------------------------------------------------------------------
// EventManager::VQueueEvent
//---------------------------------------------------------------------------------------------------------------------
bool EventManager::VQueueEvent(const IEventDataPtr& pEvent)
{
	GCC_ASSERT(m_activeQueue >= 0);
	GCC_ASSERT(m_activeQueue < EVENTMANAGER_NUM_QUEUES);

    // make sure the event is valid
    if (!pEvent)
    {
        GCC_ERROR("Invalid event in VQueueEvent()");
        return false;
    }

    GCC_LOG("Events", "Attempting to queue event: " + std::string(pEvent->GetName()));

	auto findIt = m_eventListeners.find(pEvent->VGetEventType());
    if (findIt != m_eventListeners.end())
    {
        m_queues[m_activeQueue].push_back(pEvent);
        GCC_LOG("Events", "Successfully queued event: " + std::string(pEvent->GetName()));
        return true;
    }
    else
    {
        GCC_LOG("Events", "Skipping event since there are no delegates registered to receive it: " + std::string(pEvent->GetName()));
        return false;
    }
}
예제 #3
0
void TeapotWarsLogic::NetworkPlayerActorAssignmentDelegate(IEventDataPtr pEventData)
{
	if (!m_bProxy)
		return;

    // we're a remote client getting an actor assignment.
    // the server assigned us a playerId when we first attached (the server's socketId, actually)
    shared_ptr<EvtData_Network_Player_Actor_Assignment> pCastEventData = static_pointer_cast<EvtData_Network_Player_Actor_Assignment>(pEventData);

	if (pCastEventData->GetActorId()==INVALID_ACTOR_ID)
	{
		m_remotePlayerId = pCastEventData->GetSocketId();
		return;
	}

	for (auto it = m_gameViews.begin(); it != m_gameViews.end(); ++it)
    {
        shared_ptr<IGameView> pView = *it;
        if (pView->VGetType() == GameView_Human)
        {
            shared_ptr<TeapotWarsHumanView> pHumanView = static_pointer_cast<TeapotWarsHumanView, IGameView>(pView);
			if (m_remotePlayerId == pCastEventData->GetSocketId())
			{
				pHumanView->VSetControlledActor(pCastEventData->GetActorId());
			}
			return;
		}
	}

	GCC_ERROR("Could not find HumanView to attach actor to!");
}
예제 #4
0
void RemoteNetworkView::ForwardEvent(IEventDataPtr pEventData) {
	std::string httpinmsg;
	if (!pEventData) {
		GCC_ERROR("Event Invalid");
		return;
	}
	int socketId = pEventData->VGetSocketId();

	std::ostrstream out;

	pEventData->VSerialize(out);
	out << std::ends;

	IPacket *packetBack = NULL;
	if (!strncmp("HTTP", &out.rdbuf()->str()[0], 4)) {
		packetBack = GCC_NEW HTTPPacket(out.rdbuf()->str());
	}
	else {
		//TODO create binary packet
	}
	std::shared_ptr<IPacket> ipBack(packetBack);
	printf("RemoteNetworkView Forward Event socket:%d %s\n", socketId, pEventData->GetName());
	g_pSocketManager->Send(socketId, ipBack);

	if (!strncmp("HTTP", &out.rdbuf()->str()[0], 4)) {
		IEventDataPtr pCloseSocketHttpEvent(CREATE_EVENT(EventData_CloseSocketHTTP::sk_EventType));
		char* id = new char[100];
		sprintf_s(id, 100, "%d", socketId);
		httpinmsg.append(id);
		std::istrstream in(httpinmsg.c_str(), httpinmsg.size());
		pCloseSocketHttpEvent->VDeserialize(in);
		IEventManager::Get()->VQueueEvent(pCloseSocketHttpEvent);
	}
}
예제 #5
0
파일: Network.cpp 프로젝트: snikk/Junk
bool BaseSocketManager::Init() {
    if (WSAStartup(0x0202, &m_WsaData) == 0) {
        return true;
    } else {
        GCC_ERROR("WSAStartup failure!");
        return false;
    }
}
예제 #6
0
void InternalScriptExports::ApplyTorque(LuaPlus::LuaObject axisLua, float force, int actorId)
{
    if (axisLua.IsTable())
    {
        Vec3 axis(axisLua["x"].GetFloat(), axisLua["y"].GetFloat(), axisLua["z"].GetFloat());
		g_pApp->m_pGame->VGetGamePhysics()->VApplyTorque(axis, force, actorId);
		return;
    }
    GCC_ERROR("Invalid object passed to ApplyTorque(); type = " + std::string(axisLua.TypeName()));
}
예제 #7
0
float InternalScriptExports::GetYRotationFromVector(LuaPlus::LuaObject vec3)
{
    if (vec3.IsTable())
    {
        Vec3 lookAt(vec3["x"].GetFloat(), vec3["y"].GetFloat(), vec3["z"].GetFloat());
        return ::GetYRotationFromVector(lookAt);
    }

    GCC_ERROR("Invalid object passed to GetYRotationFromVector(); type = " + std::string(vec3.TypeName()));
    return 0;
}
예제 #8
0
파일: Network.cpp 프로젝트: snikk/Junk
void RemoteEventSocket::CreateEvent(std::istrstream& in) {
    EventType eventType;
    in >> eventType;
    IEventDataPtr pEvent(CREATE_EVENT(eventType));

    if (pEvent) {
        pEvent->VDeserialize(in);
        IEventManager::Get()->VQueueEvent(pEvent);
    } else {
        GCC_ERROR("ERROR Unknown event type from remote: 0x%s\n", ToStr(eventType, 16).c_str());
    }
}
예제 #9
0
파일: Network.cpp 프로젝트: snikk/Junk
unsigned int BaseSocketManager::GetHostByName(const std::string& hostName) {
    struct hostent* pHostEnt = gethostbyname(hostName.c_str());
    struct sockaddr_in tmpSockAddr;

    if (pHostEnt == NULL) {
        GCC_ERROR("Error occurred");
        return 0;
    }

    memcpy(&tmpSockAddr.sin_addr, pHostEnt->h_addr, pHostEnt->h_length);
    return ntohl(tmpSockAddr.sin_addr.s_addr);
}
예제 #10
0
IEventManager::IEventManager(const char* pName, bool setAsGlobal)
{
	if (setAsGlobal)
    {
        if (g_pEventMgr)
        {
            GCC_ERROR("Attempting to create two global event managers! The old one will be destroyed and overwritten with this one.");
            delete g_pEventMgr;
        }

		g_pEventMgr = this;
    }
}
예제 #11
0
float BaseScriptComponent::GetYOrientationRadians(void) const
{
    shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name));
    if (pTransformComponent)
    {
        return (GetYRotationFromVector(pTransformComponent->GetLookAt()));
    }
    else
    {
        GCC_ERROR("Attempting to call GetYOrientationRadians() on actor with no physical component");
        return 0;
    }
}
예제 #12
0
void InternalScriptExports::AttachScriptProcess(LuaPlus::LuaObject scriptProcess)
{
	LuaPlus::LuaObject temp = scriptProcess.Lookup("__object");
	if (!temp.IsNil())
	{
		shared_ptr<Process> pProcess(static_cast<Process*>(temp.GetLightUserData()));
        g_pApp->m_pGame->AttachProcess(pProcess);
	}
	else
	{
		GCC_ERROR("Couldn't find __object in script process");
	}
}
예제 #13
0
//---------------------------------------------------------------------------------------------------------------------
// Destroys a listener
//---------------------------------------------------------------------------------------------------------------------
void ScriptEventListenerMgr::DestroyListener(ScriptEventListener* pListener)
{
	ScriptEventListenerSet::iterator findIt = m_listeners.find(pListener);
	if (findIt != m_listeners.end())
	{
		m_listeners.erase(findIt);
		delete pListener;
	}
	else
	{
		GCC_ERROR("Couldn't find script listener in set; this will probably cause a memory leak");
	}
}
예제 #14
0
void PhysicsComponent::SetPosition(float x, float y, float z)
{
    shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name));
    if (pTransformComponent)
    {
        Mat4x4 transform = pTransformComponent->GetTransform();
        Vec3 position = Vec3(x, y, z);
        transform.SetPosition(position);

        KinematicMove(transform);
    }
    else
        GCC_ERROR("Attempting to call RotateY() on actor with no trnasform component");
}
예제 #15
0
void BaseScriptComponent::SetPos(LuaPlus::LuaObject newPos)
{
    shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name));
    if (pTransformComponent)
    {
        Vec3 pos;
        LuaStateManager::Get()->ConvertTableToVec3(newPos, pos);
        pTransformComponent->SetPosition(pos);
    }
    else
    {
        GCC_ERROR("Attempting to call SetPos() on an actor with no physcial component; ActorId: " + ToStr(m_pOwner->GetId()));
    }
}
예제 #16
0
//---------------------------------------------------------------------------------------------------------------------
// 
//---------------------------------------------------------------------------------------------------------------------
ScriptEvent* ScriptEvent::CreateEventFromScript(EventType type)
{
	CreationFunctions::iterator findIt = s_creationFunctions.find(type);
	if (findIt != s_creationFunctions.end())
	{
		CreateEventForScriptFunctionType func = findIt->second;
		return func();
	}
	else
	{
		GCC_ERROR("Couldn't find event type");
		return NULL;
	}
}
예제 #17
0
void PhysicsComponent::VUpdate(int deltaMs)
{
    // get the transform component
    shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name));
    if (!pTransformComponent)
    {
        GCC_ERROR("No transform component!");
        return;
    }

    // get the direction the object is facing
    Mat4x4 transform = pTransformComponent->GetTransform();

	if (m_acceleration != 0)
    {
        // calculate the acceleration this frame

        float accelerationToApplyThisFrame = m_acceleration / 1000.f * (float)deltaMs;

        // Get the current velocity vector and convert to a scalar.  The velocity vector is a combination of 
        // the direction this actor is going in and the speed of the actor.  The scalar is just the speed 
        // component.
        Vec3 velocity(m_pGamePhysics->VGetVelocity(m_pOwner->GetId()));
        float velocityScalar = velocity.Length();

		Vec3 direction(transform.GetDirection());
		m_pGamePhysics->VApplyForce(direction, accelerationToApplyThisFrame, m_pOwner->GetId());

        // logging
        // [rez] Comment this back in if you want to debug the physics thrust & rotation stuff.  It spams quite 
        // a bit of info the output window so I'm commenting it out for now.
/*
        GCC_LOG("Actor", "Acceleration: " + ToStr(accelerationToApplyThisFrame) + "; velocityScalar: " + ToStr(velocityScalar) + \
                "; direction: " + ToStr(direction) + "; direction.Length(): " + ToStr(direction.Length()) + \
                "; velocity: " + ToStr(velocity) + "; velocity.Length(): " + ToStr(velocity.Length()));
*/
    }

    if (m_angularAcceleration != 0)
    {
        // calculate the acceleration this frame
        float angularAccelerationToApplyThisFrame = m_angularAcceleration / 1000.f * (float)deltaMs;
		m_pGamePhysics->VApplyTorque(transform.GetUp(), angularAccelerationToApplyThisFrame, m_pOwner->GetId());

        // logging
        // [rez] Comment this back in if you want to debug the physics thrust & rotation stuff.  It spams quite 
        // a bit of info the output window so I'm commenting it out for now.
        //GCC_LOG("Actor", "Angular Acceleration: " + ToStr(angularAccelerationToApplyThisFrame) );
    }
}
예제 #18
0
파일: Network.cpp 프로젝트: snikk/Junk
void NetListenSocket::Init(int portnum) {
    struct sockaddr_in sa;
    int value = 1;

    if ((m_sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        GCC_ERROR("NetListenSocket Error: Init failed to created socket handle");
    }

    if (setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(value)) == SOCKET_ERROR) {
        closesocket(m_sock);
        m_sock = INVALID_SOCKET;
        GCC_ERROR("NetListenSocket Error: Init failed to set socket options");
    }

    printf("Hey hey.  Here is the INADDR_ANY = %d\n", INADDR_ANY);
    memset(&sa, 0, sizeof(sa));
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = INADDR_ANY;
    sa.sin_port = htons(portnum);

    if (bind(m_sock, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR) {
        closesocket(m_sock);
        m_sock = INVALID_SOCKET;
        GCC_ERROR("NetListenSocket Error: Init failed to bind");
    }

    SetBlocking(false);

    if (listen(m_sock, 256) == SOCKET_ERROR) {
        closesocket(m_sock);
        m_sock = INVALID_SOCKET;
        GCC_ERROR("NetListenSocket Error: Init failed to listen");
    }

    port = portnum;
}
예제 #19
0
void PhysicsComponent::RotateY(float angleRadians)
{
    shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(m_pOwner->GetComponent<TransformComponent>(TransformComponent::g_Name));
    if (pTransformComponent)
    {
        Mat4x4 transform = pTransformComponent->GetTransform();
        Vec3 position = transform.GetPosition();

        Mat4x4 rotateY;
        rotateY.BuildRotationY(angleRadians);
        rotateY.SetPosition(position);

        KinematicMove(rotateY);
    }
    else
        GCC_ERROR("Attempting to call RotateY() on actor with no transform component");
}
예제 #20
0
void PhysicsComponent::VPostInit(void)
{
    if (m_pOwner)
    {
		if (m_shape == "Sphere")
		{
			m_pGamePhysics->VAddSphere((float)m_RigidBodyScale.x, m_pOwner, m_density, m_material);
		}
		else if (m_shape == "Box")
		{
			m_pGamePhysics->VAddBox(m_RigidBodyScale, m_pOwner, m_density, m_material);
		}
		else if (m_shape == "PointCloud")
		{
			GCC_ERROR("Not supported yet!");
		}
	}
}
예제 #21
0
//---------------------------------------------------------------------------------------------------------------------
// Instantiates a C++ ScriptListener object, inserts it into the manager, and returns a handle to it.  The script 
// should maintain the handle if it needs to remove the listener at some point.  Otherwise, the listener will be 
// destroyed when the program exits.
//---------------------------------------------------------------------------------------------------------------------
unsigned long InternalScriptExports::RegisterEventListener(EventType eventType, LuaPlus::LuaObject callbackFunction)
{
	GCC_ASSERT(s_pScriptEventListenerMgr);

	if (callbackFunction.IsFunction())
	{
		// create the C++ listener proxy and set it to listen for the event
		ScriptEventListener* pListener = GCC_NEW ScriptEventListener(eventType, callbackFunction);
		s_pScriptEventListenerMgr->AddListener(pListener);
		IEventManager::Get()->VAddListener(pListener->GetDelegate(), eventType);
		
		// convert the pointer to an unsigned long to use as the handle
		unsigned long handle = reinterpret_cast<unsigned long>(pListener);
		return handle;
	}

	GCC_ERROR("Attempting to register script event listener with invalid callback function");
	return 0;
}
예제 #22
0
	void MemoryUsageObject::initMemoryPool(unsigned int numChunks, const char* debugName) {
	cout << "MemoryUsageObject::initMemoryPool" << endl;

		if (s_pMemoryPool != nullptr) {
			GCC_ERROR("s_pMemoryPool is not NULL.  All data will be destroyed.  (Ignorable)");
			//templates::safe_delete<MemoryPool>(s_pMemoryPool);
			memory_pool::safe_delete(s_pMemoryPool);
		}

		s_pMemoryPool = GCC_NEW MemoryPool;

		if (debugName) {
			s_pMemoryPool->SetDebugName(debugName);
		} else {
			s_pMemoryPool->SetDebugName("MemoryUsageObject");
		}
		s_pMemoryPool->Init(sizeof(MemoryUsageObject), numChunks);
		//cout << "End MemoryUsageObject::initMemoryPool" << endl;
	}
예제 #23
0
void WatchMeProcess::VOnUpdate(unsigned long deltaMs)
{
    StrongActorPtr pTarget = MakeStrongPtr(g_pApp->m_pGame->VGetActor(m_target));
	StrongActorPtr pMe = MakeStrongPtr(g_pApp->m_pGame->VGetActor(m_me));

    shared_ptr<TransformComponent> pTargetTransform = MakeStrongPtr(pTarget->GetComponent<TransformComponent>(TransformComponent::g_Name));
    shared_ptr<TransformComponent> pMyTransform = MakeStrongPtr(pMe->GetComponent<TransformComponent>(TransformComponent::g_Name));

	if (!pTarget || !pMe || !pTargetTransform || !pMyTransform)
	{
		GCC_ERROR("This shouldn't happen");
		Fail();
	}

	Vec3 targetPos = pTargetTransform->GetPosition();
	Mat4x4 myTransform = pMyTransform->GetTransform();
	Vec3 myDir = myTransform.GetDirection();
	myDir = Vec3(0.0f, 0.0f, 1.0f);
	Vec3 myPos = pMyTransform->GetPosition();

	Vec3 toTarget = targetPos - myPos;
	toTarget.Normalize();

	float dotProduct = myDir.Dot(toTarget);
	Vec3 crossProduct = myDir.Cross(toTarget);

	float angleInRadians = acos(dotProduct);

	if (crossProduct.y < 0)
		angleInRadians = -angleInRadians;
	
	Mat4x4 rotation;
	rotation.BuildRotationY(angleInRadians);
	rotation.SetPosition(myPos);
	pMyTransform->SetTransform(rotation);
}
예제 #24
0
파일: Network.cpp 프로젝트: snikk/Junk
void BaseSocketManager::DoSelect(int pauseMicroSecs, int handleInput) {
    timeval tv;
    tv.tv_sec = 0;

    tv.tv_usec = pauseMicroSecs;

    fd_set inp_set, out_set, exc_set;
    int maxDesc;

    FD_ZERO(&inp_set);
    FD_ZERO(&out_set);
    FD_ZERO(&exc_set);

    maxDesc = 0;

    for (SocketList::iterator i = m_SockList.begin(); i != m_SockList.end(); ++i) {
        NetSocket* pSock = *i;
        if ((pSock->m_deleteFlag & 1) || pSock->m_sock == INVALID_SOCKET)
            continue;

        if (handleInput)
            FD_SET(pSock->m_sock, &inp_set);

        FD_SET(pSock->m_sock, &exc_set);

        if (pSock->VHasOutput())
            FD_SET(pSock->m_sock, &out_set);

        if ((int)pSock->m_sock > maxDesc)
            maxDesc = (int)pSock->m_sock;
    }

    int selRet = 0;

    selRet = select(maxDesc + 1, &inp_set, &out_set, &exc_set, &tv);
    if (selRet == SOCKET_ERROR) {
        GCC_ERROR("Error in DoSelect!");
        return;
    }

    if (selRet) {
        for (SocketList::iterator i = m_SockList.begin(); i != m_SockList.end(); ++i) {
            NetSocket* pSock = *i;

            if ((pSock->m_deleteFlag & 1) || pSock->m_sock == INVALID_SOCKET)
                continue;

            if (FD_ISSET(pSock->m_sock, &exc_set))
                pSock->HandleException();

            if (!(pSock->m_deleteFlag & 1) && FD_ISSET(pSock->m_sock, &out_set))
                pSock->VHandleOutput();

            if (handleInput && !(pSock->m_deleteFlag & 1) && FD_ISSET(pSock->m_sock, &inp_set)) {
                pSock->VHandleInput();
            }
        }
    }

    unsigned int timeNow = timeGetTime();

    SocketList::iterator i = m_SockList.begin();
    while (i != m_SockList.end()) {
        NetSocket* pSock = *i;
        if (pSock->m_timeOut && pSock->m_timeOut < timeNow) 
            pSock->VTimeOut();

        if (pSock->m_deleteFlag & 1) {
            switch (pSock->m_deleteFlag) {
                case 1:
                    g_pSocketManager->RemoveSocket(pSock);
                    i = m_SockList.begin();
                    break;

                case 3:
                    pSock->m_deleteFlag = 2;
                    if (pSock->m_sock != INVALID_SOCKET) {
                        closesocket(pSock->m_sock);
                        pSock->m_sock = INVALID_SOCKET;
                    }
                    break;
            }
        }
        i++;
    }
}
예제 #25
0
bool BaseScriptComponent::VInit(TiXmlElement* pData)
{
    LuaStateManager* pStateMgr = LuaStateManager::Get();
    GCC_ASSERT(pStateMgr);

    // load the <ScriptObject> tag and validate it
    TiXmlElement* pScriptObjectElement = pData->FirstChildElement("ScriptObject");
    if (!pScriptObjectElement)
    {
        GCC_ERROR("No <ScriptObject> tag in XML.  This won't be a very useful script component.");
        return true;  // technically it succeeded even though it won't be accessible
    }

    // read all the attributes
    const char* temp = NULL;
    temp = pScriptObjectElement->Attribute("var");
    if (temp)
        m_scriptObjectName = temp;

    temp = pScriptObjectElement->Attribute("constructor");
    if (temp)
        m_constructorName = temp;

    temp = pScriptObjectElement->Attribute("destructor");
    if (temp)
        m_destructorName = temp;

    // Having a var attribute will export the instance of this object to that name.
    if (!m_scriptObjectName.empty())
    {
        m_scriptObject = pStateMgr->CreatePath(m_scriptObjectName.c_str());

        if (!m_scriptObject.IsNil())
        {
            CreateScriptObject();
        }
	}

    // The scriptConstructor attribute will also cause a Lua object to be created if one wasn't created in 
    // the previous step.  The scriptConstructor string is treated as a function of the form f(scriptObject) 
    // and is called.
    if (!m_constructorName.empty())
    {
        m_scriptConstructor = pStateMgr->GetGlobalVars().Lookup(m_constructorName.c_str());
        if (m_scriptConstructor.IsFunction())
        {
			// m_scriptObject could be nil if there was no scriptObject attribute.  If this is the case, 
            // the Lua object is created here.
			if (m_scriptObject.IsNil())
			{
				m_scriptObject.AssignNewTable(pStateMgr->GetLuaState());
				CreateScriptObject();
			}
		}
    }

    // The scriptDestructor attribute is treated as a function in the form of f(scriptObject) and is called
    // when the C++ ScriptObject instance is destroyed.
    if (!m_destructorName.empty())
    {
        m_scriptDestructor = pStateMgr->GetGlobalVars().Lookup(m_destructorName.c_str());
	}

    // read the <ScriptData> tag
    TiXmlElement* pScriptDataElement = pData->FirstChildElement("ScriptData");
    if (pScriptDataElement)
    {
        if (m_scriptObject.IsNil())
        {
            GCC_ERROR("m_scriptObject cannot be nil when ScriptData has been defined");
            return false;
        }

        for (TiXmlAttribute* pAttribute = pScriptDataElement->FirstAttribute(); pAttribute != NULL; pAttribute = pAttribute->Next())
        {
            m_scriptObject.SetString(pAttribute->Name(), pAttribute->Value());
        }
    }

	return true;
}
예제 #26
0
//---------------------------------------------------------------------------------------------------------------------
// EventManager::VTick
//---------------------------------------------------------------------------------------------------------------------
bool EventManager::VUpdate(unsigned long maxMillis)
{
	unsigned long currMs = GetTickCount();
	unsigned long maxMs = ((maxMillis == IEventManager::kINFINITE) ? (IEventManager::kINFINITE) : (currMs + maxMillis));

	// This section added to handle events from other threads.  Check out Chapter 20.
	IEventDataPtr pRealtimeEvent;
	while (m_realtimeEventQueue.try_pop(pRealtimeEvent))
	{
		VQueueEvent(pRealtimeEvent);

		currMs = GetTickCount();
		if (maxMillis != IEventManager::kINFINITE)
		{
			if (currMs >= maxMs)
			{
				GCC_ERROR("A realtime process is spamming the event manager!");
			}
		}
	}

	// swap active queues and clear the new queue after the swap
    int queueToProcess = m_activeQueue;
	m_activeQueue = (m_activeQueue + 1) % EVENTMANAGER_NUM_QUEUES;
	m_queues[m_activeQueue].clear();

    GCC_LOG("EventLoop", "Processing Event Queue " + ToStr(queueToProcess) + "; " + ToStr((unsigned long)m_queues[queueToProcess].size()) + " events to process");

	// Process the queue
	while (!m_queues[queueToProcess].empty())
	{
        // pop the front of the queue
		IEventDataPtr pEvent = m_queues[queueToProcess].front();
        m_queues[queueToProcess].pop_front();
        GCC_LOG("EventLoop", "\t\tProcessing Event " + std::string(pEvent->GetName()));

		const EventType& eventType = pEvent->VGetEventType();

        // find all the delegate functions registered for this event
		auto findIt = m_eventListeners.find(eventType);
		if (findIt != m_eventListeners.end())
		{
			const EventListenerList& eventListeners = findIt->second;
            GCC_LOG("EventLoop", "\t\tFound " + ToStr((unsigned long)eventListeners.size()) + " delegates");

            // call each listener
			for (auto it = eventListeners.begin(); it != eventListeners.end(); ++it)
			{
                EventListenerDelegate listener = (*it);
                GCC_LOG("EventLoop", "\t\tSending event " + std::string(pEvent->GetName()) + " to delegate");
				listener(pEvent);
			}
		}

        // check to see if time ran out
		currMs = GetTickCount();
		if (maxMillis != IEventManager::kINFINITE && currMs >= maxMs)
        {
            GCC_LOG("EventLoop", "Aborting event processing; time ran out");
			break;
        }
	}
	
	// If we couldn't process all of the events, push the remaining events to the new active queue.
	// Note: To preserve sequencing, go back-to-front, inserting them at the head of the active queue
	bool queueFlushed = (m_queues[queueToProcess].empty());
	if (!queueFlushed)
	{
		while (!m_queues[queueToProcess].empty())
		{
			IEventDataPtr pEvent = m_queues[queueToProcess].back();
			m_queues[queueToProcess].pop_back();
			m_queues[m_activeQueue].push_front(pEvent);
		}
	}
	
	return queueFlushed;
}
예제 #27
-4
int InternalScriptExports::CreateActor(const char* actorArchetype, LuaPlus::LuaObject luaPosition, LuaPlus::LuaObject luaYawPitchRoll)
{

    if (!luaPosition.IsTable())
    {
	    GCC_ERROR("Invalid object passed to CreateActor(); type = " + std::string(luaPosition.TypeName()));
		return INVALID_ACTOR_ID;
	}

    if (!luaYawPitchRoll.IsTable())
    {
	    GCC_ERROR("Invalid object passed to CreateActor(); type = " + std::string(luaYawPitchRoll.TypeName()));
		return INVALID_ACTOR_ID;
	}

	Vec3 pos(luaPosition["x"].GetFloat(), luaPosition["y"].GetFloat(), luaPosition["z"].GetFloat());
	Vec3 ypr(luaYawPitchRoll["x"].GetFloat(), luaYawPitchRoll["y"].GetFloat(), luaYawPitchRoll["z"].GetFloat());

	Mat4x4 initialTransform;
	initialTransform.BuildYawPitchRoll(ypr.x, ypr.y, ypr.z);
	initialTransform.SetPosition(pos);

	TiXmlElement *overloads = NULL;
	StrongActorPtr pActor = g_pApp->m_pGame->VCreateActor(actorArchetype, overloads, &initialTransform);

	if (pActor)
	{
		shared_ptr<EvtData_New_Actor> pNewActorEvent(GCC_NEW EvtData_New_Actor(pActor->GetId()));
		IEventManager::Get()->VQueueEvent(pNewActorEvent);
		return pActor->GetId();
	}

	return INVALID_ACTOR_ID;
}