//-------------------------------------------------------------------------------------
bool ScriptDefModule::addPropertyDescription(const char* attrName, 
										  PropertyDescription* propertyDescription, 
										  COMPONENT_TYPE componentType)
{
	PropertyDescription* f_propertyDescription = NULL;
	PROPERTYDESCRIPTION_MAP*  propertyDescr;
	PROPERTYDESCRIPTION_UIDMAP*  propertyDescr_uidmap;

	switch(componentType)
	{
	case CELLAPP_TYPE:
			f_propertyDescription = findCellPropertyDescription(attrName);
			propertyDescr = &getCellPropertyDescriptions();
			propertyDescr_uidmap = &getCellPropertyDescriptions_uidmap();
			
			// 判断他们是什么级别的属性, 将其保存到对应detailLevel的地方
			if((propertyDescription->getFlags() & ENTITY_CLIENT_DATA_FLAGS) > 0){
				cellDetailLevelPropertyDescrs_[propertyDescription->getDetailLevel()][attrName] = propertyDescription;
			}

			setCell(true);
			break;
	case BASEAPP_TYPE:
			f_propertyDescription = findBasePropertyDescription(attrName);
			propertyDescr = &getBasePropertyDescriptions();
			propertyDescr_uidmap = &getBasePropertyDescriptions_uidmap();
			setBase(true);
			break;
	default:
			f_propertyDescription = findClientPropertyDescription(attrName);
			propertyDescr = &getClientPropertyDescriptions();
			propertyDescr_uidmap = &getClientPropertyDescriptions_uidmap();
			setClient(true);
			break;
	};

	if(f_propertyDescription)
	{
		ERROR_MSG(boost::format("ScriptDefModule::addPropertyDescription: [%1%] is exist! componentType=%2%.\n") %
			attrName % componentType);

		return false;
	}

	(*propertyDescr)[attrName] = propertyDescription;
	(*propertyDescr_uidmap)[propertyDescription->getUType()] = propertyDescription;
	propertyDescription->incRef();


	// 判断是否是存储属性, 是就存储到persistentPropertyDescr_
	if(propertyDescription->isPersistent())
	{
		PROPERTYDESCRIPTION_MAP::const_iterator pciter = 
			persistentPropertyDescr_.find(attrName);

		if(pciter == persistentPropertyDescr_.end())
		{
			persistentPropertyDescr_[attrName] = propertyDescription;
			persistentPropertyDescr_uidmap_[propertyDescription->getUType()] = propertyDescription;
		}
	}

	return true;
}
Exemple #2
0
Cell::Cell(int r , int c , int v)
{
	setCell(r,c,v);
}
void UINumberPicker::updateDisplayList()
{
    _selectedItem = nullptr;
    
    _itemsLayer->removeAllChildrenWithCleanup(true);
    sortChildrenArray.clear();
    
    displayRect.size = getContentSize();
    displayRect.origin = getParent()->convertToWorldSpace(getPosition());
    
    int numOfCell = virtualItemCount + 2;
    
    m_middleCellIndex = (int)numOfCell/2;
    
    if (show_value < m_minValue || show_value > m_maxValue)
    {
        show_value = m_minValue;
    }
    int upIndex = show_value - 1;
    int downIndex = show_value;
    
    for (int i = 0; i < numOfCell; i++)
    {
        auto cell = PickerCell::create();
        cell->setContentSize(Size(item_width, item_height));
        cell->setDirection(_pickerDirection);
        switch (_pickerDirection)
        {
            case PickerDirection::VERTICAL:
            {
                cell->setPositionX(getContentSize().width/2);
                if (i <= m_middleCellIndex)
                {
                    cell->setPositionY((m_middleCellIndex - i) * item_height);
                    
                    cell->setCellValue(downIndex);
                    downIndex += 1;
                    if (downIndex > m_maxValue)
                    {
                        downIndex = m_minValue;
                    }
                }
                else
                {
                    cell->setPositionY(i * item_height);
                    
                    if (upIndex < m_minValue)
                    {
                        upIndex = m_maxValue;
                    }
                    cell->setCellValue(upIndex);
                    upIndex -= 1;
                }
                break;
            }
            case PickerDirection::HORIZONTAL:
            {
                cell->setPositionY(0);
                if (i <= m_middleCellIndex)
                {
                    cell->setPositionX((m_middleCellIndex - i) * item_width);
                    
                    cell->setCellValue(downIndex);
                    downIndex += 1;
                    if (downIndex > m_maxValue)
                    {
                        downIndex = m_minValue;
                    }
                }
                else
                {
                    cell->setPositionX(i * item_width);
                    
                    if (upIndex < m_minValue)
                    {
                        upIndex = m_maxValue;
                    }
                    cell->setCellValue(upIndex);
                    upIndex -= 1;
                }
                break;
            }
            default:
                break;
        }
        
        if (i == 0)
        {
            setCell(cell);
        }        
        sortChildrenArray.push_back(cell);
        _itemsLayer->addChild(cell);
    }
}
void collision_detection::StaticDistanceField::initialize(
      const bodies::Body& body,
      double resolution,
      double space_around_body,
      bool save_points)
{
  points_.clear();
  inv_twice_resolution_ = 1.0 / (2.0 * resolution);


  logInform("    create points at res=%f",resolution);
  EigenSTL::vector_Vector3d points;
  determineCollisionPoints(body, resolution, points);

  if (points.empty())
  {
    logWarn("    StaticDistanceField::initialize: No points in body. Using origin.");
    points.push_back(body.getPose().translation());

    if (body.getType() == shapes::MESH)
    {
      const bodies::ConvexMesh& mesh = dynamic_cast<const bodies::ConvexMesh&>(body);
      const EigenSTL::vector_Vector3d& verts = mesh.getVertices();
      logWarn("    StaticDistanceField::initialize: also using %d vertices.", int(verts.size()));

      EigenSTL::vector_Vector3d::const_iterator it = verts.begin();
      EigenSTL::vector_Vector3d::const_iterator it_end = verts.end();
      for ( ; it != it_end ; ++it)
      {
        points.push_back(*it);
      }
    }
  }
  logInform("    StaticDistanceField::initialize: Using %d points.", points.size());

  AABB aabb;
  aabb.add(points);

  logInform("    space_around_body = %f",space_around_body);
  logInform("    DF: min=(%7.3f %7.3f %7.3f)  max=(%7.3f %7.3f %7.3f) (pre-space)",
                              aabb.min_.x(),
                              aabb.min_.y(),
                              aabb.min_.z(),
                              aabb.max_.x(),
                              aabb.max_.y(),
                              aabb.max_.z());

  aabb.min_ -= Eigen::Vector3d(space_around_body, space_around_body, space_around_body);
  aabb.max_ += Eigen::Vector3d(space_around_body, space_around_body, space_around_body);

  logInform("    DF: min=(%7.3f %7.3f %7.3f)  max=(%7.3f %7.3f %7.3f) (pre-adjust)",
                              aabb.min_.x(),
                              aabb.min_.y(),
                              aabb.min_.z(),
                              aabb.max_.x(),
                              aabb.max_.y(),
                              aabb.max_.z());

  aabb.min_.x() = std::floor(aabb.min_.x() / resolution) * resolution;
  aabb.min_.y() = std::floor(aabb.min_.y() / resolution) * resolution;
  aabb.min_.z() = std::floor(aabb.min_.z() / resolution) * resolution;

  logInform("    DF: min=(%7.3f %7.3f %7.3f)  max=(%7.3f %7.3f %7.3f) (post-adjust)",
                              aabb.min_.x(),
                              aabb.min_.y(),
                              aabb.min_.z(),
                              aabb.max_.x(),
                              aabb.max_.y(),
                              aabb.max_.z());

  Eigen::Vector3d size = aabb.max_ - aabb.min_;

  double diagonal = size.norm();

  logInform("    DF: sz=(%7.3f %7.3f %7.3f) cnt=(%d %d %d) diag=%f",
                              size.x(),
                              size.y(),
                              size.z(),
                              int(size.x()/resolution),
                              int(size.y()/resolution),
                              int(size.z()/resolution),
                              diagonal);


  distance_field::PropagationDistanceField df(
                              size.x(),
                              size.y(),
                              size.z(),
                              resolution,
                              aabb.min_.x(),
                              aabb.min_.y(),
                              aabb.min_.z(),
                              diagonal * 2.0,
                              true);
  df.addPointsToField(points);

  DistPosEntry default_entry;
  default_entry.distance_ = diagonal * 2.0;
  default_entry.cell_id_ = -1;

  resize(size.x(),
         size.y(),
         size.z(),
         resolution,
         aabb.min_.x(),
         aabb.min_.y(),
         aabb.min_.z(),
         default_entry);

  logInform("    copy %d points.",
    getNumCells(distance_field::DIM_X) *
    getNumCells(distance_field::DIM_Y) *
    getNumCells(distance_field::DIM_Z));

  int pdf_x,pdf_y,pdf_z;
  int sdf_x,sdf_y,sdf_z;
  Eigen::Vector3d pdf_p, sdf_p;
  df.worldToGrid(aabb.min_.x(), aabb.min_.y(), aabb.min_.z(), pdf_x,pdf_y,pdf_z);
  worldToGrid(aabb.min_.x(), aabb.min_.y(), aabb.min_.z(), sdf_x,sdf_y,sdf_z);
  df.gridToWorld(pdf_x,pdf_y,pdf_z, pdf_p.x(), pdf_p.y(), pdf_p.z());
  gridToWorld(sdf_x,sdf_y,sdf_z, sdf_p.x(), sdf_p.y(), sdf_p.z());

  logInform("    DF: min=(%10.6f %10.6f %10.6f)  quant->%3d %3d %3d  (pdf)",
                              aabb.min_.x(),
                              aabb.min_.y(),
                              aabb.min_.z(),
                              pdf_x,
                              pdf_y,
                              pdf_z);
  logInform("    DF: min=(%10.6f %10.6f %10.6f)  quant<-%3d %3d %3d  (pdf)",
                              pdf_p.x(),
                              pdf_p.y(),
                              pdf_p.z(),
                              pdf_x,
                              pdf_y,
                              pdf_z);
  logInform("    DF: min=(%10.6f %10.6f %10.6f)  quant<-%3d %3d %3d  (sdf)",
                              sdf_p.x(),
                              sdf_p.y(),
                              sdf_p.z(),
                              sdf_x,
                              sdf_y,
                              sdf_z);


  df.worldToGrid(0,0,0, pdf_x,pdf_y,pdf_z);
  worldToGrid(0,0,0, sdf_x,sdf_y,sdf_z);
  df.gridToWorld(pdf_x,pdf_y,pdf_z, pdf_p.x(), pdf_p.y(), pdf_p.z());
  gridToWorld(sdf_x,sdf_y,sdf_z, sdf_p.x(), sdf_p.y(), sdf_p.z());

  logInform("    DF: org=(%10.6f %10.6f %10.6f)  quant->%3d %3d %3d  (pdf)",
                              0.0,
                              0.0,
                              0.0,
                              pdf_x,
                              pdf_y,
                              pdf_z);
  logInform("    DF: org=(%10.6f %10.6f %10.6f)  quant<-%3d %3d %3d  (pdf)",
                              pdf_p.x(),
                              pdf_p.y(),
                              pdf_p.z(),
                              pdf_x,
                              pdf_y,
                              pdf_z);
  logInform("    DF: org=(%10.6f %10.6f %10.6f)  quant<-%3d %3d %3d  (sdf)",
                              sdf_p.x(),
                              sdf_p.y(),
                              sdf_p.z(),
                              sdf_x,
                              sdf_y,
                              sdf_z);


  df.worldToGrid(points[0].x(), points[0].y(), points[0].z(), pdf_x,pdf_y,pdf_z);
  worldToGrid(points[0].x(), points[0].y(), points[0].z(), sdf_x,sdf_y,sdf_z);
  df.gridToWorld(pdf_x,pdf_y,pdf_z, pdf_p.x(), pdf_p.y(), pdf_p.z());
  gridToWorld(sdf_x,sdf_y,sdf_z, sdf_p.x(), sdf_p.y(), sdf_p.z());

  logInform("    DF: p0 =(%10.6f %10.6f %10.6f)  quant->%3d %3d %3d  (pdf)",
                              points[0].x(),
                              points[0].y(),
                              points[0].z(),
                              pdf_x,
                              pdf_y,
                              pdf_z);
  logInform("    DF: p0 =(%10.6f %10.6f %10.6f)  quant<-%3d %3d %3d  (pdf)",
                              pdf_p.x(),
                              pdf_p.y(),
                              pdf_p.z(),
                              pdf_x,
                              pdf_y,
                              pdf_z);
  logInform("    DF: p0 =(%10.6f %10.6f %10.6f)  quant<-%3d %3d %3d  (sdf)",
                              sdf_p.x(),
                              sdf_p.y(),
                              sdf_p.z(),
                              sdf_x,
                              sdf_y,
                              sdf_z);


  for (int z = 0 ; z < df.getZNumCells() ; ++z)
  {
    for (int y = 0 ; y < df.getYNumCells() ; ++y)
    {
      for (int x = 0 ; x < df.getXNumCells() ; ++x)
      {
        DistPosEntry entry;
        double dist = df.getDistance(x, y, z);
        const distance_field::PropDistanceFieldVoxel& voxel = df.getCell(x,y,z);

        if (dist < 0)
        {

          // propogation distance field has a bias of -1*resolution on points inside the object
          if (dist <= -resolution)
          {
            dist += resolution;
          }
          else
          {
            logError("PropagationDistanceField returned distance=%f between 0 and -resolution=%f."
                     "  Did someone fix it?"
                     "  Need to remove workaround from static_distance_field.cpp",
                     dist,-resolution);
            dist = 0.0;
          }
          entry.distance_ = dist;
          entry.cell_id_ = getCellId(
                              voxel.closest_negative_point_.x(),
                              voxel.closest_negative_point_.y(),
                              voxel.closest_negative_point_.z());
        }
        else
        {
          entry.distance_ = dist;
          entry.cell_id_ = getCellId(
                              voxel.closest_point_.x(),
                              voxel.closest_point_.y(),
                              voxel.closest_point_.z());
        }
        setCell(x, y, z, entry);
      }
    }
  }

  if (save_points)
    std::swap(points, points_);
}
//-------------------------------------------------------------------------------------
void ScriptDefModule::autoMatchCompOwn()
{
	/*
		entity存在某部分(cell, base, client)的判定规则

		1: entitydef文件中存在实体某部分的方法或者属性,同时也必须也存在py脚本
		2: 用户在entities.xml明确声明存在某实体部分(为了unity3d或者html5类的前端无法加载py的环境考虑)
			entities.xml, <Spaces hasCell="true" hasClient="false", hasBase="true"></Spaces>
	*/

	std::string entitiesFile = Resmgr::getSingleton().getPyUserScriptsPath() + "entities.xml";

	// 打开这个entities.xml文件
	SmartPointer<XML> xml(new XML());
	if(!xml->openSection(entitiesFile.c_str()) || !xml->isGood())
		return;
	
	// 获得entities.xml根节点, 如果没有定义一个entity那么直接返回true
	TiXmlNode* node = xml->getRootNode();
	if(node == NULL)
		return;

	int assertionHasClient = -1;
	int assertionHasBase = -1;
	int assertionHasCell = -1;

	// 开始遍历所有的entity节点
	XML_FOR_BEGIN(node)
	{
		std::string moduleName = xml.get()->getKey(node);
		if(name_ == moduleName)
		{
			const char* val = node->ToElement()->Attribute("hasClient");
			if(val)
			{
				if(kbe_strnicmp(val, "true", strlen(val)) == 0)
					assertionHasClient = 1;
				else
					assertionHasClient = 0;
			}

			EntityDef::md5().append((void*)&assertionHasClient, sizeof(int));

			val = node->ToElement()->Attribute("hasCell");
			if(val)
			{
				if(kbe_strnicmp(val, "true", strlen(val)) == 0)
					assertionHasCell = 1;
				else
					assertionHasCell = 0;
			}

			EntityDef::md5().append((void*)&assertionHasClient, sizeof(int));

			val = node->ToElement()->Attribute("hasBase");
			if(val)
			{
				if(kbe_strnicmp(val, "true", strlen(val)) == 0)
					assertionHasBase = 1;
				else
					assertionHasBase = 0;
			}

			EntityDef::md5().append((void*)&assertionHasClient, sizeof(int));
			break;
		}
	}
	XML_FOR_END(node);

	std::string fmodule = "scripts/client/" + name_ + ".py";
	std::string fmodule_pyc = "scripts/client/"SCRIPT_BIN_CACHEDIR"/" + name_ + "."SCRIPT_BIN_TAG".pyc";
	if(Resmgr::getSingleton().matchRes(fmodule) != fmodule ||
		Resmgr::getSingleton().matchRes(fmodule_pyc) != fmodule_pyc)
	{
		setClient(true);
	}
	else
	{
		if(assertionHasClient < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容(因为interface的存在,interface中可能会存在客户端属性或者方法)
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			// http://www.kbengine.org/cn/docs/configuration/entities.html 
			setClient(false);
		}
		else
		{
			// 用户明确声明并进行了设定
			setClient(assertionHasClient == 1);
		}
	}

	if(g_componentType == CLIENT_TYPE)
	{
		setBase(true);
		setCell(true);
		return;
	}

	fmodule = "scripts/base/" + name_ + ".py";
	fmodule_pyc = "scripts/base/"SCRIPT_BIN_CACHEDIR"/" + name_ + "."SCRIPT_BIN_TAG".pyc";
	if(Resmgr::getSingleton().matchRes(fmodule) != fmodule ||
		Resmgr::getSingleton().matchRes(fmodule_pyc) != fmodule_pyc)
	{
		setBase(true);
	}
	else
	{
		if(assertionHasBase < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			setBase(false);
		}
		else
		{
			// 用户明确声明并进行了设定
			setBase(assertionHasBase == 1);
		}
	}

	fmodule = "scripts/cell/" + name_ + ".py";
	fmodule_pyc = "scripts/cell/"SCRIPT_BIN_CACHEDIR"/" + name_ + "."SCRIPT_BIN_TAG".pyc";
	if(Resmgr::getSingleton().matchRes(fmodule) != fmodule ||
		Resmgr::getSingleton().matchRes(fmodule_pyc) != fmodule_pyc)
	{
		setCell(true);
	}
	else
	{
		if(assertionHasCell < 0)
		{
			// 如果用户不存在明确声明并设置为没有对应实体部分
			// 这样做的原因是允许用户在def文件定义这部分的内容
			// 但如果脚本不存在仍然认为用户当前不需要该部分
			setCell(false);
		}
		else
		{
			// 用户明确声明并进行了设定
			setCell(assertionHasCell == 1);
		}
	}
}
Exemple #6
0
void LifeModel::setCellOn(int row, int col)
{
	setCell(row, col, 1);
}
Exemple #7
0
//-------------------------------------------------------------------------------------
bool ScriptDefModule::addPropertyDescription(const char* attrName, 
										  PropertyDescription* propertyDescription, 
										  COMPONENT_TYPE componentType, bool ignoreConflict)
{
	if(!ignoreConflict && hasMethodName(attrName))
	{
		ERROR_MSG(fmt::format("ScriptDefModule::addPropertyDescription: There is a method[{}] name conflict! componentType={}.\n",
			attrName, componentType));
		
		return false;
	}
	
	if (!ignoreConflict && hasComponentName(attrName))
	{
		ERROR_MSG(fmt::format("ScriptDefModule::addPropertyDescription: There is a component[{}] name conflict!\n",
			attrName));

		return false;
	}

	bool isEntityComponent = propertyDescription->getDataType() && 
		std::string("ENTITY_COMPONENT") == propertyDescription->getDataType()->getName();

	PropertyDescription* f_propertyDescription = NULL;
	PROPERTYDESCRIPTION_MAP*  propertyDescr;
	PROPERTYDESCRIPTION_UIDMAP*  propertyDescr_uidmap;

	switch(componentType)
	{
	case CELLAPP_TYPE:
			f_propertyDescription = findCellPropertyDescription(attrName);
			propertyDescr = &getCellPropertyDescriptions();
			propertyDescr_uidmap = &getCellPropertyDescriptions_uidmap();
			
			// 判断他们是什么级别的属性, 将其保存到对应detailLevel的地方
			if((propertyDescription->getFlags() & ENTITY_CLIENT_DATA_FLAGS) > 0){
				cellDetailLevelPropertyDescrs_[propertyDescription->getDetailLevel()][attrName] = propertyDescription;
			}

			setCell(true);
			break;
	case BASEAPP_TYPE:
			f_propertyDescription = findBasePropertyDescription(attrName);
			propertyDescr = &getBasePropertyDescriptions();
			propertyDescr_uidmap = &getBasePropertyDescriptions_uidmap();
			setBase(true);
			break;
	default:
			f_propertyDescription = findClientPropertyDescription(attrName);
			propertyDescr = &getClientPropertyDescriptions();
			propertyDescr_uidmap = &getClientPropertyDescriptions_uidmap();
			setClient(true);
			break;
	};

	if(f_propertyDescription)
	{
		ERROR_MSG(fmt::format("ScriptDefModule::addPropertyDescription: [{}] is exist! componentType={}.\n",
			attrName, componentType));

		return false;
	}

	(*propertyDescr)[attrName] = propertyDescription;
	(*propertyDescr_uidmap)[propertyDescription->getUType()] = propertyDescription;
	propertyDescription->incRef();

	if(isEntityComponent)
		componentPropertyDescr_[attrName] = propertyDescription;

	// 判断是否是存储属性, 是就存储到persistentPropertyDescr_
	if(propertyDescription->isPersistent())
	{
		PROPERTYDESCRIPTION_MAP::const_iterator pciter = 
			persistentPropertyDescr_.find(attrName);

		if(pciter == persistentPropertyDescr_.end())
		{
			persistentPropertyDescr_[attrName] = propertyDescription;
			persistentPropertyDescr_uidmap_[propertyDescription->getUType()] = propertyDescription;
		}
	}

	return true;
}
Exemple #8
0
void Grid::setRow( int r, int c, QWidget* w, int count )
{
    for (int i = 0; i < count; i++ )
	setCell( r, c + i, w );
}
Exemple #9
0
void Line::convertToSimpleBlock(initializer_list<int> n, bool debug) {
  int n1=1; 
  // First find the existing vertex if non then proceed; 
  if (n.size() >= 1) {n1 = *(n.begin());} 
  else {  return; }
  if (debug) cout << "Converting cell: "<<id << " to block ("<< n1<< ")"<<endl; 

  vector<int_8 > ind; 
  ind.assign(n1+1, -1); 
  
  ind[0] = node[0];   
  ind[n1] = node[1];

  Vec3 dx, x0,x1;
  x0 = Vec3(**getVertex(0)); 
  dx = edge()/double(n1); 

  // Fill in non-existing Vertices
  for (auto i = 0; i < n1+1 ; ++i) {
    if (debug) cout << "Processing i = "<< i << " using index "<< ind[i] << endl; 
    if (ind[i]>=0) {
      if (debug)
	cout<< "Existing vertex: " << ind[i] << " ("<< *(*(grid->listVertex.begin()+ind[i])) <<")"<< endl; 
      //(*(grid->listVertex.begin()+ind[i][j]))->reset(4); 
      continue;
    }
    grid->addVertex(x0 + double(i)*dx); 
    ind[i] = grid->listVertex.size()-1;
    (*(grid->listVertex.rbegin()))->reset(4);
    if (debug) 	  
      cout<< "New vertex: " << ind[i] << " ("<< *(*(grid->listVertex.begin()+ind[i])) <<")"<< endl; 
    // boundary
    //      (*(grid->listVertex.rbegin()))->setCell(0, (j-1)*n1+i-1+nCell);   
  }

  auto nCell = grid->listCell.size()-1; 
  for (auto i = 0; i < n1+1; ++i) { 
    auto v = (*(grid->listVertex.begin()+ind[i]));
    int_8 i0 = i-1; i0 = (i0 == 0) ? id : i0+nCell; 
    int_8 i1 = i;   i1 = (i1 == 0) ? id : i1+nCell; 
    
    if (i > 0 && i < n1) {
      v->setCell({i0, i1}); 
    } else if (i == 0) {
      auto v0 = grid->listVertex.begin() + ind[i]; 
      v->setCell({(*v0)->cell[0], i1}); 
    } else if (i == n1) {
      auto v0 = grid->listVertex.begin() + ind[i]; 
      v->setCell({i0, (*v0)->cell[1]}); 
    }
  }

  for (auto i = 0; i < n1; ++i) {
    if (i == 0) {
      reset({ind[i], ind[i+1]}); 
    } else {
      grid->addCell({ind[i], ind[i+1]}); 
      auto x = (*grid->listCell.rbegin())->getCoord();	
      for (auto k = 0; k < grid->listVar.size(); ++k) {
	grid->listVar[k]->set(grid->listCell.size()-1,grid->listVar[k]->get(id)); // oldv[k] + (x-xcold)*oldg[k]); 
      }
    }
  }

  return;
}
Exemple #10
0
void CTable::setCell(const char* entryc, size_t r, size_t c){
  std::string entry=entryc;
  setCell(entry,r,c);
}
Exemple #11
0
void Grid::setCol( int r, int c, QWidget* w, int count )
{
    for (int i = 0; i < count; i++ )
	setCell( r + i, c, w );
}
Exemple #12
0
void CTable::setCell(const TString& entryTS, size_t r, size_t c){
  setCell(std::string(entryTS.Data()),r,c);
}
Exemple #13
0
void CPlayer::setships()
{
	char input = 'V';
	char ok = 'Y';
	char save = 'N';
	ostringstream outSStream;
	CCell location;

	for(short j = 1; j < SHIP_SIZE_ARRAYSIZE; j++)
	{
		system("cls");
		printGrid(cout, ZERO);
		outSStream.str("");
		outSStream << "Player " << m_whichPlayer + ONE << " Enter " 
			<< shipNames[j] << " orientation";
		input = safeChoice(outSStream.str(), 'V', 'H');
		if (input == 'V')
			m_ships[j].setOrientation(ONE);
		else
			m_ships[j].setOrientation(ZERO);
		cout << "Player " << m_whichPlayer + ONE << " Enter " << shipNames[j] 
		<< " bow coordinates <row letter><col #>: ";
		location.getCoord(cin, m_gridSize);
		m_ships[j].setBowLocation(location);
		// if ok
		if(!isValidLocation(j))
		{
			cout << "invalid location. Press <enter>" ;
			cin.ignore(BUFFER_SIZE, '\n');
			cin.get();
			j--; // redo
			continue;
		}
		// our code
		location = m_ships[j].getCell();
		for(int i = 0; i < shipSize[j]; i++)
		{
			if (input == 'V')
			{
				setCell(ZERO, location, m_ships[j].getName());
				location.increaseRow();
			}
			else
			{
				setCell(ZERO, location, m_ships[j].getName());
				location.increaseCol();
			}
		}
		system("CLS");
		printGrid(cout, ZERO);
		ok = safeChoice("Position okay? ", 'Y', 'N');
		// choice not ok
		if (ok == 'N')
		{
			location = m_ships[j].getCell(); 
			for(int i = 0; i < shipSize[j]; i++)
			{
				if (input == 'V')
				{
					setCell(ZERO, location, CShip::NOSHIP);
					location.increaseRow();
				}
				else
				{
					setCell(ZERO, location, CShip::NOSHIP);
					location.increaseCol();
				}
			}
			j--;
		}
	} // end for j
	save = safeChoice("\nSave starting grid?", 'Y', 'N');
	if(save == 'Y')
		saveGrid();
}
Exemple #14
0
bool CPlayer::getGrid(string fileName)
{
	string line;
	ifstream ifs;
	CShip ship = CShip::NOSHIP;
	short shipCount[SHIP_SIZE_ARRAYSIZE] = {0};
	char cell = ' ';
	//char fsize = 'S';
	char size_of_grid;
	short numberOfRows = (toupper(getGridSize()) == 'L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize()) == 'L') ? LARGECOLS : SMALLCOLS;
	CCell location;
	ifs.open(fileName.c_str());
	if(!ifs)
	{

		cout << "could not open file " << fileName << endl
			<< " press <enter> to continue" << endl;
		cin.ignore(BUFFER_SIZE, '\n');
		return false;
	}	
	size_of_grid = ifs.get();
	if (m_gridSize != size_of_grid)
	{ 
		cout << "The input file size is not compatible with the " <<
			"grid size that you chose from the beginning.";
		cout << endl;
		ifs.close();
		return false;
	}
	for (int i = 1; i < SHIP_SIZE_ARRAYSIZE; i++)
	{
		int input_orientation;
		int input_row;
		int input_col;
		ifs >> input_orientation;
		ifs >> input_row;
		ifs >> input_col;

		location = (input_row, input_col);
		m_ships[i].setBowLocation(location);
		m_ships[i].setOrientation(input_orientation);

		for(int j = 0; j < shipSize[i]; i++)
		{
			if (m_ships[i].getOrientation() == CDirection::VERTICAL)
			{
				setCell(ZERO, location, m_ships[i].getName());
				location.increaseRow();
			}
			else
			{
				setCell(ZERO, location, m_ships[i].getName());
				location.increaseCol();
			}
		}
	}
	system("CLS");
	printGrid(cout, ZERO);
	char ok = safeChoice("Position okay? ", 'Y', 'N');
	// choice not ok
	if (ok == 'N')
	{
		for (int i = 0; i < numberOfRows; i++)
			for (int j = 0; j < numberOfCols; j++)
				m_gameGrid[ZERO][i][j] = CShip::NOSHIP;
		return false;
	}
	cin.clear();
	cin.ignore(BUFFER_SIZE, '\n');
	fflush(stdin);
	cout << "press <enter>  . . ." << endl;
	cin.get();
	system("CLS");
	ifs.close();	
	return true;
}
Exemple #15
0
bool MatrixModel::importASCII(const QString &fname, const QString &sep,
                              int ignoredLines, bool stripSpaces,
                              bool simplifySpaces, const QString &commentString,
                              int importAs, const QLocale &locale,
                              int endLineChar, int maxRows) {
  int rows = 0;
  QString name = MdiSubWindow::parseAsciiFile(fname, commentString, endLineChar,
                                              ignoredLines, maxRows, rows);
  if (name.isEmpty())
    return false;
  QFile f(name);
  if (!f.open(QIODevice::ReadOnly))
    return false;

  QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

  QTextStream t(&f);
  QLocale l = d_locale;
  if (d_matrix)
    l = d_matrix->locale();
  bool updateDecimalSeparators = (l != locale);

  QString s = t.readLine();
  if (simplifySpaces)
    s = s.simplified();
  else if (stripSpaces)
    s = s.trimmed();

  QStringList line = s.split(sep);
  int cols = line.size();

  int startRow = 1, startCol = 0;
  switch (importAs) {
  case Matrix::Overwrite:
    if (d_cols != cols)
      setColumnCount(cols);
    if (d_rows != rows)
      setRowCount(rows);
    break;
  case Matrix::NewColumns:
    startCol = d_cols;
    setColumnCount(d_cols + cols);
    if (d_rows < rows)
      setRowCount(rows);
    break;
  case Matrix::NewRows:
    startRow = d_rows;
    if (d_cols < cols)
      setColumnCount(cols);
    setRowCount(d_rows + rows);
    break;
  }

  for (int j = startCol; j < d_cols; j++) {
    int aux = j - startCol;
    if (cols > aux) {
      if (updateDecimalSeparators)
        setCell(0, j, locale.toDouble(line[aux]));
      else
        setText(0, j, line[aux]);
    }
  }

  qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
  for (int i = startRow; i < d_rows; i++) {
    s = t.readLine();
    if (simplifySpaces)
      s = s.simplified();
    else if (stripSpaces)
      s = s.trimmed();
    line = s.split(sep);
    int lc = line.size();
    if (lc > cols)
      setColumnCount(d_cols + lc - cols);

    for (int j = startCol; j < d_cols; j++) {
      int aux = j - startCol;
      if (lc > aux) {
        if (updateDecimalSeparators)
          setCell(i, j, locale.toDouble(line[aux]));
        else
          setText(i, j, line[aux]);
      }
    }
  }
  f.remove(); // remove temp file
  if (d_matrix)
    d_matrix->resetView();
  QApplication::restoreOverrideCursor();
  return true;
}
Exemple #16
0
void Concentration::setCell(long value, int x, int y)
{
	setCell(value, linearPos(x, y));
}
Exemple #17
0
void
newLife(
    LIFE_T *life,
    int32_t size)
{
    life->width = size;
    life->height = size;
    life->alignedWidth = ALIGN_TO_16(life->width);
    life->alignedHeight = ALIGN_TO_16(life->height);
    life->pitch = ALIGN_TO_16(life->width);

    life->buffer = calloc(1, life->pitch * life->alignedHeight);

    if (life->buffer == NULL)
    {
        fprintf(stderr, "life: memory exhausted\n");
        exit(EXIT_FAILURE);
    }

    life->fieldLength = life->width * life->height;

    life->field = calloc(1, life->fieldLength);

    if (life->field == NULL)
    {
        fprintf(stderr, "life: memory exhausted\n");
        exit(EXIT_FAILURE);
    }

    life->fieldNext = calloc(1, life->fieldLength);

    if (life->fieldNext == NULL)
    {
        fprintf(stderr, "life: memory exhausted\n");
        exit(EXIT_FAILURE);
    }

    struct timeval tv;
    gettimeofday(&tv, NULL);
    srand(tv.tv_usec);

    int32_t row = 0;
    for (row = 0 ; row < life->height ; row++)
    {
        int32_t col = 0;
        for (col = 0 ; col < life->width ; col++)
        {
            if (rand() > (RAND_MAX / 2))
            {
                setCell(life, col, row);
            }
            else
            {
                life->buffer[col + (row * life->alignedWidth)] = DEAD;
            }
        }
    }

    //---------------------------------------------------------------------

    VC_IMAGE_TYPE_T type = VC_IMAGE_8BPP;
    uint32_t vc_image_ptr;
    int result = 0;

    life->frontResource = 
        vc_dispmanx_resource_create(
            type,
            life->width | (life->pitch << 16),
            life->height | (life->alignedHeight << 16),
            &vc_image_ptr);
    assert(life->frontResource != 0);

    life->backResource = 
        vc_dispmanx_resource_create(
            type,
            life->width | (life->pitch << 16),
            life->height | (life->alignedHeight << 16),
            &vc_image_ptr);
    assert(life->backResource != 0);

    //---------------------------------------------------------------------

    vc_dispmanx_rect_set(&(life->bmpRect), 0, 0, life->width, life->height);

    result = vc_dispmanx_resource_write_data(life->frontResource,
                                             type,
                                             life->pitch,
                                             life->buffer,
                                             &(life->bmpRect));
    assert(result == 0);

    //---------------------------------------------------------------------

    long cores = sysconf(_SC_NPROCESSORS_ONLN);

    if (cores == -1)
    {
        cores = 1;
    }

    if (cores > LIFE_MAX_THREADS)
    {
        life->numberOfThreads = LIFE_MAX_THREADS;
    }
    else
    {
        life->numberOfThreads = cores;
    }

    pthread_barrier_init(&(life->startIterationBarrier),
                         NULL,
                         life->numberOfThreads + 1);

    pthread_barrier_init(&(life->finishedIterationBarrier),
                         NULL,
                         life->numberOfThreads + 1);

    //---------------------------------------------------------------------

    int32_t heightStep = life->height / life->numberOfThreads;
    int32_t heightStart = 0;

    int32_t thread;
    for (thread = 0 ; thread < life->numberOfThreads ; thread++)
    {
        life->heightRange[thread].startHeight = heightStart;
        life->heightRange[thread].endHeight = heightStart + heightStep;

        heightStart += heightStep;

        pthread_create(&(life->threads[thread]),
                       NULL,
                       workerLife,
                       life);
    }

    thread = life->numberOfThreads - 1;
    life->heightRange[thread].endHeight = life->height;

    //---------------------------------------------------------------------

    memcpy(life->field, life->fieldNext, life->fieldLength);
    pthread_barrier_wait(&(life->startIterationBarrier));
}
Exemple #18
0
void LifeModel::setCellOff(int row, int col)
{
	setCell(row, col, 0);
}