int main(int ac, char **av) { if (ac == 4) { try { Game *game = new Game(atoi(av[1]), atoi(av[2])); std::list<ISnake *> tmp; std::list<IFood *> tmpf; std::list<IHole *> tmph; int ret; maker_Display pMaker; void *hndl; void *mkr; srand(getpid()); hndl = dlopen(av[3], RTLD_LAZY); if (hndl == NULL) throw GameException("Error load librairie"); mkr = dlsym(hndl, "make_display"); if (mkr == NULL) { dlclose(hndl); throw GameException("Error load function librairie"); } pMaker = (maker_Display)mkr; Display *my_graph = pMaker(); ret = 0; if (my_graph->Init() == false) throw GameException("Error on creation of Window"); while (my_graph->Window() == true && ret != -1) { tmp = game->getSList(); tmpf = game->getFList(); tmph = game->getHole(); my_graph->Play(tmp, tmpf, tmph, game->getScore()); ret = game->checkCollision(tmp, tmpf, tmph); if (ret == 1) { game->setScore(); game->updateSList(tmp); game->updateFList(tmpf); } game->setSList(tmp); game->setFList(tmpf); game->analyseLevel(); usleep(game->getSpeed()); } my_graph->Finish(); dlclose(hndl); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; } } else std::cout << "Usage : ./nibbler LEN WIDTH LIB" << std::endl; return (0); }
Point3D Point3D::fromUserString(const QString &string) { if (!string.startsWith("(") || !string.endsWith(")")) { throw GameException(GameException::InvalidPoint); } QStringList stringList = string.mid(1, string.length() - 2).split(','); if (stringList.length() != 3) { throw GameException(GameException::InvalidPoint); } return Point3D(stringList[0].trimmed().toInt(), stringList[1].trimmed().toInt(), stringList[2].trimmed().toInt()); }
void Point3D::fromUserString(const QString &string, Point3D &point) { if (!string.startsWith(QLatin1String("(")) || !string.endsWith(QLatin1String(")"))) { throw GameException(GameException::InvalidPoint); } QStringList stringList = Util::splitComponents(string); if (stringList.length() != 3) { throw GameException(GameException::InvalidPoint); } point.x = stringList[0].toInt(), point.y = stringList[1].toInt(), point.z = stringList[2].toInt(); }
QJsonValue ConversionUtil::toJsonValue(const QVariant &variant) { switch (variant.type()) { case QVariant::Bool: case QVariant::Int: case QVariant::UInt: case QVariant::Double: case QVariant::String: case QVariant::List: case QVariant::StringList: case QVariant::Map: return QJsonValue::fromVariant(variant); case QVariant::DateTime: return QJsonValue((double) variant.toDateTime().toMSecsSinceEpoch()); case QVariant::UserType: { MetaTypeRegistry::JsonConverters converters = MetaTypeRegistry::jsonConverters(QMetaType::typeName(variant.userType())); if (converters.typeToJsonValueConverter) { return converters.typeToJsonValueConverter(variant); } else { const char *typeName = QMetaType::typeName(variant.userType()); LogUtil::logError(typeName ? QStringLiteral("User type not serializable: %1").arg(typeName) : QStringLiteral("Unknown user type: %1").arg(variant.userType())); return QJsonValue(); } } default: throw GameException(GameException::SerializationException, QStringLiteral("Unknown type: %1").arg(variant.typeName())); } }
void Session::setPlayer(GameObject *player) { m_player = qobject_cast<Player *>(player); if (!m_player) { throw GameException(GameException::InvalidGameObjectCast); } }
// ///////////////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////////////// EventManager::EventManager(char const * const pName, bool setAsGlobal) throw (GameException &) : IEventManager(pName, setAsGlobal), m_typeList(), m_registry(), m_activeQueue(0), /*m_RealtimeEventQueue(),*/\ m_MetaTable(), m_ScriptEventListenerMap(), m_ScriptActorEventListenerMap(), m_ScriptDefinedEventTypeSet() { if(!g_appPtr) { throw GameException(string("Cannot setup the EventManager as the global application pointer is NULL.")); } //Open up access to script. { shared_ptr<LuaStateManager> luaStateManager = g_appPtr->GetLuaStateManager(); // Note that this is slightly different than in the book, since the // Lua chapter was AFTER the event manager chapter. //Create our metatable... m_MetaTable = luaStateManager->GetGlobalState()->GetGlobals().CreateTable("EventManager"); m_MetaTable.SetObject("__index", m_MetaTable); m_MetaTable.RegisterObjectDirect( "TriggerEvent", (EventManager *)0, &EventManager::TriggerEventFromScript ); m_MetaTable.RegisterObjectDirect( "QueueEvent", (EventManager *)0, &EventManager::QueueEventFromScript ); m_MetaTable.RegisterObjectDirect( "RegisterEventType", (EventManager *)0, &EventManager::RegisterScriptEventType ); m_MetaTable.RegisterObjectDirect( "AddScriptListener", (EventManager *)0, &EventManager::AddScriptListener ); m_MetaTable.RegisterObjectDirect( "RemoveScriptListener", (EventManager *)0, &EventManager::RemoveScriptListener ); m_MetaTable.RegisterObjectDirect( "AddScriptActorListener", (EventManager *)0, &EventManager::AddScriptActorListener ); m_MetaTable.RegisterObjectDirect( "RemoveScriptActorListener", (EventManager *)0, &EventManager::RemoveScriptActorListener ); LuaObject luaStateManObj = luaStateManager->GetGlobalState()->BoxPointer(this); luaStateManObj.SetMetaTable(m_MetaTable); luaStateManager->GetGlobalState()->GetGlobals().SetObject("EventManager", luaStateManObj); } }
void TextureModelDemo::CreateVertexBuffer(ID3D11Device* device, const Mesh& mesh, ID3D11Buffer** vertexBuffer) const { const std::vector<XMFLOAT3>& sourceVertices = mesh.Vertices(); std::vector<TextureMappingVertex> vertices; vertices.reserve(sourceVertices.size()); std::vector<XMFLOAT3>* textureCoordinates = mesh.TextureCoordinates().at(0); assert(textureCoordinates->size() == sourceVertices.size()); for (UINT i = 0; i < sourceVertices.size(); i++) { XMFLOAT3 position = sourceVertices.at(i); XMFLOAT3 uv = textureCoordinates->at(i); vertices.push_back(TextureMappingVertex(XMFLOAT4(position.x, position.y, position.z, 1.0f), XMFLOAT2(uv.x, uv.y))); } D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.ByteWidth = sizeof(TextureMappingVertex) * vertices.size(); vertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA vertexSubResourceData; ZeroMemory(&vertexSubResourceData, sizeof(vertexSubResourceData)); vertexSubResourceData.pSysMem = &vertices[0]; if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexSubResourceData, vertexBuffer))) { throw GameException("ID3D11Device::CreateBuffer() failed."); } }
void Level::unserialize(std::istream & is) throw(GameException) { clear(); // Level info m_levelInfo.unserialize(is); // Entity amount uint32 nbEntities = 0; util::unserialize(is, nbEntities); // Entities for(uint32 i = 0; i < nbEntities; i++) { Entity * e = NULL; /* Unserializing entity */ try { e = Entity::unserializeEntity(is); addEntity(e); } catch(std::exception & e) { std::stringstream ss; ss << e.what() << std::endl; ss << "In Level::unserialize"; throw GameException(ss.str()); } } // end for i < nbEntities }
void RenderingGame::initialize() { if (FAILED(DirectInput8Create(mInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&mDirectInput,nullptr))) { throw GameException(L"DirectInput8Create() failed"); } mFpsComponent = new FpsComponent(*this); mTextComponent = new TextComponent(*this, L"This is my text"); mTextComponent->setTextPosition({ 50, 100 }); mKeyboard = new Keyboard(*this, mDirectInput); mMouse = new Mouse(*this, mDirectInput); mCamera = new FirstPersonCamera(*this); mDemo = new MaterialDemo(*this, *mCamera); mSpotLightDemo = new SpotLightDemo(*this, *mCamera); mServiceContainer.addService(Keyboard::typeIdClass(), mKeyboard); mServiceContainer.addService(Mouse::typeIdClass(), mMouse); mServiceContainer.addService(FirstPersonCamera::typeIdClass(),mCamera); mComponents.push_back(mCamera); mComponents.push_back(mSpotLightDemo); mComponents.push_back(mMouse); mComponents.push_back(mKeyboard); mComponents.push_back(mFpsComponent); mComponents.push_back(mTextComponent); Game::initialize(); mCamera->setPosition(0.0f, 0.0f, 25.0f); }
void RenderingGame::initialize() { if (FAILED(DirectInput8Create(mInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (LPVOID*)&mDirectInput,nullptr))) { throw GameException(L"DirectInput8Create() failed"); } mFpsComponent = new FpsComponent(*this); mTextComponent = new TextComponent(*this, L""); mTextComponent->setTextPosition({ 0, 100 }); mKeyboard = new Keyboard(*this, mDirectInput); mMouse = new Mouse(*this, mDirectInput); mCamera = new PinholeCamera(*this); mRayTracingDemo = new RayTracingDemo(*this, *mCamera); mServiceContainer.addService(Keyboard::typeIdClass(), mKeyboard); mServiceContainer.addService(Mouse::typeIdClass(), mMouse); mServiceContainer.addService(FirstPersonCamera::typeIdClass(),mCamera); mComponents.push_back(mCamera); mComponents.push_back(mRayTracingDemo); mComponents.push_back(mMouse); mComponents.push_back(mKeyboard); mComponents.push_back(mFpsComponent); mComponents.push_back(mTextComponent); Game::initialize(); mCamera->setEyeVector(0, 0, 500); mCamera->setLookAt(0, 0, 0); mCamera->setViewDistance(600); }
void Session::setSessionState(int sessionState) { m_sessionState = (SessionState) sessionState; switch (m_sessionState) { case SessionClosed: emit terminate(); break; case SigningIn: { break; } case SignedIn: { if (!m_player) { throw GameException(GameException::InvalidSignIn, "Player object should have been set"); } LogUtil::logCommand(m_player->name(), "(signed in)"); m_player->setSession(this); break; } } }
AvatarGameObj* GameplayMode::find_avatar() { GOMap::iterator i = Globals::gameobjs.find(_avatar_key); if (i == Globals::gameobjs.end()) { throw GameException(std::string("GameplayMode: LIBAvatar GameObj named ") + _avatar_key + " has disappeared unexpectedly"); } return static_cast<AvatarGameObj*>(&(*(i->second))); }
QVariant ConversionUtil::fromJsonVariant(QVariant::Type type, int userType, const QVariant &variant) { switch (type) { case QVariant::Bool: case QVariant::Int: case QVariant::Double: case QVariant::String: return variant; case QVariant::StringList: return variant.toStringList(); case QVariant::DateTime: return QDateTime::fromMSecsSinceEpoch(variant.toLongLong()); case QVariant::Map: { QVariantMap variantMap; QVariantMap map = variant.toMap(); for (const QString &key : map.keys()) { QVariantList valueList = map[key].toList(); if (valueList.length() == 3) { QVariant::Type valueType = (QVariant::Type) valueList[0].toInt(); int valueUserType = valueList[1].toInt(); QVariant value = valueList[2]; variantMap[key] = fromJsonVariant(valueType, valueUserType, value); } else { throw GameException(GameException::SerializationException, QStringLiteral("Invalid map format in key: %1").arg(key)); } } return variantMap; } case QVariant::UserType: { MetaTypeRegistry::JsonConverters converters = MetaTypeRegistry::jsonConverters(QMetaType::typeName(userType)); if (converters.jsonVariantToTypeConverter) { return converters.jsonVariantToTypeConverter(variant); } else { const char *typeName = QMetaType::typeName(userType); throw GameException(GameException::SerializationException, typeName ? QStringLiteral("User type not serializable: %1").arg(typeName) : QStringLiteral("Unknown user type: %1").arg(userType)); } } default: throw GameException(GameException::SerializationException, QStringLiteral("Unknown type: %1").arg(QVariant::typeToName(type))); } }
void Keyboard::initialize() { if (FAILED(mDirectInput->CreateDevice(GUID_SysKeyboard, &mDevice, nullptr))) { throw GameException(L"IDIRECTINPUT8::CreateDevice() failed"); } if (FAILED(mDevice->SetDataFormat(&c_dfDIKeyboard))) { throw GameException(L"IDIRECTINPUTDEVICE8::SetDataFormat() failed"); } if (FAILED(mDevice->SetCooperativeLevel(mGame->windowHandle(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE))) { throw GameException(L"IDIRECTINPUTDEVICE8::SetCoorperationLevel() failed"); } mDevice->Acquire(); }
void GameEventMultiplierMap::fromUserString(const QString &string, GameEventMultiplierMap &multipliers) { Q_UNUSED(string) Q_UNUSED(multipliers) throw GameException(GameException::NotSupported, "Converting user strings to game event multiplier map not (yet) supported"); }
GameLoop::GameLoop() : m_input_devices(), m_screen_factory(), m_screen(nullptr) { const Configuration& configuration = *the_context.configuration; if(NetworkMode::SERVER == configuration.network_mode || NetworkMode::WITH_SERVER == configuration.network_mode) { auto server_backend = std::make_unique<ENetServer>(configuration.port); auto server_impl = std::make_unique<BasicServer>(std::move(server_backend)); m_server.reset(new ServerThread(std::move(server_impl))); m_screen_factory.set_server(m_server.get()); } // configure player control if(configuration.player_number.has_value()) { const int player_number = *configuration.player_number; if(2 <= player_number) { throw GameException("Cannot control player " + std::to_string(player_number) + ". More than two players are currently not yet supported."); } m_input_devices.set_player_number(player_number); } // attach joystick input if(configuration.joystick_number.has_value()) { const int joystick_number = *configuration.joystick_number; const int joysticks_count = SDL_NumJoysticks(); if(joystick_number < 0 || joystick_number >= joysticks_count) { throw GameException("Joystick " + std::to_string(joystick_number) + " not found. There are " + std::to_string(joysticks_count) + " joysticks."); } JoystickPtr joystick(SDL_JoystickOpen(joystick_number)); sdlok(joystick.get()); m_input_devices.set_joystick(std::move(joystick)); } next_screen(); }
// ///////////////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////////////// GameLog::GameLog(const path &filenameRef, const LogLevel initialLevel, const bool timestamp) throw (GameException &) : m_logger(), m_logLevel(initialLevel), m_timestamp(timestamp) { m_logger.open(filenameRef.string().c_str()); if(!m_logger.is_open()) { throw (GameException(string("Failed to open the log file."))); } Log(FAT, string("Start")); }
void Loading::onEnter() { // Read resource list file if(!m_loadingList.loadFromLuaScript("registerResources.lua")) { std::stringstream ss; ss << "Loading::enter: " << "An error occured while reading the resource file." << std::endl; ss << "LoadingList content :" << std::endl; m_loadingList.print(ss); throw GameException(ss.str(), Exception::EX_ERROR); } m_initialLoadItemsCount = m_loadingList.getTotalRemaining(); }
GameplayMode::GameplayMode() : _fsm(*Globals::current_mission, *this) { // Locate the avatar object for (GOMap::iterator i = Globals::gameobjs.begin(); i != Globals::gameobjs.end(); ++i) { GOMap::size_type idx = i->first.find("LIBAvatar"); if (idx == 0) { _avatar_key = i->first; break; } } if (_avatar_key.size() == 0) { throw GameException(std::string("Unable to locate LIBAvatar GameObj in GameplayMode init!")); } }
GameObjectPtr GameObjectPtr::fromUserString(const QString &string) { if (string == "0") { return GameObjectPtr(); } QStringList components = string.split(':'); if (components.length() != 2) { throw GameException(GameException::InvalidGameObjectPointer); } return GameObjectPtr(Realm::instance(), GameObjectType::fromString(components[0]), components[1].toInt()); }
QVariant ConversionUtil::fromJsonValue(QVariant::Type type, int userType, const QJsonValue &value) { switch (type) { case QVariant::Bool: case QVariant::Int: case QVariant::UInt: case QVariant::Double: case QVariant::String: case QVariant::Map: return value.toVariant(); case QVariant::StringList: { QStringList stringList; for (const QJsonValue &item : value.toArray()) { stringList.append(item.toString()); } return stringList; } case QVariant::DateTime: return QDateTime::fromMSecsSinceEpoch((qint64) value.toDouble()); case QVariant::UserType: { MetaTypeRegistry::JsonConverters converters = MetaTypeRegistry::jsonConverters(QMetaType::typeName(userType)); if (converters.jsonValueToTypeConverter) { return converters.jsonValueToTypeConverter(value); } else { const char *typeName = QMetaType::typeName(userType); throw GameException(GameException::SerializationException, typeName ? QStringLiteral("User type not serializable: %1").arg(typeName) : QStringLiteral("Unknown user type: %1").arg(userType)); } } default: throw GameException(GameException::SerializationException, QStringLiteral("Unknown type: %1").arg(QVariant::typeToName(type))); } }
void RayTracerMaterial::createVertexBuffer(ID3D11Device* device, VertexPositionTexture* vertices, UINT vertexCount, ID3D11Buffer** vertexBuffer) const { D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.ByteWidth = vertexSize() * vertexCount; vertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA vertexSubResourceData; ZeroMemory(&vertexSubResourceData, sizeof(vertexSubResourceData)); vertexSubResourceData.pSysMem = vertices; if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexSubResourceData, vertexBuffer))) { throw GameException("ID3D11Device::CreateBuffer() failed."); } }
void GameObjectPtr::resolve(Realm *realm) { if (m_id == 0) { return; } m_gameObject = realm->getObject(m_objectType, m_id); if (!m_gameObject) { throw GameException(GameException::InvalidGameObjectPointer, m_objectType, m_id); } if (m_objectType == GameObjectType::Unknown) { m_objectType = m_gameObject->objectType(); } m_gameObject->registerPointer(this); }
void SkyboxMaterial::createVertexBuffer(ID3D11Device * device, XMFLOAT4 * vertices, UINT vertexCount, ID3D11Buffer** vertexBuffers)const { D3D11_BUFFER_DESC vertexBufferDesc; ZeroMemory(&vertexBufferDesc, sizeof(vertexBufferDesc)); vertexBufferDesc.ByteWidth = vertexCount * vertexSize(); vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; D3D11_SUBRESOURCE_DATA vertexSubResource; ZeroMemory(&vertexSubResource, sizeof(vertexSubResource)); vertexSubResource.pSysMem = vertices; if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexSubResource, vertexBuffers))) { throw GameException(L"CreateBuffer Failed "); } }
void Mesh::CreateIndexBuffer(ID3D11Device * pDevice, ID3D11Buffer** indexBuffer) { assert(indexBuffer != nullptr); assert(pDevice != nullptr); D3D11_BUFFER_DESC indexBufferDesc; ZeroMemory(&indexBufferDesc, sizeof(indexBufferDesc)); indexBufferDesc.ByteWidth = sizeof(UINT) * mIndices.size(); indexBufferDesc.Usage = D3D11_USAGE_IMMUTABLE; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; D3D11_SUBRESOURCE_DATA indexSubResourceData; ZeroMemory(&indexSubResourceData, sizeof(indexSubResourceData)); indexSubResourceData.pSysMem = &mIndices[0]; if (FAILED(pDevice->CreateBuffer(&indexBufferDesc, &indexSubResourceData, indexBuffer))) { throw GameException("ID3D11Device::CreateBuffer() failed."); } }
void RenderingGame::draw(const GameTimer & gameTime) { mDeviceContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float *>(&BackgroundColor)); mDeviceContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); Game::draw(gameTime); HRESULT hr; hr = mSwapChain->Present(0, 0); std::wstring mouseString( L"MousePosition : " + std::to_wstring(mMouse->x()) ); mouseString += L", " + std::to_wstring(mMouse->y()); mouseString += L"\nMouseWheel " + std::to_wstring(mMouse->wheel()); mTextComponent->setText(mouseString); if (FAILED(hr)) { throw GameException(L"IDXGISwapChain::Present() failed.", hr); } }
void DroppedItem::unserialize(std::istream & is) throw(GameException) { Entity::unserialize(is); if(m_item != NULL) delete m_item; m_item = NULL; try { m_item = Item::unserializeItem(is); setRenderer(m_item->createDroppedRenderer()); } catch(std::exception & ex) { std::stringstream ss; ss << ex.what() << std::endl; ss << "In EntityDroppedItem::unserialize"; throw GameException(ss.str()); } }
Scene::ExitAction Game::runScene(Scene::ExitAction act){ switch (act){ case Scene::ExitAction::RunMainMenu: Log::write("Runnig main menu"); return Menu(window).run(); case Scene::ExitAction::RunPlayModeSelect: Log::write("Running play mode select scene"); return PlayModeSelect(window).run(); case Scene::ExitAction::RunGameVsAI: Log::write("Running battle vs AI"); return BattleVsAI(window, settings.difficulty).run(); case Scene::ExitAction::RunGameVsPlayer: Log::write("Running battle vs Player"); return BattleVsPlayer(window).run(); case Scene::ExitAction::RunOptions: Log::write("Running options"); return Options(window, settings).run(); case Scene::ExitAction::RunAbout: Log::write("Running about"); return About(window).run(); default: throw GameException("No appropriate scene found", "Game::runScene()"); } }
// Loads the current level from its name. // If it already exist, it is erased and replaced. // Returns the loaded level (if loading succeeded). Level * LevelManager::openLevel(std::string name) throw(GameException) { std::cout << "Loading level..." << std::endl; std::string levelPath = "worlds/world/" + name; adaptFilePath(levelPath); std::ifstream ifs(levelPath.c_str(), std::ios::in | std::ios::binary); if(ifs.good()) { if(isLevel()) closeLevel(); m_level = new Level(); m_level->unserialize(ifs); ifs.close(); } else { throw GameException("LevelManager::loadLevel: Cannot load level '" + levelPath + "'"); } std::cout << "Level loaded" << std::endl; return getLevel(); }
// ///////////////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////////////// void EnvironmentSceneNode::Init(const std::vector<std::string> &cubemapTextureNameVec, const std::string &shaderNameRef, const F32 cmRadius) throw(GameException &) { // Load the textures for the sides of the cubemap. boost::optional<TexHandle> tHandle = g_appPtr->GetTextureManagerPtr()->LoadCubeMap(cubemapTextureNameVec, GL_CLAMP_TO_EDGE); if(!tHandle.is_initialized()) { throw GameException(std::string("Failed to load the textures for the EnvironmentMap")); } m_texHandle = *tHandle; SceneNode::SetRadius(cmRadius); // TODO: Remove dependancy on GLTools external lib. gltMakeCube(m_cubeBatch, cmRadius); // Set the shader name (The SGM should already have this shader built and included). SceneNode::SetShaderName(shaderNameRef); if(m_shaderPtr) { m_mvpUniform = m_shaderPtr->GetUniform("mvpMatrix"); m_cmUniform = m_shaderPtr->GetUniform("cubeMap"); } }