Esempio n. 1
0
int GModel::writeBDF(const std::string &name, int format, int elementTagType,
                     bool saveAll, double scalingFactor)
{
  FILE *fp = Fopen(name.c_str(), "w");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  if(noPhysicalGroups()) saveAll = true;

  indexMeshVertices(saveAll);

  fprintf(fp, "$ Created by Gmsh\n");

  std::vector<GEntity*> entities;
  getEntities(entities);

  // nodes
  for(unsigned int i = 0; i < entities.size(); i++)
    for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++)
      entities[i]->mesh_vertices[j]->writeBDF(fp, format, scalingFactor);

  // elements
  for(unsigned int i = 0; i < entities.size(); i++)
    for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++){
      int numPhys = entities[i]->physicals.size();
      if(saveAll || numPhys)
        entities[i]->getMeshElement(j)->writeBDF
          (fp, format, elementTagType, entities[i]->tag(),
           numPhys ? entities[i]->physicals[0] : 0);
    }

  fprintf(fp, "ENDDATA\n");

  fclose(fp);
  return 1;
}
Esempio n. 2
0
void PlayerInputSystem::update(double deltaTime)
{
	auto entities = getEntities();
	for(auto e : entities)
	{
		auto& playerComp = e.getComponent<PlayerComponent>();
		auto& velocity = e.getComponent<VelocityComponent>().velocity;
	
        bool shootKeyPressed = sf::Keyboard::isKeyPressed(playerComp.controls.shoot);


		if(sf::Keyboard::isKeyPressed(playerComp.controls.left))
		{
            std::cout << "Left key pressed\n";
            velocity.x = -playerComp.baseSpeed;
            setPlayerState(e, playerComp, shootKeyPressed ? PlayerComponent::State::MOVE_LEFT_SHOOT : PlayerComponent::State::MOVE_LEFT);
		}
		else if(sf::Keyboard::isKeyPressed(playerComp.controls.right))
		{
            std::cout << "Right key pressed\n";
            velocity.x = playerComp.baseSpeed;
            setPlayerState(e, playerComp, shootKeyPressed ? PlayerComponent::State::MOVE_RIGHT_SHOOT : PlayerComponent::State::MOVE_RIGHT);
		}
        else
        {
            velocity.x = 0;
            if(shootKeyPressed) 
            {
                std::cout << "Shoot key pressed\n";
                setPlayerState(e, playerComp, PlayerComponent::State::SHOOT);
            }
            else
            {
                setPlayerState(e, playerComp, PlayerComponent::State::DEFAULT_STATE); 
            }
        }
	}
}
Esempio n. 3
0
STDMETHODIMP_(HANDLE) CDataBase::FindNextContact(HANDLE hContact, const char* szProto)
{
	while (hContact) {
		DBCachedContact *VL = m_cache->GetCachedContact(hContact);
		if (VL == NULL)
			VL = m_cache->AddContactToCache(hContact);

		if (VL->hNext != NULL) {
			if (!szProto || CheckProto(VL->hNext, szProto))
				return VL->hNext;

			hContact = VL->hNext;
			continue;
		}

		VL->hNext = (HANDLE)getEntities().compNextContact((WPARAM)hContact);
		if (VL->hNext != NULL && (!szProto || CheckProto(VL->hNext, szProto)))
			return VL->hNext;

		hContact = VL->hNext;
	}
	return NULL;
}
Esempio n. 4
0
//public
void SliderSystem::process(float dt)
{
    auto& entities = getEntities();
    for (auto& entity : entities)
    {
        auto& slider = entity.getComponent<Slider>();
        if (slider.active)
        {
            auto& tx = entity.getComponent<xy::Transform>();
            auto movement = slider.target - tx.getPosition();

            if (xy::Util::Vector::lengthSquared(movement) > 10.f)
            {
                tx.move(movement * slider.speed * dt);
            }
            else
            {
                tx.setPosition(slider.target);
                slider.active = false;
            }
        }
    }
}
Esempio n. 5
0
STDMETHODIMP_(LONG) CDataBase::GetContactCount(void)
{
	TDBTEntityIterFilter f = {0,0,0,0};
	f.cbSize = sizeof(f);
	f.fDontHasFlags = DBT_NF_IsGroup | DBT_NF_IsVirtual | DBT_NF_IsAccount | DBT_NF_IsRoot;
	f.Options = DBT_NIFO_OSC_AC | DBT_NIFO_OC_AC;

	TDBTEntityIterationHandle hiter = DBEntityIterInit((WPARAM)&f, getEntities().getRootEntity());
	int c = 0;
	if ((hiter != 0) && (hiter != DBT_INVALIDPARAM))
	{
		TDBTEntityHandle con = DBEntityIterNext(hiter, 0);

		while ((con != DBT_INVALIDPARAM) && (con != 0))
		{
			if ((con != 0) && (con != DBT_INVALIDPARAM))
				c++;

			con = DBEntityIterNext(hiter, 0);
		}
		DBEntityIterClose(hiter, 0);
	}
	return c;
}
Esempio n. 6
0
void Render::render_entities(float camera_min_x,
    float camera_min_y,
    float camera_max_x,
    float camera_max_y,
    float camera_zoom)
{
    auto entities = getEntities();

    for (auto& entity : entities)
    {
        // No hasComponent check is needed since render system does filtering
        auto& texture_component =
            entity.getComponent<components::TextureComponent>();
        auto& transform_component =
            entity.getComponent<components::TransformComponent>();

        float x_center =
            camera_zoom * (-camera_min_x + transform_component.pos_x);
        float y_center =
            camera_zoom * (-camera_min_y + transform_component.pos_y);
        float w = camera_zoom * transform_component.size_x;
        float h = camera_zoom * transform_component.size_y;

        /* m_sp_logger->info("Entity transform results: world: X{} Y{} W{} H{}",
         */
        /*     transform_component.pos_x, */
        /*     transform_component.pos_y, */
        /*     transform_component.size_x, */
        /*     transform_component.size_y); */
        /* m_sp_logger->info("Entity transform results: camera: X{} Y{} W{}
         * H{}", */
        /*     x_center, */
        /*     y_center, */
        /*     w, */
        /*     h); */

        SDL_Rect dest_rect = {
            static_cast<int>(x_center - (w / 2.0f)),
            static_cast<int>(y_center - (h / 2.0f)),
            static_cast<int>(std::round(w)),
            static_cast<int>(std::round(h)),
        };
        SDL_RendererFlip flip = SDL_FLIP_NONE;
        if (transform_component.flip_vert)
        {
            flip = static_cast<SDL_RendererFlip>(
                static_cast<SDL_RendererFlip>(SDL_FLIP_VERTICAL) | flip);
        }
        if (transform_component.flip_horiz)
        {
            flip = static_cast<SDL_RendererFlip>(
                static_cast<SDL_RendererFlip>(SDL_FLIP_HORIZONTAL) | flip);
        }

        if (!texture_component.sp_texture)
        {
            texture_component.sp_texture =
                m_up_resourcemanager->get(texture_component.texture_path);
        }
        m_up_renderer->copy(*texture_component.sp_texture,
            nullptr,
            &dest_rect,
            static_cast<int>(transform_component.rotation),
            flip);

        if (m_render_collision && entity.hasComponent<components::Collision>())
        {
            auto& collision = entity.getComponent<components::Collision>();
            // TODO(Keegan, Use bounding box position as well)
            SDL_Rect dest_rect = {
                static_cast<int>(
                    x_center - (camera_zoom * collision.bounding_box.w / 2.0f)),
                static_cast<int>(
                    y_center - (camera_zoom * collision.bounding_box.h / 2.0f)),
                static_cast<int>(
                    std::round(collision.bounding_box.w * camera_zoom)),
                static_cast<int>(
                    std::round(collision.bounding_box.h * camera_zoom)),
            };
            m_up_renderer->set_draw_color(0, 255, 0, 128);
            m_up_renderer->fill_rect(&dest_rect);
        }
    }
}
Esempio n. 7
0
int GModel::writeMESH(const std::string &name, int elementTagType,
                      bool saveAll, double scalingFactor)
{
  FILE *fp = Fopen(name.c_str(), "w");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  if(noPhysicalGroups()) saveAll = true;

  int numVertices = indexMeshVertices(saveAll);

  fprintf(fp, " MeshVersionFormatted 2\n");
  fprintf(fp, " Dimension\n");
  fprintf(fp, " 3\n");

  fprintf(fp, " Vertices\n");
  fprintf(fp, " %d\n", numVertices);
  std::vector<GEntity*> entities;
  getEntities(entities);
  for(unsigned int i = 0; i < entities.size(); i++)
    for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++)
      entities[i]->mesh_vertices[j]->writeMESH(fp, scalingFactor);

  int numEdges = 0, numTriangles = 0, numQuadrangles = 0;
  int numTetrahedra = 0, numHexahedra = 0;
  for(eiter it = firstEdge(); it != lastEdge(); ++it){
    if(saveAll || (*it)->physicals.size()){
      numEdges += (*it)->lines.size();
    }
  }
  for(fiter it = firstFace(); it != lastFace(); ++it){
    if(saveAll || (*it)->physicals.size()){
      numTriangles += (*it)->triangles.size();
      numQuadrangles += (*it)->quadrangles.size();
    }
  }
  for(riter it = firstRegion(); it != lastRegion(); ++it){
    if(saveAll || (*it)->physicals.size()){
      numTetrahedra += (*it)->tetrahedra.size();
      numHexahedra += (*it)->hexahedra.size();
    }
  }

  if(numEdges){
    if(CTX::instance()->mesh.order == 2)
      fprintf(fp, " EdgesP2\n");
    else
      fprintf(fp, " Edges\n");
    fprintf(fp, " %d\n", numEdges);
    for(eiter it = firstEdge(); it != lastEdge(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->lines.size(); i++)
          (*it)->lines[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                     numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numTriangles){
    if(CTX::instance()->mesh.order == 2)
      fprintf(fp, " TrianglesP2\n");
    else
      fprintf(fp, " Triangles\n");
    fprintf(fp, " %d\n", numTriangles);
    for(fiter it = firstFace(); it != lastFace(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->triangles.size(); i++)
          (*it)->triangles[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                         numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numQuadrangles){
    fprintf(fp, " Quadrilaterals\n");
    fprintf(fp, " %d\n", numQuadrangles);
    for(fiter it = firstFace(); it != lastFace(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->quadrangles.size(); i++)
          (*it)->quadrangles[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                           numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numTetrahedra){
    if(CTX::instance()->mesh.order == 2)
      fprintf(fp, " TetrahedraP2\n");
    else
      fprintf(fp, " Tetrahedra\n");
    fprintf(fp, " %d\n", numTetrahedra);
    for(riter it = firstRegion(); it != lastRegion(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->tetrahedra.size(); i++)
          (*it)->tetrahedra[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                          numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }
  if(numHexahedra){
    fprintf(fp, " Hexahedra\n");
    fprintf(fp, " %d\n", numHexahedra);
    for(riter it = firstRegion(); it != lastRegion(); ++it){
      int numPhys = (*it)->physicals.size();
      if(saveAll || numPhys){
        for(unsigned int i = 0; i < (*it)->hexahedra.size(); i++)
          (*it)->hexahedra[i]->writeMESH(fp, elementTagType, (*it)->tag(),
                                         numPhys ? (*it)->physicals[0] : 0);
      }
    }
  }

  fprintf(fp, " End\n");

  fclose(fp);
  return 1;
}
Esempio n. 8
0
//public
void SpringFlowerSystem::process(float dt)
{
    auto& entities = getEntities();
    for (auto& entity : entities)
    {
        auto& flower = entity.getComponent<SpringFlower>();

        const auto& tx = entity.getComponent<xy::Transform>();

        //see who's moving past
        auto worldPos = tx.getTransform().transformPoint(flower.headPos);
        auto otherEnts = getScene()->getSystem<xy::QuadTree>().queryPoint(worldPos);
        for (auto other : otherEnts)
        {
            auto otherPos = other.getComponent<xy::Transform>().getPosition();
            if (std::abs(otherPos.x - worldPos.x) < 15.f)
            {
                auto amount = other.getComponent<xy::Transform>().getScale().x * -150.f;
                flower.externalForce.x += amount;
            }
        }

        
        //add wind (would look icer with noise but hey)
        flower.externalForce.x += (m_windTable[m_windIndex] + WindStrength) * m_windModulator[m_modulatorIndex];

        //F = -kx
        sf::Vector2f fSpring = flower.stiffness * ((flower.headPos - flower.rootPos) - flower.restPos);
        fSpring += flower.externalForce;
        flower.externalForce *= 0.9f;

        //- bv
        sf::Vector2f fDamp = flower.damping * flower.velocity;

        //a = f/m
        sf::Vector2f acceleration = (fSpring + fDamp) / flower.mass;

        flower.velocity += acceleration * dt;
        flower.headPos += flower.velocity * dt;
        

        //update vertices
        auto& verts = entity.getComponent<xy::Drawable>().getVertices();
        verts[0].position = flower.headPos;
        verts[0].position.x -= flower.textureRect.width / 2.f;
        verts[0].texCoords = { flower.textureRect.left, 0.f };
        verts[0].color = flower.colour;

        verts[1].position = verts[0].position;
        verts[1].position.x += flower.textureRect.width;
        verts[1].texCoords.x = flower.textureRect.left + flower.textureRect.width;
        verts[1].color = flower.colour;

        verts[2].position = flower.rootPos;
        verts[2].position.x += flower.textureRect.width / 2.f;
        verts[2].texCoords = { flower.textureRect.left + flower.textureRect.width, -flower.headPos.y };
        verts[2].color = flower.colour;

        verts[3].position = verts[2].position;
        verts[3].position.x -= flower.textureRect.width;
        verts[3].texCoords = { flower.textureRect.left,  -flower.headPos.y };
        verts[3].color = flower.colour;

        entity.getComponent<xy::Drawable>().updateLocalBounds();
    }

    //update this once per frame, not once per ent DUH
    m_windIndex = (m_windIndex + 1) % m_windTable.size();
    m_modulatorIndex = (m_modulatorIndex + 1) % m_windModulator.size();
}
Esempio n. 9
0
int GModel::readMED(const std::string &name)
{
  med_idt fid = MEDouvrir((char*)name.c_str(), MED_LECTURE);
  if(fid < 0) {
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  med_int v[3], vf[3];
  MEDversionDonner(&v[0], &v[1], &v[2]);
  MEDversionLire(fid, &vf[0], &vf[1], &vf[2]);
  Msg::Info("Reading MED file V%d.%d.%d using MED library V%d.%d.%d",
            vf[0], vf[1], vf[2], v[0], v[1], v[2]);
  if(vf[0] < 2 || (vf[0] == 2 && vf[1] < 2)){
    Msg::Error("Cannot read MED file older than V2.2");
    return 0;
  }

  std::vector<std::string> meshNames;
  for(int i = 0; i < MEDnMaa(fid); i++){
    char meshName[MED_TAILLE_NOM + 1], meshDesc[MED_TAILLE_DESC + 1];
    med_int spaceDim;
    med_maillage meshType;
#if (MED_MAJOR_NUM == 3)
    med_int meshDim, nStep;
    char dtUnit[MED_SNAME_SIZE + 1];
    char axisName[3 * MED_SNAME_SIZE + 1], axisUnit[3 * MED_SNAME_SIZE + 1];
    med_sorting_type sortingType;
    med_axis_type axisType;
    if(MEDmeshInfo(fid, i + 1, meshName, &spaceDim, &meshDim, &meshType, meshDesc,
                   dtUnit, &sortingType, &nStep, &axisType, axisName, axisUnit) < 0){
#else
    if(MEDmaaInfo(fid, i + 1, meshName, &spaceDim, &meshType, meshDesc) < 0){
#endif
      Msg::Error("Unable to read mesh information");
      return 0;
    }
    meshNames.push_back(meshName);
  }

  if(MEDfermer(fid) < 0){
    Msg::Error("Unable to close file '%s'", (char*)name.c_str());
    return 0;
  }

  int ret = 1;
  for(unsigned int i = 0; i < meshNames.size(); i++){
    // we use the filename as a kind of "partition" indicator, allowing to
    // complete a model part by part (used e.g. in DDM, since MED does not store
    // a partition index)
    GModel *m = findByName(meshNames[i], name);
    if(!m) m = new GModel(meshNames[i]);
    ret = m->readMED(name, i);
    if(!ret) return 0;
  }
  return ret;
}

int GModel::readMED(const std::string &name, int meshIndex)
{
  med_idt fid = MEDouvrir((char*)name.c_str(), MED_LECTURE);
  if(fid < 0){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  int numMeshes = MEDnMaa(fid);
  if(meshIndex >= numMeshes){
    Msg::Info("Could not find mesh %d in MED file", meshIndex);
    return 0;
  }

  checkPointMaxNumbers();
  GModel::setCurrent(this); // make sure we increment max nums in this model

  // read mesh info
  char meshName[MED_TAILLE_NOM + 1], meshDesc[MED_TAILLE_DESC + 1];
  med_int spaceDim, nStep = 1;
  med_maillage meshType;
#if (MED_MAJOR_NUM == 3)
  med_int meshDim;
  char dtUnit[MED_SNAME_SIZE + 1];
  char axisName[3 * MED_SNAME_SIZE + 1], axisUnit[3 * MED_SNAME_SIZE + 1];
  med_sorting_type sortingType;
  med_axis_type axisType;
  if(MEDmeshInfo(fid, meshIndex + 1, meshName, &spaceDim, &meshDim, &meshType, meshDesc,
                 dtUnit, &sortingType, &nStep, &axisType, axisName, axisUnit) < 0){
#else
  if(MEDmaaInfo(fid, meshIndex + 1, meshName, &spaceDim, &meshType, meshDesc) < 0){
#endif
    Msg::Error("Unable to read mesh information");
    return 0;
  }

  // FIXME: we should support multi-step MED3 meshes (probably by
  // storing each mesh as a separate model, with a naming convention
  // e.g. meshName_step%d). This way we could also handle multi-mesh
  // time sequences in MED3.
  if(nStep > 1)
    Msg::Warning("Discarding %d last meshes in multi-step MED mesh", nStep - 1);

  setName(meshName);
  setFileName(name);
  if(meshType == MED_NON_STRUCTURE){
    Msg::Info("Reading %d-D unstructured mesh <<%s>>", spaceDim, meshName);
  }
  else{
    Msg::Error("Reading structured MED meshes is not supported");
    return 0;
  }
  med_int vf[3];
  MEDversionLire(fid, &vf[0], &vf[1], &vf[2]);

  // read nodes
#if (MED_MAJOR_NUM == 3)
  med_bool changeOfCoord, geoTransform;
  med_int numNodes = MEDmeshnEntity(fid, meshName, MED_NO_DT, MED_NO_IT, MED_NODE,
                                    MED_NO_GEOTYPE, MED_COORDINATE, MED_NO_CMODE,
                                    &changeOfCoord, &geoTransform);
#else
  med_int numNodes = MEDnEntMaa(fid, meshName, MED_COOR, MED_NOEUD, MED_NONE,
                                MED_NOD);
#endif
  if(numNodes < 0){
    Msg::Error("Could not read number of MED nodes");
    return 0;
  }
  if(numNodes == 0){
    Msg::Error("No nodes in MED mesh");
    return 0;
  }
  std::vector<MVertex*> verts(numNodes);
  std::vector<med_float> coord(spaceDim * numNodes);
#if (MED_MAJOR_NUM == 3)
  if(MEDmeshNodeCoordinateRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_FULL_INTERLACE,
                             &coord[0]) < 0){
#else
  std::vector<char> coordName(spaceDim * MED_TAILLE_PNOM + 1);
  std::vector<char> coordUnit(spaceDim * MED_TAILLE_PNOM + 1);
  med_repere rep;
  if(MEDcoordLire(fid, meshName, spaceDim, &coord[0], MED_FULL_INTERLACE,
                  MED_ALL, 0, 0, &rep, &coordName[0], &coordUnit[0]) < 0){
#endif
    Msg::Error("Could not read MED node coordinates");
    return 0;
  }

  std::vector<med_int> nodeTags(numNodes);
#if (MED_MAJOR_NUM == 3)
  if(MEDmeshEntityNumberRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_NODE,
                           MED_NO_GEOTYPE, &nodeTags[0]) < 0)
#else
  if(MEDnumLire(fid, meshName, &nodeTags[0], numNodes, MED_NOEUD, MED_NONE) < 0)
#endif
    nodeTags.clear();

  for(int i = 0; i < numNodes; i++)
    verts[i] = new MVertex(coord[spaceDim * i],
                           (spaceDim > 1) ? coord[spaceDim * i + 1] : 0.,
                           (spaceDim > 2) ? coord[spaceDim * i + 2] : 0.,
                           0, nodeTags.empty() ? 0 : nodeTags[i]);

  // read elements (loop over all possible MSH element types)
  for(int mshType = 0; mshType < MSH_NUM_TYPE; mshType++){
    med_geometrie_element type = msh2medElementType(mshType);
    if(type == MED_NONE) continue;
#if (MED_MAJOR_NUM == 3)
    med_bool changeOfCoord;
    med_bool geoTransform;
    med_int numEle = MEDmeshnEntity(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                                    type, MED_CONNECTIVITY, MED_NODAL, &changeOfCoord,
                                    &geoTransform);
#else
    med_int numEle = MEDnEntMaa(fid, meshName, MED_CONN, MED_MAILLE, type, MED_NOD);
#endif
    if(numEle <= 0) continue;
    int numNodPerEle = type % 100;
    std::vector<med_int> conn(numEle * numNodPerEle);
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshElementConnectivityRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                                    type, MED_NODAL, MED_FULL_INTERLACE, &conn[0]) < 0){
#else
    if(MEDconnLire(fid, meshName, spaceDim, &conn[0], MED_FULL_INTERLACE, 0, MED_ALL,
                   MED_MAILLE, type, MED_NOD) < 0){
#endif
      Msg::Error("Could not read MED elements");
      return 0;
    }
    std::vector<med_int> fam(numEle, 0);
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshEntityFamilyNumberRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                                   type, &fam[0]) < 0){
#else
    if(MEDfamLire(fid, meshName, &fam[0], numEle, MED_MAILLE, type) < 0){
#endif
      Msg::Info("No family number for elements: using 0 as default family number");
    }
    std::vector<med_int> eleTags(numEle);
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshEntityNumberRd(fid, meshName, MED_NO_DT, MED_NO_IT, MED_CELL,
                             type, &eleTags[0]) < 0)
#else
    if(MEDnumLire(fid, meshName, &eleTags[0], numEle, MED_MAILLE, type) < 0)
#endif
      eleTags.clear();
    std::map<int, std::vector<MElement*> > elements;
    MElementFactory factory;
    for(int j = 0; j < numEle; j++){
      std::vector<MVertex*> v(numNodPerEle);
      for(int k = 0; k < numNodPerEle; k++)
        v[k] = verts[conn[numNodPerEle * j + med2mshNodeIndex(type, k)] - 1];
      MElement *e = factory.create(mshType, v, eleTags.empty() ? 0 : eleTags[j]);
      if(e) elements[-fam[j]].push_back(e);
    }
    _storeElementsInEntities(elements);
  }
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(verts);

  // read family info
  med_int numFamilies = MEDnFam(fid, meshName);
  if(numFamilies < 0){
    Msg::Error("Could not read MED families");
    return 0;
  }
  for(int i = 0; i < numFamilies; i++){
#if (MED_MAJOR_NUM == 3)
    med_int numAttrib = (vf[0] == 2) ? MEDnFamily23Attribute(fid, meshName, i + 1) : 0;
    med_int numGroups = MEDnFamilyGroup(fid, meshName, i + 1);
#else
    med_int numAttrib = MEDnAttribut(fid, meshName, i + 1);
    med_int numGroups = MEDnGroupe(fid, meshName, i + 1);
#endif
    if(numAttrib < 0 || numGroups < 0){
      Msg::Error("Could not read MED groups or attributes");
      return 0;
    }
    std::vector<med_int> attribId(numAttrib + 1);
    std::vector<med_int> attribVal(numAttrib + 1);
    std::vector<char> attribDes(MED_TAILLE_DESC * numAttrib + 1);
    std::vector<char> groupNames(MED_TAILLE_LNOM * numGroups + 1);
    char familyName[MED_TAILLE_NOM + 1];
    med_int familyNum;
#if (MED_MAJOR_NUM == 3)
    if(vf[0] == 2){ // MED2 file
      if(MEDfamily23Info(fid, meshName, i + 1, familyName, &attribId[0],
                         &attribVal[0], &attribDes[0], &familyNum,
                         &groupNames[0]) < 0){
        Msg::Error("Could not read info for MED2 family %d", i + 1);
        continue;
      }
    }
    else{
      if(MEDfamilyInfo(fid, meshName, i + 1, familyName, &familyNum,
                       &groupNames[0]) < 0){
        Msg::Error("Could not read info for MED3 family %d", i + 1);
        continue;
      }
    }
#else
    if(MEDfamInfo(fid, meshName, i + 1, familyName, &familyNum, &attribId[0],
                  &attribVal[0], &attribDes[0], &numAttrib, &groupNames[0],
                  &numGroups) < 0){
      Msg::Error("Could not read info for MED family %d", i + 1);
      continue;
    }
#endif
    // family tags are unique (for all dimensions)
    GEntity *ge;
    if((ge = getRegionByTag(-familyNum))){}
    else if((ge = getFaceByTag(-familyNum))){}
    else if((ge = getEdgeByTag(-familyNum))){}
    else ge = getVertexByTag(-familyNum);
    if(ge){
      elementaryNames[std::pair<int, int>(ge->dim(), -familyNum)] = familyName;
      if(numGroups > 0){
        for(int j = 0; j < numGroups; j++){
          char tmp[MED_TAILLE_LNOM + 1];
          strncpy(tmp, &groupNames[j * MED_TAILLE_LNOM], MED_TAILLE_LNOM);
          tmp[MED_TAILLE_LNOM] = '\0';
          // don't use same physical number across dimensions, as e.g. getdp
          // does not support this
          int pnum = setPhysicalName(tmp, ge->dim(), getMaxPhysicalNumber(-1) + 1);
          if(std::find(ge->physicals.begin(), ge->physicals.end(), pnum) ==
             ge->physicals.end())
            ge->physicals.push_back(pnum);
        }
      }
    }
  }

  // check if we need to read some post-processing data later
#if (MED_MAJOR_NUM == 3)
  bool postpro = (MEDnField(fid) > 0) ? true : false;
#else
  bool postpro = (MEDnChamp(fid, 0) > 0) ? true : false;
#endif

  if(MEDfermer(fid) < 0){
    Msg::Error("Unable to close file '%s'", (char*)name.c_str());
    return 0;
  }

  return postpro ? 2 : 1;
}

template<class T>
static void fillElementsMED(med_int family, std::vector<T*> &elements,
                            std::vector<med_int> &conn, std::vector<med_int> &fam,
                            med_geometrie_element &type)
{
  if(elements.empty()) return;
  type = msh2medElementType(elements[0]->getTypeForMSH());
  if(type == MED_NONE){
    Msg::Warning("Unsupported element type in MED format");
    return;
  }
  for(unsigned int i = 0; i < elements.size(); i++){
    elements[i]->setVolumePositive();
    for(int j = 0; j < elements[i]->getNumVertices(); j++)
      conn.push_back(elements[i]->getVertex(med2mshNodeIndex(type, j))->getIndex());
    fam.push_back(family);
  }
}

static void writeElementsMED(med_idt &fid, char *meshName, std::vector<med_int> &conn,
                             std::vector<med_int> &fam, med_geometrie_element type)
{
  if(fam.empty()) return;
#if (MED_MAJOR_NUM == 3)
  if(MEDmeshElementWr(fid, meshName, MED_NO_DT, MED_NO_IT, 0., MED_CELL, type,
                      MED_NODAL, MED_FULL_INTERLACE, (med_int)fam.size(),
                      &conn[0], MED_FALSE, 0, MED_FALSE, 0, MED_TRUE, &fam[0]) < 0)
#else
  if(MEDelementsEcr(fid, meshName, (med_int)3, &conn[0], MED_FULL_INTERLACE,
                    0, MED_FAUX, 0, MED_FAUX, &fam[0], (med_int)fam.size(),
                    MED_MAILLE, type, MED_NOD) < 0)
#endif
    Msg::Error("Could not write MED elements");
}

int GModel::writeMED(const std::string &name, bool saveAll, double scalingFactor)
{
  med_idt fid = MEDouvrir((char*)name.c_str(), MED_CREATION);
  if(fid < 0){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  // write header
  if(MEDfichDesEcr(fid, (char*)"MED file generated by Gmsh") < 0){
    Msg::Error("Unable to write MED descriptor");
    return 0;
  }

  char *meshName = (char*)getName().c_str();

  // Gmsh always writes 3D unstructured meshes
#if (MED_MAJOR_NUM == 3)
  char dtUnit[MED_SNAME_SIZE + 1] = "";
  char axisName[3 * MED_SNAME_SIZE + 1] = "";
  char axisUnit[3 * MED_SNAME_SIZE + 1] = "";
  if(MEDmeshCr(fid, meshName, 3, 3, MED_UNSTRUCTURED_MESH, "Mesh created with Gmsh",
               dtUnit, MED_SORT_DTIT, MED_CARTESIAN, axisName, axisUnit) < 0){
#else
  if(MEDmaaCr(fid, meshName, 3, MED_NON_STRUCTURE,
              (char*)"Mesh created with Gmsh") < 0){
#endif
    Msg::Error("Could not create MED mesh");
    return 0;
  }

  // if there are no physicals we save all the elements
  if(noPhysicalGroups()) saveAll = true;

  // index the vertices we save in a continuous sequence (MED
  // connectivity is given in terms of vertex indices)
  indexMeshVertices(saveAll);

  // get a vector containing all the geometrical entities in the
  // model (the ordering of the entities must be the same as the one
  // used during the indexing of the vertices)
  std::vector<GEntity*> entities;
  getEntities(entities);

  std::map<GEntity*, int> families;
  // write the families
  {
    // always create a "0" family, with no groups or attributes
#if (MED_MAJOR_NUM == 3)
    if(MEDfamilyCr(fid, meshName, "F_0", 0, 0, "") < 0)
#else
    if(MEDfamCr(fid, meshName, (char*)"F_0", 0, 0, 0, 0, 0, 0, 0) < 0)
#endif
      Msg::Error("Could not create MED family 0");

    // create one family per elementary entity, with one group per
    // physical entity and no attributes
    for(unsigned int i = 0; i < entities.size(); i++){
      if(saveAll || entities[i]->physicals.size()){
        int num = - ((int)families.size() + 1);
        families[entities[i]] = num;
        std::ostringstream fs;
        fs << entities[i]->dim() << "D_" << entities[i]->tag();
        std::string familyName = "F_" + fs.str();
        std::string groupName;
        for(unsigned j = 0; j < entities[i]->physicals.size(); j++){
          std::string tmp = getPhysicalName
            (entities[i]->dim(), entities[i]->physicals[j]);
          if(tmp.empty()){ // create unique name
            std::ostringstream gs;
            gs << entities[i]->dim() << "D_" << entities[i]->physicals[j];
            groupName += "G_" + gs.str();
          }
          else
            groupName += tmp;
          groupName.resize((j + 1) * MED_TAILLE_LNOM, ' ');
        }
#if (MED_MAJOR_NUM == 3)
        if(MEDfamilyCr(fid, meshName, familyName.c_str(),
                       (med_int)num, (med_int)entities[i]->physicals.size(),
                       groupName.c_str()) < 0)
#else
        if(MEDfamCr(fid, meshName, (char*)familyName.c_str(),
                    (med_int)num, 0, 0, 0, 0, (char*)groupName.c_str(),
                    (med_int)entities[i]->physicals.size()) < 0)
#endif
          Msg::Error("Could not create MED family %d", num);
      }
    }
  }

  // write the nodes
  {
    std::vector<med_float> coord;
    std::vector<med_int> fam;
    for(unsigned int i = 0; i < entities.size(); i++){
      for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++){
        MVertex *v = entities[i]->mesh_vertices[j];
        if(v->getIndex() >= 0){
          coord.push_back(v->x() * scalingFactor);
          coord.push_back(v->y() * scalingFactor);
          coord.push_back(v->z() * scalingFactor);
          fam.push_back(0); // we never create node families
        }
      }
    }
    if(fam.empty()){
      Msg::Error("No nodes to write in MED mesh");
      return 0;
    }
#if (MED_MAJOR_NUM == 3)
    if(MEDmeshNodeWr(fid, meshName, MED_NO_DT, MED_NO_IT, 0., MED_FULL_INTERLACE,
                     (med_int)fam.size(), &coord[0], MED_FALSE, "", MED_FALSE, 0,
                     MED_TRUE, &fam[0]) < 0)
#else
    char coordName[3 * MED_TAILLE_PNOM + 1] =
      "x               y               z               ";
    char coordUnit[3 * MED_TAILLE_PNOM + 1] =
      "unknown         unknown         unknown         ";
    if(MEDnoeudsEcr(fid, meshName, (med_int)3, &coord[0], MED_FULL_INTERLACE,
                    MED_CART, coordName, coordUnit, 0, MED_FAUX, 0, MED_FAUX,
                    &fam[0], (med_int)fam.size()) < 0)
#endif
      Msg::Error("Could not write nodes");
  }

  // write the elements
  {
    { // points
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(viter it = firstVertex(); it != lastVertex(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->points, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // lines
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(eiter it = firstEdge(); it != lastEdge(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->lines, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // triangles
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(fiter it = firstFace(); it != lastFace(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->triangles, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // quads
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(fiter it = firstFace(); it != lastFace(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->quadrangles, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // tets
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->tetrahedra, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // hexas
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->hexahedra, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // prisms
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->prisms, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
    { // pyramids
      med_geometrie_element typ = MED_NONE;
      std::vector<med_int> conn, fam;
      for(riter it = firstRegion(); it != lastRegion(); it++)
        if(saveAll || (*it)->physicals.size())
          fillElementsMED(families[*it], (*it)->pyramids, conn, fam, typ);
      writeElementsMED(fid, meshName, conn, fam, typ);
    }
  }

  if(MEDfermer(fid) < 0){
    Msg::Error("Unable to close file '%s'", (char*)name.c_str());
    return 0;
  }

  return 1;
}

#else

int GModel::readMED(const std::string &name)
{
  Msg::Error("Gmsh must be compiled with MED support to read '%s'",
             name.c_str());
  return 0;
}
Esempio n. 10
0
int GModel::writeDIFF(const std::string &name, bool binary, bool saveAll,
                      double scalingFactor)
{
  if(binary){
    Msg::Error("Binary DIFF output is not implemented");
    return 0;
  }

  FILE *fp = Fopen(name.c_str(), binary ? "wb" : "w");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  if(noPhysicalGroups()) saveAll = true;

  // get the number of vertices and index the vertices in a continuous
  // sequence
  int numVertices = indexMeshVertices(saveAll);

  // tag the vertices according to which surface they belong to (Note
  // that we use a brute force approach here, so that we can deal with
  // models with incomplete topology. For example, when we merge 2 STL
  // triangulations we don't have the boundary information between the
  // faces, and the vertices would end up categorized on either one.)
  std::vector<std::list<int> > vertexTags(numVertices);
  std::list<int> boundaryIndicators;
  for(riter it = firstRegion(); it != lastRegion(); it++){
    std::list<GFace*> faces = (*it)->faces();
    for(std::list<GFace*>::iterator itf = faces.begin(); itf != faces.end(); itf++){
      GFace *gf = *itf;
      boundaryIndicators.push_back(gf->tag());
      for(unsigned int i = 0; i < gf->getNumMeshElements(); i++){
        MElement *e = gf->getMeshElement(i);
        for(int j = 0; j < e->getNumVertices(); j++){
          MVertex *v = e->getVertex(j);
          if(v->getIndex() > 0)
            vertexTags[v->getIndex() - 1].push_back(gf->tag());
        }
      }
    }
  }
  boundaryIndicators.sort();
  boundaryIndicators.unique();
  for(int i = 0; i < numVertices; i++){
    vertexTags[i].sort();
    vertexTags[i].unique();
  }

  // get all the entities in the model
  std::vector<GEntity*> entities;
  getEntities(entities);

  // find max dimension of mesh elements we need to save
  int dim = 0;
  for(unsigned int i = 0; i < entities.size(); i++)
    if(entities[i]->physicals.size() || saveAll)
      for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++)
        dim = std::max(dim, entities[i]->getMeshElement(j)->getDim());

  // loop over all elements we need to save
  int numElements = 0, maxNumNodesPerElement = 0;
  for(unsigned int i = 0; i < entities.size(); i++){
    if(entities[i]->physicals.size() || saveAll){
      for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++){
        MElement *e = entities[i]->getMeshElement(j);
        if(e->getStringForDIFF() && e->getDim() == dim){
          numElements++;
          maxNumNodesPerElement = std::max(maxNumNodesPerElement, e->getNumVertices());
        }
      }
    }
  }

  fprintf(fp, "\n\n");
  fprintf(fp, " Finite element mesh (GridFE):\n\n");
  fprintf(fp, " Number of space dim. =   3\n");
  fprintf(fp, " Number of elements   =  %d\n", numElements);
  fprintf(fp, " Number of nodes      =  %d\n\n", numVertices);
  fprintf(fp, " All elements are of the same type : dpTRUE\n");
  fprintf(fp, " Max number of nodes in an element: %d \n", maxNumNodesPerElement);
  fprintf(fp, " Only one subdomain               : dpFALSE\n");
  fprintf(fp, " Lattice data                     ? 0\n\n\n\n");
  fprintf(fp, " %d Boundary indicators:  ", (int)boundaryIndicators.size());
  for(std::list<int>::iterator it = boundaryIndicators.begin();
      it != boundaryIndicators.end(); it++)
    fprintf(fp, " %d", *it);

  fprintf(fp, "\n\n\n");
  fprintf(fp,"  Nodal coordinates and nodal boundary indicators,\n");
  fprintf(fp,"  the columns contain:\n");
  fprintf(fp,"   - node number\n");
  fprintf(fp,"   - coordinates\n");
  fprintf(fp,"   - no of boundary indicators that are set (ON)\n");
  fprintf(fp,"   - the boundary indicators that are set (ON) if any.\n");
  fprintf(fp,"#\n");

  // write mesh vertices
  for(unsigned int i = 0; i < entities.size(); i++){
    for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++){
      MVertex *v = entities[i]->mesh_vertices[j];
      if(v->getIndex() > 0){
        v->writeDIFF(fp, binary, scalingFactor);
        fprintf(fp, " [%d] ", (int)vertexTags[v->getIndex() - 1].size());
        for(std::list<int>::iterator it = vertexTags[v->getIndex() - 1].begin();
            it != vertexTags[v->getIndex() - 1].end(); it++)
          fprintf(fp," %d ", *it);
        fprintf(fp,"\n");
      }
    }
  }

  fprintf(fp, "\n");
  fprintf(fp, "\n");
  fprintf(fp,     "  Element types and connectivity\n");
  fprintf(fp,     "  the columns contain:\n");
  fprintf(fp,     "   - element number\n");
  fprintf(fp,     "   - element type\n");
  fprintf(fp,     "   - subdomain number \n");
  fprintf(fp,     "   - the global node numbers of the nodes in the element.\n");
  fprintf(fp,     "#\n");

  // write mesh elements
  int num = 0;
  for(unsigned int i = 0; i < entities.size(); i++){
    if(entities[i]->physicals.size() || saveAll){
      for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++){
        MElement *e = entities[i]->getMeshElement(j);
        if(e->getStringForDIFF() && e->getDim() == dim)
          e->writeDIFF(fp, ++num, binary, entities[i]->tag());
      }
    }
  }
  fprintf(fp, "\n");

  fclose(fp);
  return 1;
}
Esempio n. 11
0
//////////////////////////////////////////////////////////////////////////
// Entries
//////////////////////////////////////////////////////////////////////////
void SaveLoad::writeEntry(SavegameType type, EntityIndex entity, uint32 value) {
#define WRITE_ENTRY(name, func, val) { \
	uint32 _prevPosition = (uint32)_savegame->pos(); \
	func; \
	uint32 _count = (uint32)_savegame->pos() - _prevPosition; \
	debugC(kLastExpressDebugSavegame, "Savegame: Writing " #name ": %d bytes", _count); \
	if (_count != val)\
		error("SaveLoad::writeEntry: Number of bytes written (%d) differ from expected count (%d)", _count, val); \
}

	if (!_savegame)
		error("SaveLoad::writeEntry: savegame stream is invalid");

	SavegameEntryHeader header;

	header.type = type;
	header.time = (uint32)getState()->time;
	header.chapter = getProgress().chapter;
	header.value = value;

	// Save position
	uint32 originalPosition = (uint32)_savegame->pos();

	// Write header
	Common::Serializer ser(NULL, _savegame);
	header.saveLoadWithSerializer(ser);

	// Write game data
	WRITE_ENTRY("entity index", ser.syncAsUint32LE(entity), 4);
	WRITE_ENTRY("state", getState()->saveLoadWithSerializer(ser), 4 + 4 + 4 + 4 + 1 + 4 + 4);
	WRITE_ENTRY("selected item", getInventory()->saveSelectedItem(ser), 4);
	WRITE_ENTRY("positions", getEntities()->savePositions(ser), 4 * 1000);
	WRITE_ENTRY("compartments", getEntities()->saveCompartments(ser), 4 * 16 * 2);
	WRITE_ENTRY("progress", getProgress().saveLoadWithSerializer(ser), 4 * 128);
	WRITE_ENTRY("events", getState()->syncEvents(ser), 512);
	WRITE_ENTRY("inventory", getInventory()->saveLoadWithSerializer(ser), 7 * 32);
	WRITE_ENTRY("objects", getObjects()->saveLoadWithSerializer(ser), 5 * 128);
	WRITE_ENTRY("entities", getEntities()->saveLoadWithSerializer(ser), 1262 * 40);
	WRITE_ENTRY("sound", getSound()->saveLoadWithSerializer(ser), 3 * 4 + getSound()->count() * 64);
	WRITE_ENTRY("savepoints", getSavePoints()->saveLoadWithSerializer(ser), 128 * 16 + 4 + getSavePoints()->count() * 16);

	header.offset = (uint32)_savegame->pos() - (originalPosition + 32);

	// Add padding if necessary
	while (header.offset & 0xF) {
		_savegame->writeByte(0);
		header.offset++;
	}

	// Save end position
	uint32 endPosition = (uint32)_savegame->pos();

	// Validate entry header
	if (!header.isValid())
		error("SaveLoad::writeEntry: entry header is invalid");

	// Save the header with the updated info
	_savegame->seek(originalPosition);
	header.saveLoadWithSerializer(ser);

	// Move back to the end of the entry
	_savegame->seek(endPosition);
}
Esempio n. 12
0
 std::vector<xy::Entity>& getActors() { return getEntities(); }
Esempio n. 13
0
int patchEntities(double versionFile, char *mapName)
{
	char patchFile[MAX_PATH_LENGTH], *line, *savePtr, itemName[MAX_VALUE_LENGTH];
	char key[MAX_VALUE_LENGTH], value[MAX_VALUE_LENGTH];
	int skipping = FALSE, x, y, read, found, saveMap;
	unsigned char *buffer;
	Entity *e;
	EntityList *el, *entities;
	Target *t;

	savePtr = NULL;

	snprintf(patchFile, sizeof(patchFile), "data/patch/%0.2f.dat", versionFile);

	saveMap = TRUE;

	if (existsInPak(patchFile) == TRUE)
	{
		buffer = loadFileFromPak(patchFile);

		line = strtok_r((char *)buffer, "\n", &savePtr);

		while (line != NULL)
		{
			if (line[strlen(line) - 1] == '\n')
			{
				line[strlen(line) - 1] = '\0';
			}

			if (line[strlen(line) - 1] == '\r')
			{
				line[strlen(line) - 1] = '\0';
			}

			sscanf(line, "%s", itemName);

			if (strcmpignorecase(itemName, "MAP_NAME") == 0)
			{
				sscanf(line, "%*s %s\n", itemName);

				skipping = strcmpignorecase(itemName, mapName) == 0 ? FALSE : TRUE;
			}

			else if (strcmpignorecase(itemName, "MODIFY_OBJECTIVE") == 0 && skipping == FALSE)
			{
				sscanf(line, "%*s \"%[^\"]\" \"%[^\"]\"", key, value);

				modifyObjective(key, value);
			}

			else if (strcmpignorecase(itemName, "REMOVE_OBJECTIVE") == 0 && skipping == FALSE)
			{
				sscanf(line, "%*s \"%[^\"]\"", key);

				removeObjective(key);
			}

			else if (strcmpignorecase(itemName, "REMOVE_TRIGGER") == 0 && skipping == FALSE)
			{
				sscanf(line, "%*s \"%[^\"]\"", key);

				removeGlobalTrigger(key);

				removeTrigger(key);
			}

			else if (strcmpignorecase(line, "ADD_ENTITY") == 0 && skipping == FALSE)
			{
				loadResources(savePtr);
			}

			else if (strcmpignorecase(itemName, "REMOVE_ENTITY") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %s %d %d", itemName, &x, &y);

				found = FALSE;

				e = getEntityByObjectiveName(itemName);

				if (e != NULL)
				{
					e->inUse = FALSE;

					found = TRUE;
				}

				if (found == FALSE)
				{
					t = getTargetByName(itemName);

					if (t != NULL)
					{
						t->active = FALSE;

						found = TRUE;
					}
				}

				if (found == FALSE && read == 3)
				{
					e = getEntityByStartXY(x, y);

					if (e != NULL)
					{
						e->inUse = FALSE;

						found = TRUE;
					}
				}
			}

			else if (strcmpignorecase(itemName, "UPDATE_ENTITY") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %s %s %s", itemName, key, value);

				if (strcmpignorecase(itemName, "PLAYER") == 0)
				{
					e = &player;
				}

				else
				{
					e = getEntityByObjectiveName(itemName);
				}

				if (e != NULL)
				{
					if (strcmpignorecase(value, "NULL") == 0)
					{
						STRNCPY(value, "", sizeof(value));
					}

					setProperty(e, key, value);
				}
			}

			else if (strcmpignorecase(itemName, "UPDATE_ENTITY_BY_START") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %d %d %s %[^\n]s", &x, &y, key, value);

				e = getEntityByStartXY(x, y);

				if (e != NULL)
				{
					setProperty(e, key, value);
				}
			}

			else if (strcmpignorecase(itemName, "UPDATE_ENTITY_BY_XY") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %d %d %s %[^\n]s", &x, &y, key, value);

				e = getEntityByXY(x, y);

				if (e != NULL)
				{
					setProperty(e, key, value);
				}
			}

			else if (strcmpignorecase(itemName, "TRANSLATE_ENTITIES") == 0 && skipping == FALSE)
			{
				read = sscanf(line, "%*s %d %d", &x, &y);

				entities = getEntities();

				player.x -= x;
				player.y -= y;

				for (el=entities->next;el!=NULL;el=el->next)
				{
					e = el->entity;

					e->x -= x;
					e->y -= y;

					if (e->startX - x > 0)
					{
						e->startX -= x;
					}

					if (e->startY - y > 0)
					{
						e->startY -= y;
					}

					if (e->endX - x > 0)
					{
						e->endX -= x;
					}

					if (e->endY - y > 0)
					{
						e->endY -= y;
					}
				}

				t = getTargets();

				for (x=0;x<MAX_TARGETS;x++)
				{
					if (t[x].active == TRUE)
					{
						if (t[x].x - x > 0)
						{
							t[x].x -= x;
						}

						if (t[x].y - y > 0)
						{
							t[x].y -= y;
						}
					}
				}
			}

			else if (strcmpignorecase(itemName, "RENAME_MAP") == 0 && skipping == FALSE)
			{
				saveMap = FALSE;
			}

			line = strtok_r(NULL, "\n", &savePtr);
		}

		free(buffer);
	}

	return saveMap;
}
Esempio n. 14
0
//////////////////////////////////////////////////////////////////////////
// Show the intro and load the main menu scene
void Menu::show(bool doSavegame, SavegameType type, uint32 value) {

	if (_isShowingMenu)
		return;

	_isShowingMenu = true;
	getEntities()->reset();

	// If no blue savegame exists, this might be the first time we start the game, so we show the full intro
	if (!getFlags()->mouseRightClick) {
		if (!SaveLoad::isSavegameValid(kGameBlue) && _engine->getResourceManager()->loadArchive(kArchiveCd1)) {

			if (!_hasShownIntro) {
				// Show Broderbrund logo
				Animation animation;
				if (animation.load(getArchive("1930.nis")))
					animation.play();

				getFlags()->mouseRightClick = false;

				// Play intro music
				getSound()->playSoundWithSubtitles("MUS001.SND", SoundManager::kFlagMusic, kEntityPlayer);

				// Show The Smoking Car logo
				if (animation.load(getArchive("1931.nis")))
					animation.play();

				_hasShownIntro = true;
			}
		} else {
			// Only show the quick intro
			if (!_hasShownStartScreen) {
				getSound()->playSoundWithSubtitles("MUS018.SND", SoundManager::kFlagMusic, kEntityPlayer);
				getScenes()->loadScene(kSceneStartScreen);

				// Original game waits 60 frames and loops Sound::unknownFunction1 unless the right button is pressed
				uint32 nextFrameCount = getFrameCount() + 60;
				while (getFrameCount() < nextFrameCount) {
					_engine->pollEvents();

					if (getFlags()->mouseRightClick)
						break;

					getSound()->updateQueue();
				}
			}
		}
	}

	_hasShownStartScreen = true;

	// Init Menu
	init(doSavegame, type, value);

	// Setup sound
	getSound()->unknownFunction4();
	getSound()->resetQueue(SoundManager::kSoundType11, SoundManager::kSoundType13);
	if (getSound()->isBuffered("TIMER"))
		getSound()->removeFromQueue("TIMER");

	// Init flags & misc
	_isShowingCredits = false;
	_handleTimeDelta = hasTimeDelta();
	getInventory()->unselectItem();

	// Set Cursor type
	_engine->getCursor()->setStyle(kCursorNormal);
	_engine->getCursor()->show(true);

	setup();
	checkHotspots();

	// Set event handlers
	SET_EVENT_HANDLERS(Menu, this);
}
Esempio n. 15
0
void LevelRestartSystem::update() {
	auto entities = getEntities();
	m_impl->update(entities);
}
Esempio n. 16
0
static void entityWait()
{
	int x1, y1, x2, y2, w1, h1, w2, h2;
	EntityList *el, *entities;
	Entity *other;

	if (self->dirX > 0)
	{
		self->endX = getMapRight(self->startX, self->startY);

		self->box.w = self->endX - self->x;
	}

	else if (self->dirX < 0)
	{
		self->x = getMapLeft(self->startX, self->startY);

		self->box.w = self->startX - self->x;
	}

	if (self->dirY > 0)
	{
		self->endY = getMapFloor(self->startX, self->startY);

		self->box.h = self->endY - self->y;
	}

	else if (self->dirY < 0)
	{
		self->y = getMapCeiling(self->startX, self->startY);

		self->box.h = self->startY - self->y;
	}

	entities = getEntities();

	for (el=entities->next;el!=NULL;el=el->next)
	{
		other = el->entity;

		if (other->inUse == TRUE && (other->type == MANUAL_DOOR || other->type == AUTO_DOOR || other->type == WEAK_WALL))
		{
			x1 = self->x + self->box.x;
			y1 = self->y + self->box.y;
			w1 = self->box.w;
			h1 = self->box.h;

			x2 = other->x + other->box.x;
			y2 = other->y + other->box.y;
			w2 = other->box.w;
			h2 = other->box.h;

			if (collision(x1, y1, w1, h1, x2, y2, w2, h2) == TRUE)
			{
				if (self->dirX > 0)
				{
					self->endX = other->x;

					self->box.w = self->endX - self->x;
				}

				else if (self->dirX < 0)
				{
					self->x = other->x + other->w;

					self->box.w = self->startX - self->x;
				}

				if (self->dirY > 0)
				{
					self->endY = other->y;

					self->box.h = self->endY - self->y;
				}

				else if (self->dirY < 0)
				{
					self->y = other->y + other->h;

					self->box.h = self->startY - self->y;
				}
			}
		}
	}
}
Esempio n. 17
0
	vector<path_type> pp2pp(id_type Id1, id_type Id2) {
		Paper pp1, pp2;
		for (auto const &pp : getEntities("Or(Id=" + to_string(Id1) + ",Id=" + to_string(Id2) + ")", _AA_AUID | _C_CID | _F_FID | _ID | _J_JID | _RID)) {
			if (pp.Id == Id1) pp1 = pp;
			if (pp.Id == Id2) pp2 = pp;
		}
		string expr;
		bool fst;
		vector<Paper> plist;
		path_type currentpath = {Id1, Id2};
		vector<path_type> ret;
		//1-hop
		//	P->P
		for (const auto &ref : pp1.RId)
			if (ref == Id2) {
				ret.push_back(currentpath);
				break;
			}
		//2-hop
		//	P-AuCFJ-P
		currentpath.push_back(Id2);
		for (const auto &au1 : pp1.AA)
			for (const auto &au2 : pp2.AA)
				if (au1.AuId == au2.AuId) {
					currentpath[1] = au1.AuId;
					if (currentpath[1] != -1) ret.push_back(currentpath);
					break;
				}
		if (pp1.C.CId == pp2.C.CId) {
			currentpath[1] = pp1.C.CId;
			if (currentpath[1] != -1) ret.push_back(currentpath);
		}
		for (const auto &f1 : pp1.F)
			for (const auto &f2 : pp2.F)
				if (f1.FId == f2.FId) {
					currentpath[1] = f1.FId;
					if (currentpath[1] != -1) ret.push_back(currentpath);
					break;
				}
		if (pp1.J.JId == pp2.J.JId) {
			currentpath[1] = pp1.J.JId;
			if (currentpath[1] != -1) ret.push_back(currentpath);
		}
		//	P->P->P
		vector<Paper> papersr, tmp;
		fst = true;
		expr.clear();
		for (const auto &ref : pp1.RId) {
			if (expr.size() + to_string(ref).size() + 8 > expr_max) {
				//string("Or(,Id=)").size() == 8
				tmp = getEntities(expr, _AA_AUID | _C_CID | _F_FID | _ID | _J_JID | _RID);
				papersr.insert(papersr.end(), tmp.begin(), tmp.end());
				fst = true;
			}
			if (fst) {
				expr = "Id=" + to_string(ref);
				fst = false;
			}
			else
				expr = "Or(" + expr + ",Id=" + to_string(ref) + ")";
		}
		if (expr.size()) {
			tmp = getEntities(expr, _AA_AUID | _C_CID | _F_FID | _ID | _J_JID | _RID);
			papersr.insert(papersr.end(), tmp.begin(), tmp.end());
		}
		for (const auto &pp : papersr)
			for (const auto &ref : pp.RId)
				if (ref == Id2) {
					currentpath[1] = pp.Id;
					if (currentpath[1] != -1) ret.push_back(currentpath);
					break;
				}
		//3-hop
		//	P-AuCFJ-P->P
		currentpath.push_back(Id2);
		fst = true;
		for (const auto &au : pp1.AA)
			if (fst) {
				expr = "Composite(AA.AuId=" + to_string(au.AuId) + ")";
				fst = false;
			} else
				expr = "Or(" + expr + ",Composite(AA.AuId=" + to_string(au.AuId) + "))";
		if (fst) {
			expr = "Composite(C.CId=" + to_string(pp1.C.CId) + ")";
			fst = false;
		} else
			expr = "Or(" + expr + ",Composite(C.CId=" + to_string(pp1.C.CId) + "))";
		for (const auto &f : pp1.F)
			if (fst) {
				expr = "Composite(F.FId=" + to_string(f.FId) + ")";
				fst = false;
			}
			else
				expr = "Or(" + expr + ",Composite(F.FId=" + to_string(f.FId) + "))";
		if (fst) {
			expr = "Composite(J.JId=" + to_string(pp1.J.JId) + ")";
			fst = false;
		} else
			expr = "Or(" + expr + ",Composite(J.JId=" + to_string(pp1.J.JId) + "))";
		if (expr.size()) expr = "And(" + expr + ",RId=" + to_string(Id2) + ")";
		plist.clear();
		if (expr.size()) plist = getEntities(expr, _AA_AUID | _C_CID | _F_FID | _ID | _J_JID);
		for (const auto &p : plist) {
			currentpath[2] = p.Id;
			for (const auto &au1 : pp1.AA)
				for (const auto &aup : p.AA)
					if (au1.AuId == aup.AuId) {
						currentpath[1] = au1.AuId;
						if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
						break;
					}
			if (pp1.C.CId == p.C.CId) {
				currentpath[1] = pp1.C.CId;
				if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
			}
			for (const auto &f1 : pp1.F)
				for (const auto &fp : p.F)
					if (f1.FId == fp.FId) {
						currentpath[1] = f1.FId;
						if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
						break;
					}
			if (pp1.J.JId == p.J.JId) {
				currentpath[1] = pp1.J.JId;
				if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
			}
		}
		//	P->P-AuCFJ-P
		for (const auto &ppr : papersr) {
			currentpath[1] = ppr.Id;
			for (const auto &aur : ppr.AA)
				for (const auto &au2 : pp2.AA)
					if (aur.AuId == au2.AuId) {
						currentpath[2] = aur.AuId;
						if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
						break;
					}
			if (ppr.C.CId == pp2.C.CId) {
				currentpath[2] = ppr.C.CId;
				if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
			}
			for (const auto &fr : ppr.F)
				for (const auto &f2 : pp2.F)
					if (fr.FId == f2.FId) {
						currentpath[2] = fr.FId;
						if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
						break;
					}
			if (ppr.J.JId == pp2.J.JId) {
				currentpath[2] = ppr.J.JId;
				if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
			}
		}
		//	P->P->P->P
		plist.clear();
		fst = true;
		for (const auto &p : papersr)
			for (const auto &ref : p.RId) {
				if (expr.size() + to_string(ref).size() + to_string(Id2).size() + 18 > expr_max) {
					//string("And(Or(,Id=),RId=)").size() == 18
					tmp = getEntities("And(" + expr + ",RId=" + to_string(Id2) + ")", _ID);
					plist.insert(plist.end(), tmp.begin(), tmp.end());
					fst = true;
				}
				if (fst) {
					expr = "Id=" + to_string(ref);
					fst = false;
				}
				else
					expr = "Or(" + expr + ",Id=" + to_string(ref) + ")";
			}
		if (expr.size()) {
			tmp = getEntities("And(" + expr + ",RId=" + to_string(Id2) + ")", _ID);
			plist.insert(plist.end(), tmp.begin(), tmp.end());
		}
		sort(plist.begin(), plist.end(), paper_id_less);
		plist.erase(unique(plist.begin(), plist.end(), paper_id_equal), plist.end());
		Paper pt;
		for (const auto &ppr : papersr) {
			currentpath[1] = ppr.Id;
			for (const auto &ref : ppr.RId) {
				pt.Id = ref;
				auto pos = lower_bound(plist.begin(), plist.end(), pt, paper_id_less);
				if (pos != plist.end() && ref == pos->Id) {
					currentpath[2] = ref;
					if (currentpath[1] != -1 && currentpath[2] != -1) ret.push_back(currentpath);
				}
			}
		}
		sort(ret.begin(), ret.end());
		ret.erase(unique(ret.begin(), ret.end()), ret.end());
		return ret;
	}
Esempio n. 18
0
void Logic::eventMouse(const Common::Event &ev) {
	bool hotspotHandled = false;

	// Reset mouse flags
	getFlags()->mouseLeftClick = false;
	getFlags()->mouseRightClick = false;

	// Process event flags
	if (ev.type == Common::EVENT_LBUTTONDOWN) {

		if (getFlags()->frameInterval)
			_ignoreFrameInterval = false;

		getFlags()->frameInterval = false;
	}

	if (getFlags()->flag_0) {
		if (ev.type == Common::EVENT_LBUTTONDOWN || ev.type == Common::EVENT_RBUTTONDOWN) {
			getFlags()->flag_0 = false;
			getFlags()->shouldRedraw = true;
			updateCursor(true);
			getFlags()->frameInterval = true;
		}
		return;
	}

	if (_ignoreFrameInterval && getScenes()->checkCurrentPosition(true) && _engine->getCursor()->getStyle() == kCursorForward) {
		getFlags()->shouldRedraw = false;
		getFlags()->flag_0 = true;
		return;
	}

	// Update coordinates
	getGameState()->setCoordinates(ev.mouse);

	// Handle inventory
	getInventory()->handleMouseEvent(ev);

	// Stop processing is inside the menu
	if (getMenu()->isShown())
		return;

	// Handle whistle case
	if (getInventory()->getSelectedItem() == kItemWhistle
	 && !getProgress().isEggOpen
	 && !getEntities()->isPlayerPosition(kCarGreenSleeping, 59)
	 && !getEntities()->isPlayerPosition(kCarGreenSleeping, 76)
	 && !getInventory()->isPortraitHighlighted()
	 && !getInventory()->isOpened()
	 && !getInventory()->isEggHighlighted()
	 && !getInventory()->isMagnifierInUse()) {

		 // Update cursor
		_engine->getCursor()->setStyle(getInventory()->get(kItemWhistle)->cursor);

		// Check if clicked
		if (ev.type == Common::EVENT_LBUTTONUP && !getSoundQueue()->isBuffered("LIB045")) {

			getSound()->playSoundEvent(kEntityPlayer, 45);

			if (getEntities()->isPlayerPosition(kCarGreenSleeping, 26) || getEntities()->isPlayerPosition(kCarGreenSleeping, 25) || getEntities()->isPlayerPosition(kCarGreenSleeping, 23)) {
				getSavePoints()->push(kEntityPlayer, kEntityMertens, kAction226078300);
			} else if (getEntities()->isPlayerPosition(kCarRedSleeping, 26) || getEntities()->isPlayerPosition(kCarRedSleeping, 25) || getEntities()->isPlayerPosition(kCarRedSleeping, 23)) {
				getSavePoints()->push(kEntityPlayer, kEntityCoudert, kAction226078300);
			}

			if (!getState()->sceneUseBackup)
				getInventory()->unselectItem();
		}

		REDRAW_CURSOR()
	}
Esempio n. 19
0
int GModel::writeINP(const std::string &name, bool saveAll, bool saveGroupsOfNodes,
                     double scalingFactor)
{
  FILE *fp = Fopen(name.c_str(), "w");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  if(noPhysicalGroups()) saveAll = true;

  indexMeshVertices(saveAll);
  std::vector<GEntity*> entities;
  getEntities(entities);

  fprintf(fp, "*Heading\n");
  fprintf(fp, " %s\n", name.c_str());

  fprintf(fp, "*Node\n");
  for(unsigned int i = 0; i < entities.size(); i++)
    for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++)
      entities[i]->mesh_vertices[j]->writeINP(fp, scalingFactor);

  for(viter it = firstVertex(); it != lastVertex(); ++it){
    writeElementsINP(fp, *it, (*it)->points, saveAll);
  }
  for(eiter it = firstEdge(); it != lastEdge(); ++it){
    writeElementsINP(fp, *it, (*it)->lines, saveAll);
  }
  for(fiter it = firstFace(); it != lastFace(); ++it){
    writeElementsINP(fp, *it, (*it)->triangles, saveAll);
    writeElementsINP(fp, *it, (*it)->quadrangles, saveAll);
  }
  for(riter it = firstRegion(); it != lastRegion(); ++it){
    writeElementsINP(fp, *it, (*it)->tetrahedra, saveAll);
    writeElementsINP(fp, *it, (*it)->hexahedra, saveAll);
    writeElementsINP(fp, *it, (*it)->prisms, saveAll);
    writeElementsINP(fp, *it, (*it)->pyramids, saveAll);
  }

  std::map<int, std::vector<GEntity*> > groups[4];
  getPhysicalGroups(groups);

  // save elements sets for each physical group
  for(int dim = 0; dim <= 3; dim++){
    for(std::map<int, std::vector<GEntity*> >::iterator it = groups[dim].begin();
        it != groups[dim].end(); it++){
      std::vector<GEntity *> &entities = it->second;
      fprintf(fp, "*ELSET,ELSET=%s\n", physicalName(this, dim, it->first).c_str());
      int n = 0;
      for(unsigned int i = 0; i < entities.size(); i++){
        for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++){
          MElement *e = entities[i]->getMeshElement(j);
          if(n && !(n % 10)) fprintf(fp, "\n");
          fprintf(fp, "%d, ", e->getNum());
          n++;
        }
      }
      fprintf(fp, "\n");
    }
  }

  // save node sets for each physical group
  if(saveGroupsOfNodes){
    for(int dim = 1; dim <= 3; dim++){
      for(std::map<int, std::vector<GEntity*> >::iterator it = groups[dim].begin();
          it != groups[dim].end(); it++){
        std::set<MVertex*> nodes;
        std::vector<GEntity *> &entities = it->second;
        for(unsigned int i = 0; i < entities.size(); i++){
          for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++){
            MElement *e = entities[i]->getMeshElement(j);
            for (int k = 0; k < e->getNumVertices(); k++)
              nodes.insert(e->getVertex(k));
          }
        }
        fprintf(fp, "*NSET,NSET=%s\n", physicalName(this, dim, it->first).c_str());
        int n = 0;
        for(std::set<MVertex*>::iterator it2 = nodes.begin(); it2 != nodes.end(); it2++){
          if(n && !(n % 10)) fprintf(fp, "\n");
          fprintf(fp, "%d, ", (*it2)->getIndex());
          n++;
        }
        fprintf(fp, "\n");
      }
    }
  }

  fclose(fp);
  return 1;
}
Esempio n. 20
0
void SaveLoad::readEntry(SavegameType *type, EntityIndex *entity, uint32 *val, bool keepIndex) {
#define LOAD_ENTRY(name, func, val) { \
	uint32 _prevPosition = (uint32)_savegame->pos(); \
	func; \
	uint32 _count = (uint32)_savegame->pos() - _prevPosition; \
	debugC(kLastExpressDebugSavegame, "Savegame: Reading " #name ": %d bytes", _count); \
	if (_count != val) \
		error("SaveLoad::readEntry: Number of bytes read (%d) differ from expected count (%d)", _count, val); \
}

#define LOAD_ENTRY_ONLY(name, func) { \
	uint32 _prevPosition = (uint32)_savegame->pos(); \
	func; \
	uint32 _count = (uint32)_savegame->pos() - _prevPosition; \
	debugC(kLastExpressDebugSavegame, "Savegame: Reading " #name ": %d bytes", _count); \
}

	if (!type || !entity || !val)
		error("SaveLoad::readEntry: Invalid parameters passed!");

	if (!_savegame)
		error("SaveLoad::readEntry: No savegame stream present!");

	// Load entry header
	SavegameEntryHeader entry;
	Common::Serializer ser(_savegame, NULL);
	entry.saveLoadWithSerializer(ser);

	if (!entry.isValid())
		error("SaveLoad::readEntry: entry header is invalid!");

	// Init type, entity & value
	*type = entry.type;
	*val = entry.value;

	// Save position
	uint32 originalPosition = (uint32)_savegame->pos();

	// Load game data
	LOAD_ENTRY("entity index", ser.syncAsUint32LE(*entity), 4);
	LOAD_ENTRY("state", getState()->saveLoadWithSerializer(ser), 4 + 4 + 4 + 4 + 1 + 4 + 4);
	LOAD_ENTRY("selected item", getInventory()->saveSelectedItem(ser), 4);
	LOAD_ENTRY("positions", getEntities()->savePositions(ser), 4 * 1000);
	LOAD_ENTRY("compartments", getEntities()->saveCompartments(ser), 4 * 16 * 2);
	LOAD_ENTRY("progress", getProgress().saveLoadWithSerializer(ser), 4 * 128);
	LOAD_ENTRY("events", getState()->syncEvents(ser), 512);
	LOAD_ENTRY("inventory", getInventory()->saveLoadWithSerializer(ser), 7 * 32);
	LOAD_ENTRY("objects", getObjects()->saveLoadWithSerializer(ser), 5 * 128);
	LOAD_ENTRY("entities", getEntities()->saveLoadWithSerializer(ser), 1262 * 40);
	LOAD_ENTRY_ONLY("sound", getSound()->saveLoadWithSerializer(ser));
	LOAD_ENTRY_ONLY("savepoints", getSavePoints()->saveLoadWithSerializer(ser));

	// Update chapter
	getProgress().chapter = entry.chapter;

	// Skip padding
	uint32 offset = (uint32)_savegame->pos() - originalPosition;
	if (offset & 0xF) {
		_savegame->seek((~offset & 0xF) + 1, SEEK_SET);
	}
}
Esempio n. 21
0
	void LuaSystem::onMessage(jl::Message *message)
	{
		if(message->name == "ReloadLua")
		{
			for(auto itr = getEntities().begin(); itr != getEntities().end(); itr++)
			{
				LuaComponent *luaComp = itr->second->getComponent<LuaComponent>();
				runScript(*itr->second);
			}
		}
		else
		{
			// Find entities (scripts) associated with this message
			auto itr = m_subscribedScripts.find(message->name);

			if(itr != m_subscribedScripts.end())
			{
				for(std::size_t i = 0; i < itr->second.size(); i++)
				{
					lua_State *state = m_luaEnv.getRaw();

					// Grab event function
					lua_getglobal(state, "events");
					int eventFuncIndex = lua_gettop(state);

					// Push self
					LuaEnvironment::pushObjectToLua<Entity>(state, itr->second[i], "jl.Entity");

					// Push event name
					lua_pushstring(state, message->name.c_str());
					int argCount = 2;

					// Push event args, depending on event
					if(message->name == "KeyDown" || message->name == "KeyUp")
					{
						if(message->isType<SDL_Event>())
						{
							const SDL_Event& sdlEvent = static_cast<MessageData<SDL_Event>*>(message)->data;
							argCount += m_luaEnv.pushArgsToLua(
								LuaArg<std::string>{SDL_GetScancodeName(sdlEvent.key.keysym.scancode)},
								LuaArg<bool>{sdlEvent.key.repeat});
							
						}
					}

					else if(message->isType<std::string>())
					{
						std::string strData = static_cast<MessageData<std::string>*>(message)->data;
						lua_pushstring(state, strData.c_str());
						++argCount;
					}

					// Call event function
					if(!lua_isnil(state, eventFuncIndex))
						if(lua_pcall(state, argCount, 0, 0))
							m_luaEnv.reportError();
				}
			}
		}

		
	}
bool DOMDocumentTypeImpl::isEqualNode(const DOMNode* arg) const
{
    if (isSameNode(arg)) {
        return true;
    }

    if (!fNode.isEqualNode(arg)) {
        return false;
    }

    DOMDocumentType* argDT = (DOMDocumentType*) arg;
    // check the string values
    if (!getPublicId()) {
        if (argDT->getPublicId()) {
            return false;
        }
    }
    else if (!XMLString::equals(getPublicId(), argDT->getPublicId())) {
        return false;
    }

    if (!getSystemId()) {
        if (argDT->getSystemId()) {
            return false;
        }
    }
    else if (!XMLString::equals(getSystemId(), argDT->getSystemId())) {
        return false;
    }

    if (!getInternalSubset()) {
        if (argDT->getInternalSubset()) {
            return false;
        }
    }
    else if (!XMLString::equals(getInternalSubset(), argDT->getInternalSubset())) {
        return false;
    }

    // check the notations
    if (getNotations()) {
        if (!argDT->getNotations())
            return false;

        DOMNamedNodeMap* map1 = getNotations();
        DOMNamedNodeMap* map2 = argDT->getNotations();

        XMLSize_t len = map1->getLength();
        if (len != map2->getLength()) {
            return false;
        }
        for (XMLSize_t i = 0; i < len; i++) {
            DOMNode* n1 = map1->item(i);
            DOMNode* n2 = map2->getNamedItem(n1->getNodeName());
            if (!n2 || !n1->isEqualNode(n2)) {
                return false;
            }
        }
    }
    else {
        if (argDT->getNotations())
            return false;
    }

    // check the entities
    if (getEntities()) {
        if (!argDT->getEntities())
            return false;

        DOMNamedNodeMap* map1 = getEntities();
        DOMNamedNodeMap* map2 = argDT->getEntities();

        XMLSize_t len = map1->getLength();
        if (len != map2->getLength()) {
            return false;
        }
        for (XMLSize_t i = 0; i < len; i++) {
            DOMNode* n1 = map1->item(i);
            DOMNode* n2 = map2->getNamedItem(n1->getNodeName());
            if (!n2 || !n1->isEqualNode(n2)) {
                return false;
            }
        }
    }
    else {
        if (argDT->getEntities())
            return false;
    }

    return fParent.isEqualNode(arg);
}
Esempio n. 23
0
int isAtEdge(Entity *e)
{
	int i, tile;
	int x = e->face == LEFT ? floor(e->x) : ceil(e->x) + e->w;
	int y = e->y + e->h - 1;
	EntityList *el, *entities;

	entities = getEntities();

	x /= TILE_SIZE;
	y /= TILE_SIZE;

	y++;

	tile = mapTileAt(x, y);

	/* Return immediately if the tile isn't blank */

	if (!(e->flags & ON_GROUND) || (tile != BLANK_TILE && tile < BACKGROUND_TILE_START))
	{
		return FALSE;
	}

	if (e->w > TILE_SIZE)
	{
		if (e->dirX > 0)
		{
			for (i=0;;)
			{
				x = e->x + i;

				x /= TILE_SIZE;

				tile = mapTileAt(x, y);

				if (tile >= SLOPE_DOWN_START && tile <= SLOPE_DOWN_END)
				{
					return FALSE;
				}

				if (i == e->w)
				{
					break;
				}

				i += TILE_SIZE;

				if (i > e->w)
				{
					i = e->w;
				}
			}
		}

		else
		{
			for (i=e->w;;)
			{
				x = e->x + i;

				x /= TILE_SIZE;

				tile = mapTileAt(x, y);

				if (tile >= SLOPE_UP_START && tile <= SLOPE_UP_END)
				{
					return FALSE;
				}

				if (i == 0)
				{
					break;
				}

				i -= TILE_SIZE;

				if (i < 0)
				{
					i = 0;
				}
			}
		}
	}

	x = e->face == LEFT ? floor(e->x) : ceil(e->x);

	if (e->face == RIGHT)
	{
		x += e->w;
	}

	/* There might still be Entities that can be walked on */

	for (el=entities->next;el!=NULL;el=el->next)
	{
		if (e != el->entity && el->entity->inUse == TRUE && el->entity->touch != NULL
			&& ((el->entity->flags & (PUSHABLE|OBSTACLE)) || (el->entity->type == WEAK_WALL)
			|| (el->entity->type == PRESSURE_PLATE) || (el->entity->type == ANTI_GRAVITY)))
		{
			if (collision(x, e->y, 1, e->h + 10, el->entity->x, el->entity->y, el->entity->w, el->entity->h) == TRUE)
			{
				return FALSE;
			}
		}
	}

	return TRUE;
}
Esempio n. 24
0
int GModel::writePOS(const std::string &name, bool printElementary,
                     bool printElementNumber, bool printGamma, bool printEta,
                     bool printRho, bool printDisto,
                     bool saveAll, double scalingFactor)
{
  FILE *fp = Fopen(name.c_str(), "w");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  /*
  bool printVertices = true;
  if(printVertices){
    fprintf(fp, "View \"Vertices\" {\n");
    std::vector<GEntity*> entities;
    getEntities(entities);
    for(unsigned int i = 0; i < entities.size(); i++)
      for(unsigned int j = 0; j < entities[i]->mesh_vertices.size(); j++){
        MVertex *v = entities[i]->mesh_vertices[j];
        fprintf(fp, "SP(%g,%g,%g){1};\n", v->x(), v->y(), v->z());
      }
    fprintf(fp, "};\n");
    fclose(fp);
    return 1;
  }
  */

  bool f[6] = {printElementary, printElementNumber, printGamma, printEta, printRho,
               printDisto};

  bool first = true;
  std::string names;
  if(f[0]){
    if(first) first = false; else names += ",";
    names += "\"Elementary Entity\"";
  }
  if(f[1]){
    if(first) first = false; else names += ",";
    names += "\"Element Number\"";
  }
  if(f[2]){
    if(first) first = false; else names += ",";
    names += "\"Gamma\"";
  }
  if(f[3]){
    if(first) first = false; else names += ",";
    names += "\"Eta\"";
  }
  if(f[4]){
    if(first) first = false; else names += ",";
    names += "\"Rho\"";
  }
  if(f[5]){
    if(first) first = false; else names += ",";
    names += "\"Disto\"";
  }

  if(names.empty()){ fclose(fp); return 0; }

  if(noPhysicalGroups()) saveAll = true;

  fprintf(fp, "View \"Statistics\" {\n");
  fprintf(fp, "T2(1.e5,30,%d){%s};\n", (1<<16)|(4<<8), names.c_str());

  std::vector<GEntity*> entities;
  getEntities(entities);
  for(unsigned int i = 0; i < entities.size(); i++)
    if(saveAll || entities[i]->physicals.size())
      for(unsigned int j = 0; j < entities[i]->getNumMeshElements(); j++)
        entities[i]->getMeshElement(j)->writePOS
          (fp, f[0], f[1], f[2], f[3], f[4], f[5], scalingFactor, entities[i]->tag());
  fprintf(fp, "};\n");

  fclose(fp);
  return 1;
}
Esempio n. 25
0
PyObject* EntityGarbages<T>::pyHas_key(ENTITY_ID entityID)
{
	ENTITYS_MAP& entities = getEntities();
	return PyLong_FromLong((entities.find(entityID) != entities.end()));
}
Esempio n. 26
0
void EntityEngine::executeMoveIntents() {
	for (EntityList::iterator it = getEntities().begin(); it != getEntities().end(); it++) {
		MoveAccessClass::applyMoveIntent(*(*it));
	}
}
Esempio n. 27
0
int GModel::readPLY(const std::string &name)
{
  // this is crazy!?
  replaceCommaByDot(name);

  FILE *fp = Fopen(name.c_str(), "r");
  if(!fp){
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  std::vector<MVertex*> vertexVector;
  std::map<int, std::vector<MElement*> > elements[5];
  std::map<int, std::vector<double> > properties;

  char buffer[256], str[256], str2[256], str3[256];
  std::string s1;
  int elementary = getMaxElementaryNumber(-1) + 1;
  int nbv = 0, nbf = 0;
  int nbprop = 0;
  int nbView = 0;
  std::vector<std::string> propName;
  while(!feof(fp)) {
    if(!fgets(buffer, sizeof(buffer), fp)) break;
    if(buffer[0] != '#'){ // skip comments
      sscanf(buffer, "%s %s", str, str2);
      if(!strcmp(str, "element") && !strcmp(str2, "vertex")){
	sscanf(buffer, "%s %s %d", str, str2, &nbv);
      }
      if(!strcmp(str, "format") && strcmp(str2, "ascii")){
	Msg::Error("Only reading of ascii PLY files implemented");
        fclose(fp);
	return 0;
      }
      if(!strcmp(str, "property") && strcmp(str2, "list")){
	nbprop++;
	sscanf(buffer, "%s %s %s", str, str2, str3);
	if (nbprop > 3) propName.push_back(s1+str3);
      }
      if(!strcmp(str, "element") && !strcmp(str2, "face")){
	sscanf(buffer, "%s %s %d", str, str2, &nbf);
      }
      if(!strcmp(str, "end_header")){
	nbView = nbprop -3;
	Msg::Info("%d elements", nbv);
	Msg::Info("%d triangles", nbf);
	Msg::Info("%d properties", nbView);

	vertexVector.resize(nbv);
	for(int i = 0; i < nbv; i++) {
	  double x,y,z;
	  char line[10000], *pEnd, *pEnd2, *pEnd3;
	  if(!fgets(line, sizeof(line), fp)){ fclose(fp); return 0; }
	  x = strtod(line, &pEnd);
	  y = strtod(pEnd, &pEnd2);
	  z = strtod(pEnd2, &pEnd3);
	  vertexVector[i] = new MVertex(x, y, z);

	  pEnd = pEnd3;
          std::vector<double> prop(nbView);
	  for (int k = 0; k < nbView; k++){
	    prop[k]=strtod(pEnd, &pEnd2);
	    pEnd = pEnd2;
	    properties[k].push_back(prop[k]);
	  }
	}

	for(int i = 0; i < nbf; i++) {
	  if(!fgets(buffer, sizeof(buffer), fp)) break;
	  int n[3], nbe;
	  sscanf(buffer, "%d %d %d %d", &nbe, &n[0], &n[1], &n[2]);
	  std::vector<MVertex*> vertices;
	  if(!getVertices(3, n, vertexVector, vertices)){ fclose(fp); return 0; }
	  elements[0][elementary].push_back(new MTriangle(vertices));
	}

      }

    }
  }

  for(int i = 0; i < (int)(sizeof(elements) / sizeof(elements[0])); i++)
    _storeElementsInEntities(elements[i]);
  _associateEntityWithMeshVertices();
  _storeVerticesInEntities(vertexVector);

#if defined(HAVE_POST)
  // create PViews here
  std::vector<GEntity*> _entities;
  getEntities(_entities);
  for (int iV=0; iV< nbView; iV++){
    PView *view = new PView();
    PViewDataList *data = dynamic_cast<PViewDataList*>(view->getData());
    for(unsigned int ii = 0; ii < _entities.size(); ii++){
	for(unsigned int i = 0; i < _entities[ii]->getNumMeshElements(); i++){
	  MElement *e = _entities[ii]->getMeshElement(i);
	  int numNodes = e->getNumVertices();
	  std::vector<double> x(numNodes), y(numNodes), z(numNodes);
	  std::vector<double> *out = data->incrementList(1, e->getType());
	  for(int nod = 0; nod < numNodes; nod++) out->push_back((e->getVertex(nod))->x());
	  for(int nod = 0; nod < numNodes; nod++) out->push_back((e->getVertex(nod))->y());
	  for(int nod = 0; nod < numNodes; nod++) out->push_back((e->getVertex(nod))->z());
	  std::vector<double> props;
	  int n[3];
	  n[0] = e->getVertex(0)->getNum()-1;
	  n[1] = e->getVertex(1)->getNum()-1;
	  n[2] = e->getVertex(2)->getNum()-1;
	  if(!getProperties(3, n, properties[iV], props)){ fclose(fp); return 0; }
	  for(int nod = 0; nod < numNodes; nod++) out->push_back(props[nod]);
	}
    }
    data->setName(propName[iV]);
    data->Time.push_back(0);
    data->setFileName("property.pos");
    data->finalize();
  }
#endif

  fclose(fp);

  return 1;
}
Esempio n. 28
0
void EntityEngine::removeEntity(EntityList::iterator const& it, Engines & e) {
	(*it)->unregister(e);
	delete *it;
	getEntities().erase(it);
}
Esempio n. 29
0
int GModel::writeKEY(const std::string &name, int saveAll,
                     int saveGroupsOfNodes, double scalingFactor)
{
  FILE *fp = Fopen(name.c_str(), "w");
  if(!fp) {
    Msg::Error("Unable to open file '%s'", name.c_str());
    return 0;
  }

  if(noPhysicalGroups()) saveAll = 0x51;

  indexMeshVertices(saveAll & 0x51);
  std::vector<GEntity *> entities;
  getEntities(entities);

  fprintf(fp, "$# LS-DYNA Keyword file created by Gmsh\n*KEYWORD\n*TITLE\n");
  fprintf(fp, " %s\n", name.c_str());

  fprintf(fp, "*NODE\n");
  for(std::size_t i = 0; i < entities.size(); i++)
    for(std::size_t j = 0; j < entities[i]->mesh_vertices.size(); j++)
      entities[i]->mesh_vertices[j]->writeKEY(fp, scalingFactor);

  if(!(saveAll & 0x2)) // save or ignore Vertex, not in GUI
    for(viter it = firstVertex(); it != lastVertex(); ++it) {
      writeElementsKEY(fp, *it, (*it)->points, saveAll & 0x1);
    }
  if(!(saveAll & 0x8)) // save or ignore line
    for(eiter it = firstEdge(); it != lastEdge(); ++it) {
      writeElementsKEY(fp, *it, (*it)->lines, saveAll & 0x4);
    }
  if(!(saveAll & 0x20)) // save or ignore surface
    for(fiter it = firstFace(); it != lastFace(); ++it) {
      writeElementsKEY(fp, *it, (*it)->triangles, saveAll & 0x10);
      writeElementsKEY(fp, *it, (*it)->quadrangles, saveAll & 0x10);
    }
  if(!(saveAll & 0x80)) // save or ignore surface
    for(riter it = firstRegion(); it != lastRegion(); ++it) {
      writeElementsKEY(fp, *it, (*it)->tetrahedra, saveAll & 0x40);
      writeElementsKEY(fp, *it, (*it)->hexahedra, saveAll & 0x40);
      writeElementsKEY(fp, *it, (*it)->prisms, saveAll & 0x40);
      writeElementsKEY(fp, *it, (*it)->pyramids, saveAll & 0x40);
    }

  std::map<int, std::vector<GEntity *> > groups[4];
  getPhysicalGroups(groups);

  int setid = 0;
  // save elements sets for each physical group
  if(saveGroupsOfNodes & 0x2) {
    for(int dim = 0; dim <= 3; dim++) {
      if(saveAll & (0x2 << (2 * dim))) continue; // elements are ignored
      for(std::map<int, std::vector<GEntity *> >::iterator it =
            groups[dim].begin();
          it != groups[dim].end(); it++) {
        std::vector<GEntity *> &entities = it->second;
        int n = 0;
        for(std::size_t i = 0; i < entities.size(); i++) {
          for(std::size_t j = 0; j < entities[i]->getNumMeshElements(); j++) {
            MElement *e = entities[i]->getMeshElement(j);
            if(!n) {
              const char *str = (e->getDim() == 3) ?
                                  "SOLID" :
                                  (e->getDim() == 2) ?
                                  "SHELL" :
                                  (e->getDim() == 1) ? "BEAM" : "NODE";
              fprintf(fp, "*SET_%s_LIST\n$# %s\n%d", str,
                      physicalName(this, dim, it->first).c_str(), ++setid);
            }
            if(!(n % 8))
              fprintf(fp, "\n%lu", e->getNum());
            else
              fprintf(fp, ", %lu", e->getNum());
            n++;
          }
        }
        if(n) fprintf(fp, "\n");
      }
    }
  }

  // save node sets for each physical group, for easier load/b.c.
  if(saveGroupsOfNodes & 0x1) {
    for(int dim = 1; dim <= 3; dim++) {
      for(std::map<int, std::vector<GEntity *> >::iterator it =
            groups[dim].begin();
          it != groups[dim].end(); it++) {
        std::set<MVertex *> nodes;
        std::vector<GEntity *> &entities = it->second;
        for(std::size_t i = 0; i < entities.size(); i++) {
          for(std::size_t j = 0; j < entities[i]->getNumMeshElements(); j++) {
            MElement *e = entities[i]->getMeshElement(j);
            for(std::size_t k = 0; k < e->getNumVertices(); k++)
              nodes.insert(e->getVertex(k));
          }
        }
        fprintf(fp, "*SET_NODE_LIST\n$# %s\n%d",
                physicalName(this, dim, it->first).c_str(), ++setid);
        int n = 0;
        for(std::set<MVertex *>::iterator it2 = nodes.begin();
            it2 != nodes.end(); it2++) {
          if(!(n % 8))
            fprintf(fp, "\n%ld", (*it2)->getIndex());
          else
            fprintf(fp, ", %ld", (*it2)->getIndex());
          n++;
        }
        if(n) fprintf(fp, "\n");
      }
    }
  }

  fprintf(fp, "*END\n");
  fclose(fp);
  return 1;
}
Esempio n. 30
0
void NinjaSenseDetector::checkForEntitiesAffectedByNinjaSense() {
	auto entities = getEntities();
	m_impl->checkForEntitiesAffectedByNinjaSense(entities);

}