Room *RoomLoader::loadRoom(const std::string& filename) { TileMap* tileMap = loadTileMap(filename); std::cout << "Loading room " + filename + "..."; std::vector<std::string> data = tokenize(loadFile(filename), "\n", true); std::vector<std::string> tileSetInfo = tokenize(data[data.size()-1], " "); if (tileSetInfo.size() == 0) { throw DB_EXCEPTION("Tilset info is missing in file " + filename); } std::string tileSetFileName = "graphics/" + tileSetInfo[0]; int numTiles = fromString<int>(tileSetInfo[1]); Room* room = new Room(tileMap, new Animation(tileSetFileName, numTiles)); int width = 0; int height = 0; int row; int col; // Load entities int x = 0; int y = 0; for (row = 0; row < tileMap->getHeight(); row++) { for (col = 0; col < tileMap->getWidth(); col++) { char c = data[row].at(col); // Ignore solidities. if (c != '.' && c != '#') { Entity* entity = createEntity(c, x * TileMap::TILE_SIZE, y * TileMap::TILE_SIZE, Random::get()); room->addEntity(entity); } x++; } x = 0; y++; } std::cout << " Done!" << std::endl; return room; }
//------------------------------------------------------------------------------- // conversion to Events (for compatibility with EventExtraction web service) Events* EventTemplateData:: convertToEvents(const AnnotationData* annotationData) const { Events* events=new Events(); int eventNum=1; for (std::vector<EventTemplate>::const_iterator it= begin(); it!= end();it++) { const map<string,EventTemplateElement>& templateElements=(*it).getTemplateElements(); if (! templateElements.empty()) { // one event per template Event* event=new Event(); // only one paragraph per event EventParagraph* eventPar=new EventParagraph(); event->push_back(eventPar); /*if ((*it).isMainEvent()) { event->setMain(); } event->setWeight((*it).getWeight());*/ eventPar->setId(eventNum); // set position and length of paragraph using position and length of template elements uint64_t posBeginPar(ULONG_MAX); uint64_t posEndPar(0); for(map<string,EventTemplateElement>::const_iterator it1= templateElements.begin(); it1!= templateElements.end();it1++) { const LinguisticAnalysisStructure::AnalysisGraph* graph=(*it1).second.getGraph(); LinguisticGraphVertex v=(*it1).second.getVertex(); MediaticData::EntityType type=(*it1).second.getType(); Entity* e=createEntity(graph, v, annotationData, (*it1).first, eventNum); if (e->getPosition() < posBeginPar) { posBeginPar=e->getPosition(); } uint64_t posEnd=e->getPosition()+e->getLength(); if (posEnd > posEndPar) { posEndPar=posEnd; } if (e!=0) { eventPar->addEntity(type,e); } } eventPar->setPosition(posBeginPar); eventPar->setLength(posEndPar-posBeginPar); events->push_back(event); eventNum++; } } return events; }
int entity_addRINT(const char * name){ entity_count++; for(; entity_arrayfirstopen < entity_arraysize && entity_list[entity_arrayfirstopen].type; entity_arrayfirstopen++); if(entity_arrayfirstopen == entity_arraysize){ //resize entity_arraysize++; entity_list = realloc(entity_list, entity_arraysize * sizeof(entity_t)); } entity_list[entity_arrayfirstopen] = createEntity(name); int returnid = (entity_count << 16) | entity_arrayfirstopen; entity_list[entity_arrayfirstopen].myid = returnid; addToHashTable(entity_list[entity_arrayfirstopen].name, returnid, entityhashtable); if(entity_arraylasttaken < entity_arrayfirstopen) entity_arraylasttaken = entity_arrayfirstopen; //todo redo if(returnid == 0) printf("yes, i can\n"); return returnid; }
void MapReader::onBeginEntity(const size_t line, const Model::EntityAttribute::List& attributes, const ExtraAttributes& extraAttributes) { const EntityType type = entityType(attributes); switch (type) { case EntityType_Layer: createLayer(line, attributes, extraAttributes); break; case EntityType_Group: createGroup(line, attributes, extraAttributes); break; case EntityType_Worldspawn: m_brushParent = onWorldspawn(attributes, extraAttributes); break; case EntityType_Default: createEntity(line, attributes, extraAttributes); break; } }
// 从配置文件创建游戏对象 Entity* ECSManager::createEntity(const std::string& filename) { auto data=(ComData*)Resource::getInstance()->addResource(filename,ComData::_TYPE); if (data!=nullptr) { rapidjson::Value& root=data->data; if (!root.IsNull()&&root.Size()>0) { Entity* entity=createEntity(); CCLOG("Created Entity: %d with filename: %s",entity->getId(),filename.c_str()); int count=root.Size(); for (int i=0; i<count; i++) { rapidjson::Value& comValue=root[i]; if (!comValue.IsNull()) { const char* type= root[i]["type"].GetString(); auto iter=__unuseComs.find(type); if (iter!=__unuseComs.end()) { Com* Com=iter->second->cloneEmpty(); //在lua中,不能直接将rapidjson作为参数,所以直接传入json字符串在lua中自行解析 if (Com->_isCustom) { //auto custom=(CustomCom*)Com; rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); comValue.Accept(writer); Com->initWithJson(buffer.GetString()); } else { Com->initWithMap(comValue); } addComToEntity(Com, entity); } } } //增持其引用计数 entity->setComData(data); return entity; } } return nullptr; }
EntityWrapper EntityManagerWrapper::createEntityF(const std::string& entity_name) { luabridge::LuaRef handle = global.scriptManager.getGlobal(entity_name); EntityWrapper entity = createEntity(); entity.setProperty("tableName", entity_name); entity.setProperty("type", handle["type"]); if (handle["GraphicsComponent"]) m_addGraphicsComponent(entity.getEntity(), handle["GraphicsComponent"]); if (handle["PhysicsComponent"]) m_addPhysicsComponent(entity.getEntity(), handle["PhysicsComponent"]); if (handle["AnimationComponent"]) m_addAnimationComponent(entity.getEntity(), handle["AnimationComponent"]); return entity; }
Entity* View::initialSight(const RootEntity& gent) { Entity* ent = createEntity(gent); assert(m_contents.count(gent->getId()) == 0); m_contents[gent->getId()] = ent; ent->init(gent, false); InitialSightEntity.emit(ent); NotifySightMap::iterator it = m_notifySights.find(gent->getId()); if (it != m_notifySights.end()) { it->second.emit(ent); m_notifySights.erase(it); } return ent; }
int main() { auto baseManager = BaseManager_t::factory(); auto ent2 = baseManager->createEntity(); baseManager->addTag<TEnemy>(ent2); baseManager->addComponent<Location>(ent2) = { 32321.232132f, 235.21321f }; auto LoadedDLL = LoadLibrary(L"ExternallLoadedDLL"); assert(LoadedDLL); using funcType = void(*)(const std::shared_ptr<BaseManager_t>&); funcType func = reinterpret_cast<funcType>(GetProcAddress(LoadedDLL, "RUN")); assert(func); func(baseManager); std::cin.get(); }
void TestScene12::runOgre() { // initialize framework & open window Ogre::Root* root = new Ogre::Root(); root->restoreConfig(); root->initialise(false); auto window = root->createRenderWindow("Ogre RenderWindow", 800, 600, false); auto sceneMgr = root->createSceneManager(Ogre::ST_GENERIC); // adjust camera auto cam1 = sceneMgr->createCamera("cam1"); auto camNode1 = sceneMgr->getRootSceneNode()->createChildSceneNode("camnode1"); cam1->setNearClipDistance(5); camNode1->attachObject(cam1); camNode1->setPosition(Ogre::Vector3(100, 100, 100)); camNode1->lookAt(Ogre::Vector3(-1, -1, -1), Ogre::Node::TS_LOCAL); window->addViewport(cam1); // load & integrate model root->addResourceLocation("./resources/Ogre", "FileSystem"); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); Mesh_Cube M(1); M.createMesh("cube"); Ogre::SceneNode* groups[ROWS]; std::list<Ogre::SceneNode*> nodes; for (int i = 0; i < ROWS; i++) { groups[i] = sceneMgr->getRootSceneNode()->createChildSceneNode(); nodes.push_back(groups[i]); } for (int i = 0; i < ROWS * COLS; i++) { auto node = groups[i % ROWS]->createChildSceneNode(); node->attachObject(sceneMgr->createEntity(std::string("model") + boost::lexical_cast<std::string>(i), "cube")); node->setPosition( camNode1->getOrientation() * -Ogre::Vector3::UNIT_X * LEFT(i) + camNode1->getOrientation() * Ogre::Vector3::UNIT_Y * UP(i) ); } root->addFrameListener(new MoveObjectTask_Ogre12(nodes)); // loop runOgreLoop(root); }
GameObject EntityFactory::createRandomEntity(int min_level, int max_level) const { int obj_lvl = 0; int picked = 0; bool ignore = false; //creates based on depth do { ignore = false; picked = rand() % entity_list_.size(); // Ignore entities with ignore flag in xml. if (iml::GetAttribute(*entity_list_[picked], "ignore", 0) == 1) { ignore = true; continue; } IMLNode *stats = entity_list_[picked]->findByName("stats"); obj_lvl = iml::GetAttribute(*stats, "level", 0); } while (ignore || obj_lvl < min_level || obj_lvl > max_level); return createEntity(entity_list_[picked]->getName()); }
void TestSceneManager3::populate() { // Build the vertex array using the lowest toplevel voxel per corner. Note, we're // leaving in vertex duplication so each voxel can have its own normals and tex-coords. // This will increase our sene complexity, but give us more control, as well. std::vector<Vector3> vertsArray; std::vector<Vector2> coordsArray; for (int x = 0; x < _world->getWidth(); x++) { for (int y = 0; y < _world->getHeight(); y++) { #define ADD_VECTOR(xOff, yOff) do { \ vertsArray.push_back(getVectorForCorner(x + xOff, y + yOff)); \ coordsArray.push_back(Vector2(xOff, yOff)); \ } while (0) // Bottom left triangle. ADD_VECTOR(0, 0); ADD_VECTOR(1, 0); ADD_VECTOR(0, 1); // Top right triangle. ADD_VECTOR(0, 1); ADD_VECTOR(1, 0); ADD_VECTOR(1, 1); #undef ADD_VECTOR } } // Calculate normals for each of the vertices. Vector3 *verts = new Vector3[vertsArray.size()]; Vector3 *norms = new Vector3[vertsArray.size()]; for (int i = 0; i < vertsArray.size(); i+=3) { Vector3 one = vertsArray[i+1] - vertsArray[i+0]; Vector3 two = vertsArray[i+2] - vertsArray[i+1]; Vector3 normal = one.crossProduct(two); normal.normalize(); for (int j = 0; j < 3; j++) { verts[i+j] = vertsArray[i+j]; norms[i+j] = normal; } } Entity *entity = createEntity(new WorldEntity(verts, norms, vector_to_array(coordsArray), vertsArray.size()), "world"); entity->setMaterial(_materialManager->getOrLoadResource("grass")); getRootNode()->attach(entity); }
//----------------------------------------------------------------------- void SceneDecoratorExtern::_notifyStart (void) { // Scale the node if (!mSubnode && mParentTechnique->getParentSystem()) { std::stringstream ss; ss << this; String sceneNodeName = "ParticleUniverse" + ss.str() + StringConverter::toString(mCount++); Ogre::SceneNode* sceneNode = mParentTechnique->getParentSystem()->getParentSceneNode(); mSubnode = sceneNode->createChildSceneNode(sceneNodeName); } if (!mEntity) { createEntity(); mSubnode->attachObject(mEntity); } mSubnode->setScale(mScale); mSubnode->setPosition(mPosition); }
entity_t * entity_addRPOINT(const char * name){ entity_count++; for(; entity_arrayfirstopen < entity_arraysize && entity_list[entity_arrayfirstopen].type; entity_arrayfirstopen++); if(entity_arrayfirstopen == entity_arraysize){ //resize entity_arraysize++; entity_list = realloc(entity_list, entity_arraysize * sizeof(entity_t)); } entity_list[entity_arrayfirstopen] = createEntity(name); int returnid = (entity_count << 16) | entity_arrayfirstopen; entity_list[entity_arrayfirstopen].myid = returnid; addToHashTable(entity_list[entity_arrayfirstopen].name, returnid, entityhashtable); //todo maybe have entity have a hash variable, so i dont have to calculate it again if i want to delete... maybe if(entity_arraylasttaken < entity_arrayfirstopen) entity_arraylasttaken = entity_arrayfirstopen; // printf("entity_arraysize = %i\n", entity_arraysize); // printf("entity_count = %i\n", entity_count); if(entity_list[entity_arrayfirstopen].myid == 0) printf("yes, i can\n"); return &entity_list[entity_arrayfirstopen]; }
//! //! //! \return True, if successful loading of ogre mesh //! False, otherwise. //! bool Model2SceneNode::loadMesh () { // destroy an existing OGRE entity for the mesh destroyEntity(); QString filename = getStringValue("Geometry File"); if (filename == "") { Log::debug(QString("Geometry file has not been set yet. (\"%1\")").arg(m_name), "Model2SceneNode::loadMesh"); return false; } // check if the file exists if (!QFile::exists(filename)) { Log::error(QString("Mesh file \"%1\" not found.").arg(filename), "Model2SceneNode::loadMesh"); return false; } // split the absolute filename to path and base filename int lastSlashIndex = filename.lastIndexOf('/'); QString path = ""; if (lastSlashIndex > -1) { path = filename.mid(0, lastSlashIndex); filename = filename.mid(lastSlashIndex + 1); } if (!filename.endsWith(".mesh")) { Log::error("The geometry file has to be an OGRE mesh file.", "Model2SceneNode::loadMesh"); return false; } // destroy old resource group and generate new one QString resourceGroupName = QString::fromStdString(createUniqueName("ResourceGroup_" + filename + "_Model2SceneNode")); OgreTools::destroyResourceGroup(m_oldResourceGroupName); m_oldResourceGroupName = resourceGroupName; OgreTools::createResourceGroup(resourceGroupName, path); // recreating the entity createEntity(m_name, filename); Log::info(QString("Mesh file \"%1\" loaded.").arg(filename), "Model2SceneNode::loadMesh"); return true; }
light *createDynamicLight(int x, int y, character *actor) { light *_c, *_p_c; _c = calloc(1, sizeof(light)); _c->entityId = createEntity(getWorld()); _c->x = x; _c->y = y; _c->r_tint = 55; _c->g_tint = 50; _c->b_tint = 35; _c->fuelMax = 70; _c->fuel = _c->fuelMax; _c->flickerRate = .5; _c->brightness = .45; _c->noTint = 0; _c->owner = actor; _c->size = 8; _c->sizeMod = 1.f; _c->prev = NULL; _c->next = NULL; _c->fov = copyLevelMap(); _c->lightMap = copyLevelMap(); if (DYNAMIC_LIGHTS == NULL) { DYNAMIC_LIGHTS = _c; } else { _p_c = DYNAMIC_LIGHTS; while (_p_c->next) { _p_c = _p_c->next; } _p_c->next = _c; _c->prev = _p_c; } return _c; }
/** newSceneObj **/ entity_t *createSceneObj(FILE *inFP, scene_t *scene, char *type, int code) { entity_t *ent; /* Pointer to new entity_t */ sobj_t *sobj; /* Pointer to new sobj_t */ pixel_t white = {255, 255, 255}; /* Default color */ intensity_t zero = {0, 0, 0}; /* Default diffuse/reflect values */ /* create new sceneObject structure */ ent = createEntity(inFP, type, code); sobj = (sobj_t *) malloc(sizeof(sobj_t)); assert(sobj != NULL); ent->entDerived = sobj; /* Set default values for a shape */ sobj->color = white; sobj->diffuse = zero; sobj->reflective = zero; sobj->magic = SCENEOBJ_T; loadSceneObj(inFP, ent); completeSceneObj(scene, ent); return(ent); }
unsigned int createStar(World *world, char *name, double x, double y, double z, double dx, double dy, double dz, double mass, double radius, double luminosity) { unsigned int entity = createEntity(world); world->mask[entity] = STAR_MASK; strcpy(world->name[entity].name, name); world->position[entity].position[0] = x; world->position[entity].position[1] = y; world->position[entity].position[2] = z; world->velocity[entity].velocity[0] = dx; world->velocity[entity].velocity[1] = dy; world->velocity[entity].velocity[2] = dz; world->mass[entity].mass = mass; world->radius[entity].radius = radius; world->luminosity[entity].luminosity = luminosity; return entity; }
void ListEntityDialog::actionTriggered(QAction *action) { switch (static_cast<ActionId>(action->data().toInt())) { case Create: { createEntity(); break; } case Remove: { removeEntity(currentIndex()); break; } case AddProperty: { break; } case RemoveProperty: { break; } } }
//Funcion que realizar el parse del fichero tmx bool CParserTile::parserFile(const std::string &filename) { BaseSubsystems::Log::Debug("Nombre del fichero a parsear "+filename); pugi::xml_document doc; const char *file = filename.c_str(); pugi::xml_parse_result result = doc.load_file(file); assert(result && "Error al cargar el fichero tmx del escenario"); //Leo las caracteristicas generales del mapa (dimensiones, propiedades) #pragma region CaracteristicasMapa int width = doc.first_child().attribute("width").as_float(); int height = doc.first_child().attribute("height").as_float(); #pragma endregion #pragma region Lectura de los atributos de los tiles pugi::xml_object_range<pugi::xml_named_node_iterator> atributos = doc.first_child().first_child().children("tile"); pugi::xml_object_range<pugi::xml_named_node_iterator>::const_iterator itAtributos = atributos.begin(); //Si hay tiles con atributos if(itAtributos != atributos.end()) { pugi::xml_object_range<pugi::xml_named_node_iterator> properties = (*itAtributos).first_child().children("property"); pugi::xml_object_range<pugi::xml_named_node_iterator>::const_iterator itProperties = properties.begin(); //Declaracion de variables antes de un for int id = 0; std::string name = ""; std::string valor =""; std::map<std::string, std::string> atributo; //Leemos los tiles que contengan atributos for(; itAtributos != atributos.end(); ++itAtributos) { //Leemos el id del tile que contenga atributo. Le sumo 1, por que en el xml me lo resta id = itAtributos->attribute("id").as_int()+1; //Obtenemos los atributos del tile en cuestion properties = (*itAtributos).first_child().children("property"); //Los recorremos for(itProperties = properties.begin(); itProperties != properties.end(); ++itProperties) { //Nombre del atributo name = (*itProperties).attribute("name").as_string(); //Su valor valor = (*itProperties).attribute("value").as_string(); //Lo inserto en el map correspondiente al tile atributo.insert(std::make_pair(name,valor)); } _atributosMap.insert(std::make_pair(id, atributo)); //Lo limpio para usarlo de nuevo en la siguiente iteracion atributo.clear(); } } #pragma endregion //Leo todas las capas y las almaceno en un map. Cada capa contiene una matriz que contiene los ids de los tiles que la conforman, ademas de otras caracteristicas #pragma region Capas //CAPAS pugi::xml_object_range<pugi::xml_named_node_iterator> capas = doc.first_child().children("layer"); pugi::xml_object_range<pugi::xml_named_node_iterator>::const_iterator itCapas = capas.begin(); pugi::xml_object_range<pugi::xml_named_node_iterator>::const_iterator endCapas = capas.end(); //Guardo sitio para la matriz entityList, de manera que me guarda [width][height] espacios para almacenar Map::CEntity* TMatriz matriz2(height, std::vector<Map::CEntity*>(width)); TMatrizMatriz matriz3(2, matriz2); _entityList = matriz3; int numeroCapa = 0; for(; itCapas != endCapas; ++itCapas, ++numeroCapa) { capa[numeroCapa] = new Capa(); //Nombre de la capa capa[numeroCapa]->name = itCapas->attribute("name").as_string(); //RELLENO LA MATRIZ DE CADA UNA DE LAS CAPAS CON LOS IDS DE LOS TILES QUE LA CONFORMAN pugi::xml_node nodoData = itCapas->child("data"); pugi::xml_object_range<pugi::xml_named_node_iterator> idTiles = nodoData.children("tile"); pugi::xml_object_range<pugi::xml_named_node_iterator>::const_iterator itidTiles = idTiles.begin(); pugi::xml_object_range<pugi::xml_named_node_iterator>::const_iterator endidTiles = idTiles.end(); //Creamos la matriz para almcenar los ids y entityInfos con el tamaño del mapa typedef std::vector<std::vector<std::pair<int,CEntity*>>> Matriz; Matriz matri(height,std::vector<std::pair<int,CEntity*>>(width)); //Dado que no he inicializado la matriz de la capa cuando la he definido, la inicializo ahora igualandola a la recien creada capa[numeroCapa]->matriz = matri; //RELLENO LA MATRIZ #pragma region Relleno de la matriz for(int i=0; i < height; ++i) { for(int j=0; j < width; ++j, ++itidTiles) { assert(itidTiles!=endidTiles); capa[numeroCapa]->matriz[i][j].first = itidTiles->attribute("gid").as_int();//Almaceno el id del tile if(capa[numeroCapa]->matriz[i][j].first != 0) { //CREAMOS EL ENTITYINFO ASOCIADO AL TILE TipoCapa tipocapa = TipoCapa(numeroCapa); createEntity(capa[numeroCapa]->matriz[i][j].first, //ID tipocapa, //numero de capa j, // pos X -i, //pos Y la posicion es negativa para ir construyendo los bloques en orden std::to_string(numeroCapa) + std::to_string(i)+ '_'+ std::to_string(j) + '_'// nombre ); } } } #pragma endregion } #pragma endregion #pragma region Crear puertas //Dado que una puerta esta formada por 4 tiles, creo una matriz de dimensiones 1 por cada grupo de puertas y 4 porque son 4 tiles TMatriz matrix(_doorMap.size()/4, std::vector<Map::CEntity*>(4)); _doorList = matrix; createDoorEntity(TipoTile::DOOR_HORIZONTAL_TRIGGER); createDoorEntity(TipoTile::DOOR_VERTICAL_DER_TRIGGER); createDoorEntity(TipoTile::DOOR_VERTICAL_IZQ_TRIGGER); #pragma endregion return true; }
void bossControllerUpdate(Controller* c, Entity* e, Iwbtg* iw, float dt) { ControllerBoss* b = &c->boss; if(b->triggered) { if(!b->initialized) { b->initialized = true; // Take the first action in the queue if(!bossIsActionQueueEmpty(b)) { b->actionQueue[0].initialized = false; bossAddActiveAction(b, &b->actionQueue[0]); } } for(int i = 0; i < MAX_ACTIONS_PER_BOSS; ++i) { BossAction* a = b->activeActions[i]; if(a == 0) continue; a->time += dt; switch(a->type) { case BossActionType_wait: if(a->time > a->wait.time) bossRemoveActiveAction(b, a); break; case BossActionType_move: if(!a->initialized) { a->move.start = e->position; a->initialized = true; } e->position = vector2fLerp(a->move.start, a->move.destination, inOutEase(clamp(a->time / a->move.time, 0, 1))); if(a->time >= a->move.time) bossRemoveActiveAction(b, a); break; case BossActionType_projectileBurst: { BossActionProjectileBurst* pb = &a->projectileBurst; if(!a->initialized) pb->shotTimer = 0; pb->shotTimer += dt; // TODO: do something a little smarter here so that // if two shots occur on the same frame, their positions // are correctly seperated from each other. if(pb->shotTimer > pb->interval) { soundPlay(assetsGetSound(&iw->game, "bossShoot"), 0.2); while(pb->shotTimer > pb->interval) { for(int i = 0; i < pb->count; ++i) { Entity* p = createEntity(iw, pb->projectileEntityType, e->position.x + (e->sprite.size.x / 2), e->position.y + (e->sprite.size.y / 2)); p->position.x -= (p->sprite.size.x / 2); p->position.y -= (p->sprite.size.y / 2); p->velocity = speedDirectionToVector2f(pb->speed, pb->direction + ((360 / pb->count) * i)); } pb->direction += pb->rotation; pb->shotTimer -= pb->interval; } } if(a->time > pb->interval * pb->repeat) bossRemoveActiveAction(b, a); } break; case BossActionType_playMusic: musicPlay(a->playMusic.music, 0.7, &iw->game); bossRemoveActiveAction(b, a); break; case BossActionType_projectileRandomSpray: if(a->time > a->projectileRandomSpray.time) bossRemoveActiveAction(b, a); BossActionProjectileRandomSpray* pb = &a->projectileRandomSpray; Entity* p = createEntity(iw, pb->projectileEntityType, e->position.x + (e->sprite.size.x / 2), e->position.y + (e->sprite.size.y / 2)); p->position.x -= (p->sprite.size.x / 2); p->position.y -= (p->sprite.size.y / 2); pb->previousDirection += (12 * 7); //pb->previousDirection = (randomfBetween(0, 360)); p->velocity = speedDirectionToVector2f(pb->speed, pb->previousDirection + randomfBetween(-12, 12)); pb->soundCounter++; if(pb->soundCounter > 1) { pb->soundCounter = 0; soundPlay(assetsGetSound(&iw->game, "bossShoot"), 0.1); } break; case BossActionType_projectileAimed: { BossActionProjectileAimed* pa = &a->projectileAimed; Entity* p = createEntity(iw, pa->projectileEntityType, e->position.x + (e->sprite.size.x / 2), e->position.y + (e->sprite.size.y / 2)); p->position.x -= (p->sprite.size.x / 2); p->position.y -= (p->sprite.size.y / 2); float direction = vector2fDirection( vector2fAdd(e->position, v2f(e->sprite.size.x / 2, e->sprite.size.y / 2)), vector2fAdd(iw->player.position, v2f(16, 16))) * (180 / PI); p->velocity = speedDirectionToVector2f(pa->speed, direction); soundPlay(assetsGetSound(&iw->game, "bossShoot"), 0.1); bossRemoveActiveAction(b, a); } break; default: bossRemoveActiveAction(b, a); printf("Warning: Tried to perform boss action that has not been implemented!\n"); break; } if(!a->initialized) a->initialized = true; } // TODO: Make this into a loop so multiple actions can start per frame. if(!bossIsActionBlocking(b) && iw->state != GameState_gameOver) bossNextAction(b); if(b->health <= 0) { if(iw->boss == e) iw->boss = 0; createEntity(iw, EntityType_warp, 480 - 64, 540 - 256); musicPlayOnce(assetsGetMusic(&iw->game, "bossDefeatedMusic"), 0.7, &iw->game); destroyEntity(e); } } }
void MapView::createTerrain() { unsigned int sizeX = mMap->getTerrainSize().x; unsigned int sizeZ = mMap->getTerrainSize().z; mTileX = 33; mTileZ = 33; unsigned int tileCount = ((sizeX - 1) / (mTileX - 1)) * ((sizeZ - 1) / (mTileZ - 1)); unsigned int vertexPerTile = mTileX * mTileZ; unsigned int trianglesPerTile = (mTileX - 1) * (mTileZ - 1) * 2; mMeshes.resize(tileCount); mEntities.resize(tileCount); mSceneNodes.resize(tileCount); // vertexPerTile * 3 vertices * 2 texture coordinates * 3 colours * 3 normals VertexVector vertices(vertexPerTile * 11); // trianglesPerTile * 3 indices per each triangle IndexVector indices[3] = { IndexVector(trianglesPerTile * 3 ), IndexVector(trianglesPerTile * 3 / 4), IndexVector(trianglesPerTile * 3 / 8) }; unsigned int vertexIndex, indexIndex = 0, tileIndex = 0; for (unsigned int zIndex = 0; zIndex < mTileZ - 1; ++zIndex) { for (unsigned int xIndex = 0; xIndex < mTileX - 1; ++xIndex) { indices[0][indexIndex++] = zIndex * mTileX + xIndex; indices[0][indexIndex++] = (zIndex + 1) * mTileX + xIndex; indices[0][indexIndex++] = zIndex * mTileX + xIndex + 1; indices[0][indexIndex++] = (zIndex + 1) * mTileX + xIndex; indices[0][indexIndex++] = (zIndex + 1) * mTileX + xIndex + 1; indices[0][indexIndex++] = zIndex * mTileX + xIndex + 1; } } indexIndex = 0; for (unsigned int zIndex = 0; zIndex < mTileZ - 1; zIndex += 2) { for (unsigned int xIndex = 0; xIndex < mTileX - 1; xIndex += 2) { indices[1][indexIndex++] = zIndex * mTileX + xIndex; indices[1][indexIndex++] = (zIndex + 2) * mTileX + xIndex; indices[1][indexIndex++] = zIndex * mTileX + xIndex + 2; indices[1][indexIndex++] = (zIndex + 2) * mTileX + xIndex; indices[1][indexIndex++] = (zIndex + 2) * mTileX + xIndex + 2; indices[1][indexIndex++] = zIndex * mTileX + xIndex + 2; } } indexIndex = 0; for (unsigned int zIndex = 0; zIndex < mTileZ - 1; zIndex += 4) { for (unsigned int xIndex = 0; xIndex < mTileX - 1; xIndex += 4) { indices[2][indexIndex++] = zIndex * mTileX + xIndex; indices[2][indexIndex++] = (zIndex + 4) * mTileX + xIndex; indices[2][indexIndex++] = zIndex * mTileX + xIndex + 4; indices[2][indexIndex++] = (zIndex + 4) * mTileX + xIndex; indices[2][indexIndex++] = (zIndex + 4) * mTileX + xIndex + 4; indices[2][indexIndex++] = zIndex * mTileX + xIndex + 4; } } float scaleX = mMap->getSize().x / (float)(sizeX - 1); float scaleZ = mMap->getSize().z / (float)(sizeZ - 1); for (unsigned int zTile = 0; zTile < (sizeZ - 1); zTile += (mTileZ - 1)) { for (unsigned int xTile = 0; xTile < (sizeX - 1); xTile += (mTileX - 1)) { vertexIndex = 0; for (unsigned int zVertex = zTile; zVertex < zTile + mTileZ; ++zVertex) { for (unsigned int xVertex = xTile; xVertex < xTile + mTileX; ++xVertex) { float yVertex = mMap->getTerrainData()[zVertex * sizeX + xVertex]; vertices[vertexIndex++] = (float)xVertex * scaleX; vertices[vertexIndex++] = (float)yVertex; vertices[vertexIndex++] = (float)zVertex * scaleZ; vertices[vertexIndex++] = (float)xVertex / (float)(sizeX - 1); vertices[vertexIndex++] = (float)zVertex / (float)(sizeZ - 1); vertices[vertexIndex++] = 1.0f; vertices[vertexIndex++] = 1.0f; vertices[vertexIndex++] = 1.0f; vertices[vertexIndex++] = 0.0f; vertices[vertexIndex++] = 1.0f; vertices[vertexIndex++] = 0.0f; } } std::string name = "MapView_" + Convert::ToString(mID) + "_Tile_" + Convert::ToString(tileIndex); // Create mesh. mMeshes[tileIndex] = Ogre::MeshManager::getSingleton().createManual( name, "General").get(); // Create one submesh. Ogre::SubMesh* subMesh = mMeshes[tileIndex]->createSubMesh(); // Create vertex data structure for vertices shared between submeshes. mMeshes[tileIndex]->sharedVertexData = new Ogre::VertexData(); mMeshes[tileIndex]->sharedVertexData->vertexCount = vertexPerTile; // Create declaration (memory format) of vertex data. Ogre::VertexDeclaration* decl = mMeshes[tileIndex]->sharedVertexData->vertexDeclaration; size_t offset = 0; // 1st buffer decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); decl->addElement(0, offset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES); offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT2); decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_DIFFUSE); offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); decl->addElement(0, offset, Ogre::VET_FLOAT3, Ogre::VES_NORMAL); offset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); // Allocate vertex buffer of the requested number of vertices (vertexPerTile) // and bytes per vertex (offset). Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( offset, vertexPerTile, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); // Upload the vertex data to the card vbuf->writeData(0, vbuf->getSizeInBytes(), &(vertices.front()), true); // Set vertex buffer binding so buffer 0 is bound to our vertex buffer. Ogre::VertexBufferBinding* bind = mMeshes[tileIndex]->sharedVertexData->vertexBufferBinding; bind->setBinding(0, vbuf); // Allocate index buffer of the requested number of vertices . Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton(). createIndexBuffer( Ogre::HardwareIndexBuffer::IT_16BIT, trianglesPerTile * 3, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); // Upload the index data to the card. ibuf->writeData(0, ibuf->getSizeInBytes(), &(indices[0].front()), true); /// Set parameters of the submesh subMesh->useSharedVertices = true; subMesh->indexData->indexBuffer = ibuf; subMesh->indexData->indexCount = indices[0].size(); subMesh->indexData->indexStart = 0; subMesh->setMaterialName("terrain"); float xMin = vertices[0]; float yMin = vertices[1]; float zMin = vertices[2]; float xMax = vertices[0]; float yMax = vertices[1]; float zMax = vertices[2]; for (unsigned int i = 0; i < vertexPerTile * 11; i += 11) { if (vertices[i ] < xMin) xMin = vertices[i ]; else if (vertices[i ] > xMax) xMax = vertices[i ]; if (vertices[i + 1] < yMin) yMin = vertices[i + 1]; else if (vertices[i + 1] > yMax) yMax = vertices[i + 1]; if (vertices[i + 2] < zMin) zMin = vertices[i + 2]; else if (vertices[i + 2] > zMax) zMax = vertices[i + 2]; } // Set bounding information (for culling). mMeshes[tileIndex]->_setBounds(Ogre::AxisAlignedBox(xMin, yMin, zMin, xMax, yMax, zMax)); mMeshes[tileIndex]->_setBoundingSphereRadius(1.0f); // Notify Mesh object that it has been loaded. mMeshes[tileIndex]->load(); // Create entity. mEntities[tileIndex] = createEntity(name, name); mEntities[tileIndex]->setCastShadows(false); mEntities[tileIndex]->setUserAny(Ogre::Any(this)); // Create scene node. mSceneNodes[tileIndex] = createSceneNode(); mSceneNodes[tileIndex]->attachObject(mEntities[tileIndex]); // Advance to next tile. tileIndex++; } } }
void RigidControlet::rebuildEntity(){ destroyEntity(); createEntity(); }
AcBr::ErrorStatus selectEntityByType(AcBrEntity*& pEnt, AcDb::SubentType& subType) { Acad::ErrorStatus acadReturnValue = Acad::eOk; AcBr::ErrorStatus returnValue = AcBr::eOk; // Query validation level AcBr::ValidationLevel vlevel = validationLevel(); // Query the subentity type subType = subtype(); // Query whether to select a database entity or create a new one Adesk::Boolean context = (subType != AcDb::kNullSubentType) ? Adesk::kFalse : localContext(); if (!context) { // Query the subentity by AutoCAD pick and get the subentity path AcDbFullSubentPath subPath(kNullSubent); acadReturnValue = selectEntity(subType, subPath); if (acadReturnValue != Acad::eOk) { acutPrintf(ACRX_T("\n Error in selectEntity: %d"), acadReturnValue); return (AcBr::ErrorStatus)acadReturnValue; } // Call the appropriate subentity constructor switch (subType) { case AcDb::kNullSubentType: pEnt = new AcBrBrep(); break; case AcDb::kFaceSubentType: pEnt = new AcBrFace(); break; case AcDb::kEdgeSubentType: pEnt = new AcBrEdge(); break; default: acutPrintf(ACRX_T("\n selectEntityByType: unsupported subentity type: %d\n"), subType); returnValue = (AcBr::ErrorStatus)Acad::eWrongSubentityType; return returnValue; } if (pEnt == NULL) { acutPrintf(ACRX_T("\n selectEntityByType: unable to allocate memory\n")); returnValue = (AcBr::ErrorStatus)Acad::eOutOfMemory; return returnValue; } returnValue = pEnt->set(subPath); if (returnValue != AcBr::eOk) { acutPrintf(ACRX_T("\n Error in AcBrEntity::set:")); errorReport(returnValue); return returnValue; } } else { // Create the entity as a local object AcDbEntity* pEntity; acadReturnValue = createEntity(pEntity); if (acadReturnValue != Acad::eOk) { acutPrintf(ACRX_T("\n Error in createEntity: %d"), acadReturnValue); return (AcBr::ErrorStatus)acadReturnValue; } if (pEntity == NULL) { acutPrintf(ACRX_T("\n selectEntityByType: unable to allocate memory\n")); returnValue = (AcBr::ErrorStatus)Acad::eOutOfMemory; return returnValue; } pEnt = new AcBrBrep(); if (pEnt == NULL) { acutPrintf(ACRX_T("\n selectEntityByType: unable to allocate memory\n")); returnValue = (AcBr::ErrorStatus)Acad::eOutOfMemory; return returnValue; } returnValue = ((AcBrBrep*)pEnt)->set((const AcDbEntity&)*pEntity); if (returnValue != AcBr::eOk) { acutPrintf(ACRX_T("\n Error in AcBrEntity::set:")); errorReport(returnValue); return returnValue; } } returnValue = pEnt->setValidationLevel(vlevel); if (returnValue != AcBr::eOk) { acutPrintf(ACRX_T("\n Error in AcBrEntity::setValidationLevel:")); errorReport(returnValue); return returnValue; } return returnValue; }
Entity* EntityManager::createEntity(WorldPacket& packet) { Entity* entity = createEntity(); if (!entity) return 0; PropertySetComp* propSet = entity->getComponent<PropertySetComp>(ComponentBase::PropertySet); UnitInterfComp* unitInterf = entity->getComponent<UnitInterfComp>(ComponentBase::UnitInterf); // 设置基本属性 propSet->initialize(PLAYER_END); propSet->setUintValue(OBJECT_FIELD_GUID, m_hiCharGuid++); propSet->setUintValue(OBJECT_FIELD_GUID + 1, HIGHGUID_PLAYER); propSet->setUintValue(OBJECT_FIELD_TYPE, Entity::Type_Object | Entity::Type_Unit | Entity::Type_Player); packet >> entity->m_entityName; // ***TODO*** 出生地需要根据种族和职业来查表 unitInterf->map(0); unitInterf->posX(-8921.41f); unitInterf->posY(-118.494f); unitInterf->posZ(82.273f); unitInterf->orientation(0); propSet->setFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 0.388999998569489f); propSet->setFloatValue(UNIT_FIELD_COMBATREACH, 1.5f); // 种族和职业 u_char race, cls, gender; packet >> race >> cls >> gender; // ***TODO*** 模型ID, 暂时先固定一个, 人类男性 propSet->setUintValue(UNIT_FIELD_DISPLAYID, 49); propSet->setUintValue(UNIT_FIELD_NATIVEDISPLAYID, 49); propSet->setUintValue(UNIT_FIELD_FACTIONTEMPLATE, 1); // ***TODO*** 需要查表 u_char powerType = 1; u_int unitfield = 0x00110000; propSet->setUintValue(UNIT_FIELD_BYTES_0, (race | (cls << 8) | (gender << 16) | (powerType << 24))); propSet->setUintValue(UNIT_FIELD_BYTES_1, unitfield); propSet->setUintValue(UNIT_FIELD_BYTES_2, (0x28 << 8)); // players - 0x2800, 0x2801, units - 0x1001 propSet->setUintValue(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN1); propSet->setFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); propSet->setFloatValue(OBJECT_FIELD_SCALE_X, 1.0f); // 5项基本属性 for (int i = STAT_STRENGTH; i < STATS_MAX; ++i) { propSet->setUintValue(UNIT_FIELD_STAT0 + i, 20); propSet->setFloatValue(UNIT_FIELD_POSSTAT0 + i, 0.0f); propSet->setFloatValue(UNIT_FIELD_NEGSTAT0 + i, 0.0f); } // ***TODO*** 生命值, 查表或配置 propSet->setUintValue(UNIT_FIELD_BASE_HEALTH, 100); propSet->setUintValue(UNIT_FIELD_BASE_MANA, 0); propSet->setUintValue(UNIT_FIELD_MAXHEALTH, 100); propSet->setUintValue(UNIT_FIELD_MAXPOWER1, 0); propSet->setUintValue(UNIT_FIELD_MAXPOWER2, 1000); propSet->setUintValue(UNIT_FIELD_MAXPOWER3, 0); propSet->setUintValue(UNIT_FIELD_MAXPOWER4, 100); propSet->setUintValue(UNIT_FIELD_MAXPOWER5, 0); u_char skin,face,hairStyle,hairColor,facialHair,outfitId; packet >> skin >> face; packet >> hairStyle >> hairColor >> facialHair >> outfitId; propSet->setUintValue(PLAYER_FIELD_WATCHED_FACTION_INDEX, u_int(-1)); propSet->setUintValue(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24))); propSet->setUintValue(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24))); propSet->setUintValue(PLAYER_BYTES_3, gender); // ***TODO*** 新建的角色都为1级, 改为可配置的 propSet->setUintValue(UNIT_FIELD_LEVEL, 1); propSet->setUintValue(PLAYER_FIELD_MAX_LEVEL, 70); propSet->setUintValue(PLAYER_NEXT_LEVEL_XP, 100); propSet->setUintValue(UNIT_FIELD_RESISTANCES, 40); propSet->setUintValue(PLAYER_FIELD_MOD_HEALING_DONE_POS, 0); for (int i = 0; i < 7; ++i) { propSet->setUintValue(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG + i, 0); propSet->setUintValue(PLAYER_FIELD_MOD_DAMAGE_DONE_POS + i, 0); propSet->setFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT + i, 1.0f); } propSet->setFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f); propSet->setFloatValue(UNIT_FIELD_OFFHANDATTACKTIME, 2000.0f); propSet->setFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f); propSet->setUintValue(PLAYER_CHARACTER_POINTS2, 2); return entity; }
int main(int argc, char *argv[]) { pthread_t recvThread; srand(time(NULL)); GameState gamestate; SDL_Window *window=NULL; // Declare a window SDL_Renderer *renderer=NULL; // Declare a renderer Entity tempEntity; SDL_Init(SDL_INIT_EVERYTHING); // Initialize SDL2 //srandom((int)time(NULL)); //Create an application window with the following settings: window = SDL_CreateWindow("Game Window", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position SCREEN_WIDTH, // width, in pixels SCREEN_HEIGHT, // height, in pixels 0 // flags ); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); gamestate.renderer=renderer; SDL_Rect cameraScene= {0,0,SCREEN_WIDTH,SCREEN_HEIGHT}; gamestate.nrOfAi=0; loadMedia(&gamestate); ///load images to textures // The window is open: enter program loop (see SDL_PollEvent) /**Event loop*/ int done = 0; // NEDANSTÅENDE SKA BLI EN FUNKTION SOM LIGGER I GAMENET // TODO GÖR 96x96 for(int i = 0;i<100;i++) // initializera ai token listan gamestate.aiEntityToken[i]=0; //Event loop while(1){ for(int i = 0;i<100;i++) // initializera ai token listan gamestate.aiEntityToken[i]=0; threadJoinQuerry = 0; startMenu(renderer,&gamestate); gamestate.castle=createEntity(&tempEntity,896,508,96,96,500.0); while(!done) ///main game loop { for(int i=0;i<maxPlayers;i++){ if(gamestate.playerEntityToken[i]!=0){ gamestate.playerEntity[i].mPosX=getAIPositionX(&gamestate.playerEntity[i]); /// get last mainplayers position gamestate.playerEntity[i].mPosY=getAIPositionY(&gamestate.playerEntity[i]); //coPlayerControll(&gamestate.playerEntity[i]); } } for(int i=0;i<=highestId;i++){ if(gamestate.aiEntityToken[i]!=0){ if(gamestate.AiEntity[i].hpData.currentHp <= 0){ gamestate.aiEntityToken[i] = 0; } } } for(int i=0;i<=highestId;i++){ gamestate.AiEntity[i].mPosX=getAIPositionX(&gamestate.AiEntity[i]); ///AI data gamestate.AiEntity[i].mPosY=getAIPositionY(&gamestate.AiEntity[i]); AITTick(&gamestate.AiEntity[i]); /// AI changes position and checks collision if(gamestate.aiEntityToken[i]!=0){ if(checkIFObjectHit(&gamestate.playerEntity[gamestate.mySlot].attack, &gamestate.AiEntity[i].object.rect)){//Kollar om spelarens attack kolliderar med AIn giveDamage(&gamestate,i); resetAttack(&gamestate.playerEntity[gamestate.mySlot].attack); } } } done = processEvents(window, &gamestate); cameraScene.x=(getmPosX(&gamestate.playerEntity[gamestate.mySlot])+ 20/2)-SCREEN_WIDTH/2; cameraScene.y=(getmPosY(&gamestate.playerEntity[gamestate.mySlot])+20/2)-SCREEN_HEIGHT/2; if( cameraScene.x < 0 ) /// cameraScren follows main player { cameraScene.x = 0; } if( cameraScene.y < 0 ) { cameraScene.y = 0; } if( cameraScene.x > LEVEL_WIDTH - cameraScene.w ) { cameraScene.x = LEVEL_WIDTH - cameraScene.w; } if( cameraScene.y > LEVEL_HEIGHT - cameraScene.h ) { cameraScene.y = LEVEL_HEIGHT - cameraScene.h; } //Render display doRender(renderer, &gamestate,cameraScene); /// renderer Ai , players and map //don't burn up the CPU //SDL_Delay(10); ///***************if players position x,y changes -> send to server***********/// if(getmPosX(&gamestate.playerEntity[gamestate.mySlot])!=gamestate.playerEntity[gamestate.mySlot].mPosX || getmPosY(&gamestate.playerEntity[gamestate.mySlot])!=gamestate.playerEntity[gamestate.mySlot].mPosY){ printf("Attempting to update player movement\n"); updatePlayerMovement(&gamestate); } ///*******'LOSS CONDITION*****//// if(gamestate.castle.hpData.currentHp<=0){ done=1; } } //TODO Rensa upp alla textures osv threadJoinQuerry = 1; pthread_join(recvThread,NULL); SDLNet_TCP_Close(gamestate.socket); lossMenu(renderer); } // Close and destroy the window SDL_DestroyTexture(gamestate.gTileTexture.mTexture); SDL_DestroyTexture(gamestate.mAiTexture); SDL_DestroyTexture(gamestate.playerEntity[0].object.mTexture); ///clear Textures SDL_DestroyTexture(gamestate.playerEntity[1].object.mTexture); SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); // Clean up SDL_Quit(); //pthread_join(recvThread,NULL); // close(gamestate.socket); return 0; }
void Game::load(bool init) { _map = sfutils::VMap::createMapFromFile(_mapFileName); if(_map == nullptr) throw std::runtime_error("Impossible to load file map"); _map->clear();//we just need the geometry here int initialGold = 0; std::vector<sf::Vector2i> spawns; { utils::json::Value* rootPtr = utils::json::Driver::parse_file(_mapFileName); utils::json::Object& root = *rootPtr; const utils::json::Object& size = root["size"]; const utils::json::Object& min = size["min"]; const utils::json::Object& max = size["max"]; _minCoord.x = min["x"].as_int(); _minCoord.y = min["y"].as_int(); _maxCoord.x = max["x"].as_int(); _maxCoord.y = max["y"].as_int(); const utils::json::Object& players = root["players"]; const utils::json::Array& spawn = players["spawn"]; for(const utils::json::Object& value : spawn) spawns.emplace_back(value["x"].as_int(),value["y"].as_int()); initialGold = players["gold"].as_int(); } if(init) { for(unsigned int i = 0; i<spawns.size();++i) { Team::type_ptr team(new Team(i,sf::Color(book::random(110,225), book::random(110,225), book::random(110,225) ), initialGold, this->as_type_ptr())); createEntity(spawns[i],team,book::makeAsMain); _teams.emplace_back(team); team->save(); } //add enemies for(unsigned int i=0; i<spawns.size();++i) { for(unsigned int j=0; j<spawns.size();++j) { if(i!=j) { _teams[i]->addEnemy(_teams[j]); } } } } systems.add<book::SysAIMain>(*this); systems.add<book::SysAIWarrior>(*this); systems.add<book::SysAIDefender>(*this); systems.add<book::SysAISpawner>(*this); systems.add<book::SysAIWalker>(*this); systems.add<book::SysAIFlyer>(*this); systems.add<book::SysHp>(*this); }
void Game::processNetworkEvents() { sf::Lock guard(_clientsMutex); for(auto it = _clients.begin(); it != _clients.end();++it) { book::Client* client = *it; book::packet::NetworkEvent* msg; while(client and client->pollEvent(msg)) { switch(msg->type()) { case book::FuncIds::IdDisconnected : { it = _clients.erase(it); --it; delete client; client = nullptr; }break; case book::FuncIds::IdLogOut : { it = _clients.erase(it); --it; client->getTeam()->remove(client); onLogOut(client); client = nullptr; }break; case book::FuncIds::IdRequestCreateEntity : { book::packet::RequestCreateEntity* event = static_cast<book::packet::RequestCreateEntity*>(msg); sf::Lock gameGuard(_teamMutex); short int entityType = event->getType(); int gold = client->getTeam()->getGold(); sf::Vector2i coord = event->getCoord(); for(book::EntityType::Info& info : book::EntityType::informations) { if(info.makeAs == entityType and gold >= info.cost and _byCoords[coord].size() == 0) { book::MakeAs makeAs = book::getMakeAs(info.makeAs); if(makeAs != nullptr) { createEntity(coord,client->getTeam(),makeAs); client->getTeam()->addGold(-info.cost); } } } }break; case book::FuncIds::IdRequestDestroyEntity : { book::packet::RequestDestroyEntity* event = static_cast<book::packet::RequestDestroyEntity*>(msg); unsigned int id = event->getId(); if(entities.isValid(id)) { sf::Lock gameGuard(_teamMutex); CompTeam::Handle team = entities.getComponent<CompTeam>(id); if(team.isValid()) { if(team->_team->id() == client->getTeam()->id()) { destroyEntity(id); } } } }break; default : break; } } } }
Entity createEntity(const Entity &entity) { std::shared_ptr<World> world = std::get<0>(entity)->children[std::get<1>(entity)]; return createEntity(world); }
//*********************************************************************** void SpecificEntitiesLoader::XMLHandler:: addSpecificEntity(AnalysisContent& analysis, LinguisticAnalysisStructure::AnalysisGraph* anagraph, const std::string& str, const std::string& type, uint64_t position, uint64_t length) { LOGINIT("LP::SpecificEntities"); LDEBUG << "loader: add entity " << str << "," << type << ",[" << position << "," << length << "]"; // create RecognizerMatch Automaton::RecognizerMatch match(anagraph); uint64_t posBegin=position; uint64_t posEnd=posBegin+length; // find vertices corresponding to pos/len : have to go through the graph LinguisticGraph* graph=anagraph->getGraph(); std::queue<LinguisticGraphVertex> toVisit; std::set<LinguisticGraphVertex> visited; LinguisticGraphOutEdgeIt outItr,outItrEnd; // output vertices between begin and end, toVisit.push(anagraph->firstVertex()); bool first=true; bool inEntity=false; while (!toVisit.empty()) { LinguisticGraphVertex v=toVisit.front(); toVisit.pop(); if (v == anagraph->lastVertex()) { break; } if (first) { first=false; } else if (inEntity) { LinguisticAnalysisStructure::Token* t=get(vertex_token,*graph,v); if (t->position() >= posEnd) { inEntity=false; break; // no need to go further } else { // OME?? valeur true?,"SE"? match.addBackVertex(v,true,"SE"); } } else { LinguisticAnalysisStructure::Token* t=get(vertex_token,*graph,v); if(t!=0) { if (t->position() == posBegin) { match.addBackVertex(v,true,"SE"); inEntity=true; } } } // add next vertices for (boost::tie(outItr,outItrEnd)=out_edges(v,*graph); outItr!=outItrEnd; outItr++) { LinguisticGraphVertex next=target(*outItr,*graph); if (visited.find(next)==visited.end()) { visited.insert(next); toVisit.push(next); } } } if (match.size()==0) { LWARN << "Warning: no matching vertices for given position/length"; } // set entity properties match.setType(Common::MediaticData::MediaticData::single().getEntityType(Common::Misc::utf8stdstring2limastring(type))); // set normalized form similar to string (otherwise, may cause problem when trying to access the created specific entity) match.features().addFeature(DEFAULT_ATTRIBUTE,Common::Misc::utf8stdstring2limastring(str)); // create specific entity from RecognizerMatch using default action CreateSpecificEntity createEntity(m_language); createEntity(match,analysis); }
Any Scene::load(const std::string& scene) { std::string filename; clear(); m_modelTable.clear(); m_name = scene; bool isFilename = endsWith(toLower(scene), ".scn.any") || endsWith(toLower(scene), ".Scene.Any"); if (isFilename) { filename = scene; } else { const std::string* f = filenameTable().getPointer(scene); if (f == NULL) { throw "No scene with name '" + scene + "' found in (" + stringJoin(filenameTable().getKeys(), ", ") + ")"; } filename = *f; } Any any; any.load(filename); { const std::string& n = any.get("name", filename); // Ensure that this name appears in the filename table if it does not already, // so that it can be loaded by name in the future. if (! filenameTable().containsKey(n)) { filenameTable().set(n, filename); } } m_sourceAny = any; // Load the lighting environment (do this before loading entities, since some of them may // be lights that will enter this array) bool hasEnvironmentMap = false; if (any.containsKey("localLightingEnvironment")) { m_localLightingEnvironment = any["localLightingEnvironment"]; hasEnvironmentMap = any["localLightingEnvironment"].containsKey("environmentMap"); } // Load the models if (any.containsKey("models")) { Any models = any["models"]; if (models.size() > 0) { for (Any::AnyTable::Iterator it = models.table().begin(); it.isValid(); ++it) { const std::string name = it->key; Any v = it->value; createModel(v, name); } } } // Instance the models if (any.containsKey("entities")) { Any entities = any["entities"]; if (entities.size() > 0) { for (Table<std::string, Any>::Iterator it = entities.table().begin(); it.isValid(); ++it) { const std::string& name = it->key; const std::string& entityType = it->value.name(); createEntity(entityType, name, it->value); } } } shared_ptr<Texture> skyboxTexture = Texture::whiteCube(); Any skyAny; // Use the environment map as a skybox if there isn't one already, and vice versa Array<shared_ptr<Skybox> > skyboxes; getTypedEntityArray<Skybox>(skyboxes); if ( skyboxes.size() == 0 ) { if (any.containsKey("skybox")) { createEntity("Skybox", "skybox", any["skybox"]); m_skybox = typedEntity<Skybox>("skybox"); } else if (hasEnvironmentMap) { m_skybox = Skybox::create("skybox", this, Array<ScaledTexture>(m_localLightingEnvironment.environmentMapArray[0]), Array<SimTime>(0.0), 0, SplineExtrapolationMode::CLAMP, false, false); insert(m_skybox); } else { m_skybox = Skybox::create("skybox", this, Array<ScaledTexture>(ScaledTexture(Texture::whiteCube(), 1.0f)), Array<SimTime>(0.0), 0, SplineExtrapolationMode::CLAMP, false, false); insert(m_skybox); } } if (any.containsKey("environmentMap")) { throw std::string("environmentMap field has been replaced with localLightingEnvironment"); } // Default to using the skybox as an environment map if none is specified. if (! hasEnvironmentMap) { m_localLightingEnvironment.environmentMapArray.append(ScaledTexture(m_skybox->keyframeArray()[0].texture, m_skybox->keyframeArray()[0].constant)); } ////////////////////////////////////////////////////// if (m_cameraArray.size() == 0) { // Create a default camera, back it up from the origin m_cameraArray.append(Camera::create("camera")); m_cameraArray.last()->setFrame(CFrame::fromXYZYPRDegrees(0,1,-5,0,-5)); } setTime(any.get("time", 0.0)); m_lastVisibleChangeTime = m_lastLightChangeTime = m_lastStructuralChangeTime = System::time(); m_defaultCameraName = (std::string)any.get("defaultCamera", ""); // Set the initial positions, repeating a few times to allow // objects defined relative to others to reach a fixed point for (int i = 0; i < 3; ++i) { for (int e = 0; e < m_entityArray.size(); ++e) { m_entityArray[e]->onSimulation(m_time, nan()); } } // Pose objects so that they have bounds. { Array< shared_ptr<Surface> > ignore; onPose(ignore); } return any; }