MainMenuState::MainMenuState(Vector2 screenSize, ALLEGRO_KEYBOARD_STATE* keyState, ALLEGRO_KEYBOARD_STATE* prevKeyState, ALLEGRO_MOUSE_STATE* mouseState, ALLEGRO_MOUSE_STATE* prevMouseState, ALLEGRO_FONT* font) : GameState(screenSize, keyState, prevKeyState, mouseState, prevMouseState) { cout << "Main State initialized" << endl; this->font = font; background = al_load_bitmap("assets/img/selectGameScreen/Starfield.png"); leftDoor = GameObject("assets/img/selectGameScreen/Leftblastdoor.png", Vector2(1, 1), 30, Vector2()); rightDoor = GameObject("assets/img/selectGameScreen/Rightblastdoor.png", Vector2(1, 1), 30, Vector2(457, 0)); //457 = 559 (size of left door) - 102 (overlap between doors) mainButton = Button("assets/img/selectGameScreen/StartButton.png", Vector2(1, 1), 100, "assets/img/selectGameScreen/StartButton.png", Vector2(1, 1), 100, "assets/img/selectGameScreen/StartButtonHover.png", Vector2(2, 1), 100, Vector2(300, 200), true); cout << "Main button loaded" << endl; opening = false; /*********************************************************************************************** ****************************************** Planets ******************************************** ***********************************************************************************************/ Vector2 center = Vector2(getScreenSize().x / 2, getScreenSize().y / 2); planets.push_back(PlanetButton("Play", font, "assets/img/gameMenuCircles/Center.png", center, 0, 0, 0.001, 0.001)); planets.push_back(PlanetButton("Instructions", font, "assets/img/gameMenuCircles/Planet1.png", center, 175, M_PI / 2, 0.0003, 0.002)); planets.push_back(PlanetButton("Back", font, "assets/img/gameMenuCircles/Planet3.png", center, 350, M_PI, -0.0002, -0.0015)); planets.push_back(PlanetButton("Quit", font, "assets/img/gameMenuCircles/Planet2.png", center, 410, M_PI, -0.00015, 0.003)); }
Player::Player(std::string _name, osg::Vec3f _pos, float _colRad, int _hp, osg::ref_ptr<osg::MatrixTransform> _scene, int _bridgeModel) { initTransform(); rigidBodyRadius = _colRad; pos = _pos; setName(_name); setHP(_hp); setMaxHP(_hp); _scene->addChild(playerTransform); playerTransform->postMult(osg::Matrix::translate(pos)); healthbarTransform->postMult(osg::Matrix::rotate(-PI / 8, 1.0f, 0.0f, 0.0f)); bridgeTransform->postMult(osg::Matrix::rotate(PI + PI / 4.0, 1.0, 0.0, 0.0)); //bridgeTransform->postMult(osg::Matrix::scale(0.1f, 0.1f, 0.1f)); if (_bridgeModel == 1) { bridge = GameObject((std::string)("Kommandobryggan"), osg::Vec3f(0, 0, 0), 0, 100000, (std::string)("models/kurvbrygga_lasselagom.ive"), bridgeTransform, 100000); bridgeTransform->postMult(osg::Matrix::translate(0.0f, 3.5f, 0.0f)); } if (_bridgeModel == 2) { bridge = GameObject((std::string)("Kommandobryggan"), osg::Vec3f(0, 0, 0), 0, 100000, (std::string)("models/kurvbrygga_lasselagom.ive"), bridgeTransform, 100000); bridgeTransform->postMult(osg::Matrix::translate(0.0f, 2.5f, 0.0f)); } if (_bridgeModel == 3) { bridge = GameObject((std::string)("Kommandobryggan"), osg::Vec3f(0, 0, 0), 0, 100000, (std::string)("models/kurvbrygga_lassesmal.ive"), bridgeTransform, 100000); bridgeTransform->postMult(osg::Matrix::translate(0.0f, 3.5f, 0.0f)); } if (_bridgeModel == 4) { bridge = GameObject((std::string)("Kommandobryggan"), osg::Vec3f(0, 0, 0), 0, 100000, (std::string)("models/kurvbrygga_lassesmal.ive"), bridgeTransform, 100000); bridgeTransform->postMult(osg::Matrix::translate(0.0f, 2.5f, 0.0f)); } }
void SpriteRenderer::Render() { if (!_mesh) return; if (!_mesh->IsValid()) return; Shader *shader = _material.Shader(); if (!shader) return; if (!shader->Valid()) return; RenderPipeline *pipeline = GameObject()->RenderPipeline(); RenderOperation rop; rop.material = &_material; rop.mesh = _mesh.get(); Matrix4 scale = math::Scaling(Vector3(_size, 1)); if (_useTransform) { _worldMatrix = Transform()->TransformToWorldMatrix(); } else { Quaternion rotation = math::Rotation(_rotation, Vector3(0,0,1)); Matrix4 transform = Transform::GetRTMatrix(Vector3(_position, 0), rotation); _worldMatrix = transform; } _worldMatrix *= scale; rop.worldMatrix = &_worldMatrix; rop.is2D = true; pipeline->AddRenderOperation(rop); }
Asteroid::Asteroid(int x, int y, SDL_Surface *sprite, Player *p) { GameObject(); m_posX = x; m_posY = y; m_velX = 1; m_velY = 0; m_dirX = -1; m_dirY = 0; m_boundX = 35; m_boundY = 35; m_curFrame = 0; m_frameWidth = 64; m_frameHeight = 64; m_frameCount = 0; m_frameDelay = 3; m_maxFrame = 64; m_animationColumns = 8; m_animationRow = 0; m_animationDirection = 1; SetSprite(sprite); SetID(ENEMY); Asteroid::p=p; }
GameObject EntityFactory::createObjectFromIML( const std::string &name, const IMLNode *iml) const { //printf("EntityFactory::createObjectFromIML: '%s'\n", name.c_str()); IMLNode *node = iml->findByName(name); if (!node || name.empty()) { fprintf(stderr, "Unable to create entity: '%s'\n", name.c_str()); return GameObject(0); } EntityManager &em = EntityManager::instance(); GameObject entity = em.createEntity(); std::list<IMLNode*> &components_iml = node->getChildren(); std::list<IMLNode*>::iterator it = components_iml.begin(); for (; it != components_iml.end(); ++it) { IMLTag *tag = dynamic_cast<IMLTag*>(*it); if (tag) { ComponentFactory &cf = ComponentFactory::instance(); IComponent *comp = cf.create((*it)->getName()); if (!comp) { fprintf(stderr, "Unable to create component: %s\n", (*it)->getName().c_str()); } else { comp->loadIML(*tag); em.addComponentToEntity(comp, entity); } } } return entity; }
std::shared_ptr<Weapon> ObjectFactory::createWeapon(TemplateWeapon &weaponTemplate, RarityType &rarityType){ int damage = (int)(engine::damageMax * weaponTemplate.damageFromMax * rarityType.improvementMultiplier * engine::random.variationMultiplier(engine::statisticVariation)); double durability = engine::durabilityMax * weaponTemplate.durabilityFromMax * engine::random.variationMultiplier(engine::statisticVariation); std::shared_ptr<Weapon> weapon = std::shared_ptr<Weapon>(new Weapon( Equipment(Item(engine::raritySystem.getWeaponMod(rarityType), GameObject( weaponTemplate.name, weaponTemplate.type, weaponTemplate.glyph), weaponTemplate.weightKg, weaponTemplate.limbsRequiredToHold), durability), damage, *engine::objectLibrary.creatureSkills[weaponTemplate.skillId] )); //rarity color weapon->glyph.fgColor = weapon->glyph.fgColor * rarityType.color; return weapon; }
GameObject EntityManager::createEntity() { unsigned eid = generateEid(); entities_.push_back(eid); //printf("Created entity: %d\n", eid); return GameObject(eid); }
void WorldState::Init(RenderContext& ctx,Scene* m_scene){ std::cout << "Initializing WorldState\n"; ctx.checkFS(isFullscreen = false); Tiles* tile; tile->CreateMap(ctx,m_scene); m_scene->add(GameObject(ctx, std::string("res/hero1.png"), std::string("hero")), 0, {300, 200}, true); }
std::shared_ptr<Armor> ObjectFactory::createArmor(TemplateArmor &armorTemplate, RarityType &rarityType){ int defence = (int)(engine::defenceMax * armorTemplate.defenceFromMax * rarityType.improvementMultiplier * engine::random.variationMultiplier(engine::statisticVariation)); double durability = engine::durabilityMax * armorTemplate.durabilityFromMax * engine::random.variationMultiplier(engine::statisticVariation); std::shared_ptr<Armor> armor = std::shared_ptr<Armor>(new Armor( Equipment(Item(engine::raritySystem.getArmorMod(rarityType), GameObject( armorTemplate.name, armorTemplate.type, armorTemplate.glyph), armorTemplate.weightKg, armorTemplate.limbsRequiredToHold), durability), armorTemplate.limbsRequiredToEquip, defence )); //rarity color armor->glyph.fgColor = armor->glyph.fgColor * rarityType.color; return armor; }
std::shared_ptr<Consumable> ObjectFactory::createConsumable(TemplateConsumable &consumableTemplate, RarityType &rarityType){ double potency = engine::consumablePotencyMax * consumableTemplate.potencyFromMax * rarityType.improvementMultiplier * engine::random.variationMultiplier(engine::statisticVariation); double concentration = engine::consumableConcentrationMax * consumableTemplate.concentrationFromMax * rarityType.improvementMultiplier * engine::random.variationMultiplier(engine::statisticVariation); std::shared_ptr<Consumable> consumable = std::shared_ptr<Consumable>(new Consumable( Item(engine::raritySystem.getConsumableMod(rarityType), GameObject( consumableTemplate.name, GameObject::CONSUMABLE, consumableTemplate.glyph), consumableTemplate.weightKg), potency, concentration )); //rarity color consumable->glyph.fgColor = consumable->glyph.fgColor * rarityType.color; return consumable; }
void Game::DefeatScreen() { SDL_RenderClear(this->g_Renderer); this->resultText.setRenderer(this->g_Renderer); this->resultText.LoadFromRenderedText("YOU LOSE!", this->g_Font); this->resultTextObj = GameObject(&this->resultText, &this->invadersViewport, NULL, (this->invadersViewport.w - this->resultText.getWidth()) / 2, (Game::SCREEN_HEIGHT - this->resultText.getHeight()) / 4); this->playAgainTextObj = GameObject(&this->playAgainText, &this->invadersViewport, NULL, (this->invadersViewport.w - this->playAgainText.getWidth()) / 2, (Game::SCREEN_HEIGHT - this->resultText.getHeight()) / 4 + this->resultText.getHeight()); this->resultTextObj.Draw(); this->playAgainTextObj.Draw(); this->scoreTextObj.Draw(); SDL_RenderPresent(this->g_Renderer); }
Pickup::Pickup() { GameObject(); scaleX = scaleY = 1.0f; scaleZ = 7.0f; rotX = rotY = rotZ = 0.0f; transX = transY = transZ = 0.0f; }
void GameObjectPool::Initialize(size_t poolSize) { mObjects.resize(poolSize, GameObject(nullptr)); pNextAvailable = &mObjects[0]; for (size_t i = 0; i < mObjects.size() - 1; ++i) { mObjects[i].pNextFreeObject = &mObjects[i + 1]; } mObjects.back().pNextFreeObject = nullptr; }
void Game::LoadScreen() { this->invadersDirection = 1; this->invadersMoveTime = 500; this->movedDown = false; this->updateInvoked = false; this->projectiles.erase(this->projectiles.begin(), this->projectiles.end()); this->invadersGrid.erase(this->invadersGrid.begin(), this->invadersGrid.end()); for (int i = 0; i < this->g_Texture.getWidth(); i += Game::INVADER_WIDTH) { this->invaderTypes.push_back({ i, 0, Game::INVADER_WIDTH, Game::INVADER_HEIGHT }); } srand(time(NULL)); int x = 0; for (int col = 0; col < Game::INVADER_COLS; ++col) { std::vector<Invader> newCol; int y = 0; for (int row = 0; row < Game::INVADER_ROWS; ++row) { newCol.push_back(Invader(&this->g_Texture, &this->invadersViewport, &this->invaderTypes[rand() % Game::INVADER_TYPES_COUNT], rand() % Game::INVADER_BOUNTY_CAP, x, y)); y += Game::INVADER_WIDTH + Game::GAME_INFO_VIEWPORT_ITEMS_SPACE_WIDTH / 2; } this->invadersGrid.push_back(newCol); x += Game::INVADER_HEIGHT + Game::GAME_INFO_VIEWPORT_ITEMS_SPACE_WIDTH; } this->playerSrcRect = { 0, Game::INVADER_HEIGHT, Game::PLAYER_WIDTH, Game::PLAYER_HEIGHT }; this->player = Player(&this->g_Texture, &this->playerViewport, &this->playerSrcRect, (Game::SCREEN_WIDTH - Game::PLAYER_WIDTH) / 2, 0); this->scoreText.LoadFromRenderedText("SCORE: " + std::to_string(this->player.getPoints()), this->g_Font); this->scoreTextObj = GameObject(&this->scoreText, &this->scoreInfoViewport, NULL, Game::GAME_INFO_VIEWPORT_ITEMS_SPACE_WIDTH, (this->scoreInfoViewport.h - this->scoreText.getHeight()) / 2); this->livesText.LoadFromRenderedText("LIVES: " + std::to_string(this->player.getLives()), this->g_Font); this->livesTextObj = GameObject(&this->livesText, &this->playerLivesViewport, NULL, Game::GAME_INFO_VIEWPORT_ITEMS_SPACE_WIDTH, (this->scoreInfoViewport.h - this->scoreText.getHeight()) / 2); this->playAgainText.setRenderer(this->g_Renderer); this->playAgainText.LoadFromRenderedText("PRESS SPACE TO PLAY AGAIN!", this->g_Font); this->projectileSrcRect = { Game::PLAYER_WIDTH, Game::INVADER_HEIGHT, Game::PROJECTILE_WIDTH, Game::PROJECTILE_HEIGHT }; }
/* Loading */ bool HUD::load(Viewport *viewport) { // HUD Weapon int x = viewport->getLeft() + viewport->getWidth() - MARGIN_WEAPON - WEAPON_ELEMENT_SIZE/2; int y = viewport->getTop() - MARGIN_WEAPON - WEAPON_ELEMENT_SIZE/2; weaponUsed = GameObject(x, y, GameData::SINGLESHOTWEAPON_SPRITE_INDEX, WEAPON_ELEMENT_SIZE, WEAPON_ELEMENT_SIZE, false, HUD_DEPTH); x = viewport->getLeft() + viewport->getWidth() - MARGIN_WEAPONHUD - WEAPONHUD_ELEMENT_SIZE/2; y = viewport->getTop() - MARGIN_WEAPONHUD - WEAPONHUD_ELEMENT_SIZE/2; weaponHUD = GameObject(x, y, GameData::WEAPONHUD_SPRITE_INDEX, WEAPONHUD_ELEMENT_SIZE, WEAPONHUD_ELEMENT_SIZE, false, HUD_DEPTH); currentType = SINGLE_SHOT; // HUD Life x = viewport->getLeft() + MARGIN_LIFE + LIFE_ELEMENT_SIZE/2; y = viewport->getTop() - MARGIN_LIFE - LIFE_ELEMENT_SIZE/2; playerLife = std::vector<GameObject>(MAX_LIFE); for (unsigned i = 0; i < MAX_LIFE; i++) { playerLife[i] = GameObject(x + i*LIFE_ELEMENT_SIZE, y, GameData::LIFEHUD_SPRITE_INDEX, LIFE_ELEMENT_SIZE, LIFE_ELEMENT_SIZE, false, HUD_DEPTH); } return true; }
Character::Character(): Player(){ animationIndex = 0; leftArm = GameObject("ghost_arm_left", "ghost_arm_right_texture"); leftArm.setPosition(1.2f, -0.5f, 0.0f); leftArm.rotationNode->setAxis(glm::vec3(1.0f, 0.0f, 0.0f)); leftArm.setDirection(10.0f); StaticGameObject flashLight("flash_light", "flash_light_texture"); flashLight.setPosition(0.8f, -0.7f, 1.8f); leftArm.rotationNode->addChildNode(flashLight.getSceneGraphBranch()); rightArm = GameObject("ghost_arm_right", "ghost_arm_right_texture"); rightArm.setPosition(-1.2f, -0.5f, 0.0f); rightArm.rotationNode->setAxis(glm::vec3(1.0f, 0.0f, 0.0f)); StaticGameObject pickAxe("pick_axe", "pick_axe_texture"); pickAxe.setPosition(-0.6f, 0.0f, 1.8f); pickAxe.setRotation(0.0f, 20.0f); rightArm.rotationNode->addChildNode(pickAxe.getSceneGraphBranch()); head.rotationNode->addChildNode(leftArm.getSceneGraphBranch()); head.rotationNode->addChildNode(rightArm.getSceneGraphBranch()); light = new LightSource(flashLight.modelNode); light->setPosition(0,0,1.0f); //light->setDirection(0,-0.2f,1); light->setColor(0.9f, 0.8f, 0.7f); light->setIntensity(170); light->setSpread(32); leftArm.update(0.0f); rightArm.update(0.0f); //pickAxe.update(0.0f); }
void SkillSpiderMine::internActivationPoint(const Vector3& target) { //if (target->GetFaction() == owner->GetFaction()) //{ // return false; //} GameObject* go = TIKI_NEW GameObject(engine); go->PRS.SPosition() = owner->Pos3D() + Vector3(5); gameState->GetBotFactory()->CreatePlayerSpiderMine(go, target); //return true; }
void Game::step(units::MS dt) { creation_countdown_ -= dt; if (creation_countdown_ <= 0) { game_objects_.push_back(GameObject(ground_plane_, cube_mesh_, shaders_)); creation_countdown_ = 1500 + rand() % 250; } for (auto& game_object : game_objects_) { game_object.step(dt, ground_plane_, game_objects_); if (game_object.captured()) continue; if (camera_.bounding_sphere().collides(game_object.bounding_sphere())) { game_object.onCameraCollision(); ++score_; } } }
void UserView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { qDebug() << "Cursor Pos = " << QCursor :: pos(); qDebug() << "WidgetAt = " << QApplication::widgetAt(QCursor :: pos())->objectName(); scenka->addItem(event->pos(), new MapObject(TreeObject())); } if (event->button() == Qt::RightButton) { qDebug() << QCursor :: pos(); qDebug() << QApplication::widgetAt(QCursor :: pos())->objectName(); scenka->addItem(event->pos(), new MapObject(GameObject())); } }
void GameLevel::init(std::vector<std::vector<GLuint>> tileData, GLuint levelWidth, GLuint levelHeight) { // Calculate dimensions if (tileData.size() == 0) { return; } GLuint height = static_cast<GLuint>(tileData.size()); GLuint width = static_cast<GLuint>(tileData[0].size()); // Note we can index vector at [0] since this function is only called if height > 0 GLfloat unit_width = levelWidth / static_cast<GLfloat>(width); GLfloat unit_height = levelHeight / static_cast<GLfloat>(height); // Initialize level tiles based on tileData for (GLuint y = 0; y < height; ++y) { for (GLuint x = 0; x < width; ++x) { // Check block type from level data (2D level array) if (tileData[y][x] == 1) // Solid { glm::vec2 pos(unit_width * x, unit_height * y); glm::vec2 size(unit_width, unit_height); GameObject obj(pos, size, ResourceManager::GetTexture("block_solid"), glm::vec3(0.8f, 0.8f, 0.7f)); obj.IsSolid = GL_TRUE; this->Bricks.push_back(obj); } else if (tileData[y][x] > 1) // Non-solid; now determine its color based on level data { glm::vec3 color = glm::vec3(1.0f); // original: white if (tileData[y][x] == 2) color = glm::vec3(0.2f, 0.6f, 1.0f); else if (tileData[y][x] == 3) color = glm::vec3(0.0f, 0.7f, 0.0f); else if (tileData[y][x] == 4) color = glm::vec3(0.8f, 0.8f, 0.4f); else if (tileData[y][x] == 5) color = glm::vec3(1.0f, 0.5f, 0.0f); glm::vec2 pos(unit_width * x, unit_height * y); glm::vec2 size(unit_width, unit_height); this->Bricks.push_back(GameObject(pos, size, ResourceManager::GetTexture("block"), color)); } } } }
void PlayerShip::ProcessPhysicsControls() { btRigidBody *body = GameObject()->Rigidbody()->Body(); if (!body) return; body->setActivationState(DISABLE_DEACTIVATION); body->setDamping(0.9, 0.95); float moveKoef = _currentSpeed; btVector3 moveForce = btVector3(0,0,-moveKoef); btVector3 torqueForce = btVector3(-_stickerControl.y, -_stickerControl.x, -_rollControl * 1.5); torqueForce *= 15; torqueForce = body->getWorldTransform().getBasis() * torqueForce; body->applyCentralForce(body->getWorldTransform().getBasis() * moveForce); body->applyTorque(torqueForce); }
/* Updating */ void HUD::update(GameData *data, Viewport *viewport, int life, WeaponType weaponType) { // Player Life for (unsigned int i = 0; i < playerLife.size(); i++) { playerLife[i].update(data); // Position int x = viewport->getLeft() + MARGIN_LIFE + LIFE_ELEMENT_SIZE/2; int y = viewport->getTop() - MARGIN_LIFE - LIFE_ELEMENT_SIZE/2; playerLife[i].setX(x + i*LIFE_ELEMENT_SIZE); playerLife[i].setY(y); // Action if (life > (int)i) playerLife[i].setAction(STATIC_UP); // STATIC_UP = Heart full else playerLife[i].setAction(STATIC_DOWN); // STATIC_DOWN = Heart empty } // Weapon used if (currentType != weaponType) { currentType = weaponType; int spriteIndex; switch (currentType) { case SINGLE_SHOT: spriteIndex = GameData::SINGLESHOTWEAPON_SPRITE_INDEX; break; case THREE_SHOTS: spriteIndex = GameData::THREESHOTWEAPON_SPRITE_INDEX; break; case FIVE_SHOTS: spriteIndex = GameData::FIVESHOTWEAPON_SPRITE_INDEX; break; case FLAMETHROWER: spriteIndex = GameData::FLAMETHROWER_SPRITE_INDEX; break; default: break; } weaponUsed = GameObject(0, 0, spriteIndex, WEAPON_ELEMENT_SIZE, WEAPON_ELEMENT_SIZE, false, HUD_DEPTH); } weaponUsed.update(data); weaponHUD.update(data); weaponUsed.setAction(STATIC_UP); weaponHUD.setAction(STATIC_UP); int x = viewport->getLeft() + viewport->getWidth() - MARGIN_WEAPON - WEAPON_ELEMENT_SIZE/2; int y = viewport->getTop() - MARGIN_WEAPON - WEAPON_ELEMENT_SIZE/2; weaponUsed.setX(x); weaponUsed.setY(y); x = viewport->getLeft() + viewport->getWidth() - MARGIN_WEAPONHUD - WEAPONHUD_ELEMENT_SIZE/2; y = viewport->getTop() - MARGIN_WEAPONHUD - WEAPONHUD_ELEMENT_SIZE/2; weaponHUD.setX(x); weaponHUD.setY(y); }
//Randomises rock shape and color void RocksShapeAndColor() { if (frameCounter % rockSpawnInterval == 0) { int x = rand() % WindowWidth; //Rocks in defferent shapes int shapeNum = rand() % 7; switch (shapeNum) { case 0: rockSymbol = static_cast<char>(177); break; case 1: rockSymbol = static_cast<char>(176); break; case 2: rockSymbol = static_cast<char>(219); break; case 3: rockSymbol = static_cast<char>(220); break; case 4: rockSymbol = static_cast<char>(222); break; case 5: rockSymbol = static_cast<char>(178); break; case 6: rockSymbol = static_cast<char>(254); break; } stoneCounter++; rocks.push_back(GameObject(x, 0, rockSymbol)); if (stoneCounter == 2) { rocks[0].Color = colour; } //It makes stones colorful randomAccess_iterator rock = rocks.end() - 1; switch (shapeNum) { case 0: rock->Color = ConsoleColors::Green; break; case 1: rock->Color = ConsoleColors::Red; break; case 2: rock->Color = ConsoleColors::Blue; break; case 3: rock->Color = ConsoleColors::Grey; break; case 4: rock->Color = ConsoleColors::Yellow; break; case 5: rock->Color = ConsoleColors::Purple; break; case 6: rock->Color = ConsoleColors::Cyan; break; } colour = rock->Color; } }
/** \brief Fills an array of GameObjects with those described in a file. * \param filename The filename of the configuration file to load. * \param objects The array of GameObjects to be written to. */ void GameObject::loadConfigFile(std::string filename, GameObject *objects) { int index; bool threed; float locx, locy, locz, orx, ory, orz; bool show; float scale; std::string id; std::ifstream file(filename.c_str()); //reads each game object into the objects array while(file >> index) { file >> threed >> locx >> locy >> locz >> orx >> ory >> orz >> filename >> show >> scale; objects[index] = GameObject(filename, irr::core::vector3df(locx, locy, locz), irr::core::vector3df(orx, ory, orz), irr::core::vector3df(scale, scale,scale), show); } }
std::shared_ptr<Accessory> ObjectFactory::createAccessory(TemplateAccessory &accessoryTemplate, RarityType &rarityType){ double spellPower = engine::magicSpellPowerMax * accessoryTemplate.spellPowerFromMax * rarityType.improvementMultiplier * engine::random.variationMultiplier(engine::statisticVariation); std::shared_ptr<Accessory> accessory = std::shared_ptr<Accessory>(new Accessory( Item(engine::raritySystem.getAccessoryMod(rarityType), GameObject( accessoryTemplate.name, accessoryTemplate.type, accessoryTemplate.glyph), accessoryTemplate.weightKg), spellPower )); //rarity color accessory->glyph.fgColor = accessory->glyph.fgColor * rarityType.color; return accessory; }
Map::Map(const GameObject & gameObject, std::string fileName) :GameObject(gameObject),schedule(new Schedule()) { std::ifstream cityFile(fileName); if (cityFile.is_open()) { while (!cityFile.eof()) { std::string textureName, cityName, connectionsListFile, productsFileName; Vector2 pos, size; cityFile >> pos >> size >> textureName >> cityName >> connectionsListFile >> productsFileName; try { mapElements.push_back(new City(MapElement(GameObject(pos, size, 0, Textures::getTexture(textureName)), cityName, connectionsListFile), productsFileName)); } catch (GameError & gameError) { gameError.generateErrorLog(errorFile); } } } else throw GameError(fileName + ":file not found(Cities)");
GameObject* Scene::addGameObject(const std::string nameP) { gameObjects.push_back(GameObject(nameP)); return &gameObjects.back(); }
GameObject* Scene::addGameObject() { GameObject go = GameObject(); gameObjects.push_back(go); return &gameObjects.back(); }
bool ResourceManager::loadScene(std::string fileName) { // Check if file exists std::ifstream fin(fileName.c_str()); if(!fin.fail()) { fin.close(); } else { std::cout << "File: " << fileName << " could not be loaded." << std::endl; return false; } scene = importer.ReadFile( fileName, aiProcessPreset_TargetRealtime_Quality); size_t pos = fileName.find_last_of("."); std::string sType = fileName.substr(pos); // If the import failed, report it if( !scene) { std::cout << "Scene import failed." << std::endl; return false; } std::cout << "Assimp meshes: " << scene->mNumMeshes << std::endl; std::cout << "Assimp vertices: " << scene->mMeshes[0]->mNumVertices << std::endl; if(scene->mMeshes[0]->HasNormals()) std::cout << "Assimp normals present" << std::endl; std::cout << "Assimp faces: " << scene->mMeshes[0]->mNumFaces << std::endl; std::cout << "Assimp tcoords: " << scene->mMeshes[0]->mTextureCoords << std::endl; std::cout << "Material index: " << scene->mMeshes[0]->mMaterialIndex << std::endl; std::cout << "Number of materials: " << scene->mNumMaterials << std::endl; textures_.reserve(scene->mNumMaterials); for(unsigned k(0); k < scene->mNumMaterials; ++k) { aiMaterial *mat = scene->mMaterials[k]; aiString name; mat->Get(AI_MATKEY_NAME,name); std::cout << "Material name: " << name.C_Str() << std::endl; std::cout << "Number of textures: " << mat->GetTextureCount(aiTextureType_DIFFUSE) << std::endl; aiString path; if(mat->GetTexture(aiTextureType_DIFFUSE, 0, &path, nullptr, nullptr, nullptr, nullptr, nullptr) == AI_SUCCESS) { std::cout << "Texture path: " << path.C_Str() << std::endl; std::cout << "Texture path: " << sType << std::endl; std::string texName; if(sType == ".dae") { std::string dir("../../textures/"); std::string basename(path.C_Str()); texName = std::string(dir + basename); } else { texName = std::string(path.C_Str()); } Texture tex; tex.createTextureFromImage(i3dTexType::i3d_tex_diffuse_map, texName); textures_.push_back(std::move(tex)); } else { std::cout << "Default Texture path: " << std::endl; std::string texName("../../textures/greyhalf.png"); Texture tex; tex.createTextureFromImage(i3dTexType::i3d_tex_diffuse_map, texName); textures_.push_back(std::move(tex)); } float specularExponent; if(mat->Get(AI_MATKEY_SHININESS, specularExponent) == AI_SUCCESS) { specularExponent = 40.0f; std::cout << "Specular Exponent: " << specularExponent << std::endl; } else { specularExponent = 20.0f; std::cout << "Specular Exponent: " << specularExponent << std::endl; } float specularIntensity; if(mat->Get(AI_MATKEY_SHININESS_STRENGTH, specularIntensity) == AI_SUCCESS) std::cout << "Specular Intensity: " << specularIntensity << std::endl; else { specularIntensity = 0.8f; std::cout << "Specular Intensity: " << specularIntensity << std::endl; } aiVector3D col_diffuse; float diffuseIntensity(0.0f); if(mat->Get(AI_MATKEY_COLOR_DIFFUSE, col_diffuse) == AI_SUCCESS) { std::cout << "Diffuse color: " << col_diffuse.x << std::endl; } else { diffuseIntensity = 1.0f; } PhongMaterial phong; phong.specularIntensity_ = specularIntensity; phong.specularExponent_ = specularExponent; phong.diffuseIntensity_ = 0.8f; phong.textures_.push_back(&(textures_.back())); materials_.push_back(phong); } meshObjects_.reserve(scene->mNumMeshes); for(unsigned k(0); k < scene->mNumMeshes; ++k) { gameObjects_.push_back(GameObject()); GameObject &go = gameObjects_.back(); meshObjects_.push_back(Mesh()); Mesh &meshObj = meshObjects_.back(); go.meshObject_ = &meshObj; meshObj.polygonMode_ = GL_FILL; meshObj.texFormat_ = tCoordFormat::i3d_format_assimp; meshObj.model_.meshes_.push_back(Mesh3D()); Mesh3D &mesh = meshObj.model_.meshes_.front(); unsigned numVerts = scene->mMeshes[k]->mNumFaces * 3; mesh.vertices_.reserve(numVerts); if(scene->mMeshes[k]->HasNormals()) mesh.vertexNormals_.reserve(numVerts); mesh.texCoords_.reserve(numVerts); std::cout << "Loading mesh with: " << numVerts << " vertices." << std::endl; std::cout << "Loading " << scene->mMeshes[k]->mName.C_Str() << "." << std::endl; if(scene->mMeshes[k]->mMaterialIndex < scene->mNumMaterials) { meshObj.hasTexture_ = true; go.material_ = &materials_[scene->mMeshes[k]->mMaterialIndex]; } unsigned count = 0; if(scene->mMeshes[k]->mFaces[0].mNumIndices > 3) { std::cerr << "Cannot handle faces with more than 3 vertices: file: " << __FILE__ << " line: " << __LINE__ << std::endl; std::exit(EXIT_FAILURE); } for(unsigned i(0); i < scene->mMeshes[k]->mNumFaces; ++i) { const aiFace &face = scene->mMeshes[k]->mFaces[i]; int vi[3]; int ti[3]; for(unsigned j(0); j < 3; ++j) { aiVector3D p = scene->mMeshes[k]->mVertices[face.mIndices[j]]; aiVector3D n = scene->mMeshes[k]->mNormals[face.mIndices[j]]; aiVector3D t = scene->mMeshes[k]->mTextureCoords[0][face.mIndices[j]]; mesh.vertices_.push_back(Vec3(p.x,p.z,p.y)); if(scene->mMeshes[k]->HasNormals()) mesh.vertexNormals_.push_back(Vec3(n.x,n.z,n.y)); mesh.texCoords_.push_back(Vec2(t.x,t.y)); vi[j] = count; ti[j] = count; count++; } mesh.faces_.push_back(TriFace(vi, ti)); //std::cout << "face: " << vi[0] << " " << vi[1] << " " << vi[2] << std::endl; } meshObj.transform_.translation_ = i3d::Vec4(0.f, 0.0f, 0.f, 0.f); meshObj.transform_.setRotationEuler(i3d::Vec3(0.0f, 0.0f, 0.0f)); meshObj.initRender(); } // We're done. Everything will be cleaned up by the importer destructor return true; }
bool Component::DispatchEvent(Event *event, int dispatchType) { return GameObject()->DispatchEvent(event, (EventDispatchType)dispatchType); }