コード例 #1
0
ファイル: MapSegment.cpp プロジェクト: Kr4w4r/citygame-engine
void CMapSegment::render(IMap* pMap)
{
	glPushMatrix();

	glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	GLfloat maxHeight = pMap->getMaxHeight();

	CVector3f color;
	for (GLint y = mUpperLeftCorner.y; y < mLowerRightCorner.y; y += getGridSize())
	{
		glBegin(GL_TRIANGLE_STRIP);
		for (GLint x = mUpperLeftCorner.x; x <= mLowerRightCorner.x; x += getGridSize())
		{
			MAP_CORNER* point = pMap->getMapCorner(x, y);
			color = getColor(point->z, maxHeight);
			glColor3f(color.x, color.y, color.z);
			glVertex3f(point->x, point->y, point->z);

			MAP_CORNER* nextPoint = pMap->getMapCorner(x, y + getGridSize());
			color = getColor(nextPoint->z, maxHeight);
			glColor3f(color.x, color.y, color.z);
			glVertex3f(nextPoint->x, nextPoint->y, nextPoint->z);
		}
		glEnd();
	}

	glPopMatrix();
}
コード例 #2
0
void TileMapCollisionResolver::sweepHorizontalEdge(const int& x, const int& yMin, const int& yMax, const Direction& directionX, CollisionInfo& collisionInfo) {
    if(!map.expired()) {
        auto mapPtr = map.lock();
        if(mapPtr) {
            const int tileX = x / mapPtr->getGridSize();
            const int tileYMin = yMin / mapPtr->getGridSize();
            const int tileYMax = yMax / mapPtr->getGridSize();

            collisionInfo.isCollisionX = false;

            for(int tileY = tileYMin; tileY <= tileYMax; tileY++) {
                const int currentTile = mapPtr->getAttributeAt(tileX, tileY);

                if(tileIsSolid(currentTile)) {
                    collisionInfo.isCollisionX = true;
                    collisionInfo.tileX = tileX;
                    collisionInfo.tileY = tileY;
                    collisionInfo.tileType = currentTile;
                    collisionInfo.directionX = directionX;

                    determineCorrection(directionX, collisionInfo);

                    return;
                }
            }
        }
    }
    return;
}
コード例 #3
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
void CPlayer::deleteMemory()
{
	short numberOfRows = (toupper(getGridSize()) == 'L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize()) == 'L') ? LARGECOLS : SMALLCOLS;
	for(short i = 0; i < NUMPLAYERS; ++i)
	{
		if (m_gameGrid[0] != nullptr)
		{
			for(short j = 0; j < numberOfRows; ++j)
			{
				if (m_gameGrid[0][j] != nullptr)
					delete[] m_gameGrid[0][j];
			} // end for i
			delete[] m_gameGrid[0];
			m_gameGrid[0] = nullptr;
		}
		if (m_gameGrid[1] != nullptr)
		{	
			for(short j = 0; j < numberOfRows; ++j)
			{
				if (m_gameGrid[1][j] != nullptr)
					delete[] m_gameGrid[1][j];
			} // end for i
			delete[] m_gameGrid[1];
			m_gameGrid[1] = nullptr;
		}
	} // end for j
}
コード例 #4
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
void CPlayer::printGrid(ostream & sout, short whichGrid) const
{
	short numberOfRows = (toupper(getGridSize()) == 'L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize()) == 'L') ? LARGECOLS : SMALLCOLS;

	for(short j = 1; j <= numberOfCols; ++j)
	{
		sout << setw(3) << j;	
	}
	sout << endl;

	for(short i = 1; i <= numberOfRows; ++i)
	{
		sout  << static_cast<char>(64 + i);
		for(short j = 1; j <= numberOfCols; ++j)
		{
			m_gameGrid[whichGrid][i][j].printShip(sout);
		} 
		sout  << endl;
		sout  << " ";
		for(short j = 1; j <= numberOfCols; ++j)
		{
			sout << HORIZ << HORIZ << CL;
		}
		sout  << endl;
	}
}
コード例 #5
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
void CPlayer::allocateMemory()
{
	char * p = nullptr;
	short numberOfRows = (toupper(getGridSize()) == 'L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize()) == 'L') ? LARGECOLS : SMALLCOLS;

	for(short i = 0; i < NUMPLAYERS; ++i)
	{
		m_gameGrid[0] = nullptr;
		m_gameGrid[0] = new CShip*[numberOfRows];
		m_gameGrid[1] = nullptr;
		m_gameGrid[1] = new CShip*[numberOfRows];
		for(short j = 0; j < numberOfRows; ++j)
		{
			m_gameGrid[0][j] = nullptr;
			m_gameGrid[0][j] = new CShip[numberOfCols];
			m_gameGrid[1][j] = nullptr;
			m_gameGrid[1][j] = new CShip[numberOfCols];
			for(short k = 0; k < numberOfCols; ++k)
			{
				m_gameGrid[0][j][k] = CShip::NOSHIP;
				m_gameGrid[1][j][k] = CShip::NOSHIP;
			} // end for k
		} // end for j
	} // end for i

}
コード例 #6
0
void TileMapCollisionResolver::sweepVerticalEdge(const int& y, const int& xMin, const int& xMax, const Direction& directionY, CollisionInfo& collisionInfo) {
    if(!map.expired()) {
        auto mapPtr = map.lock();
        if(mapPtr) {
            const int tileY = y / mapPtr->getGridSize();
            const int tileXMin = xMin / mapPtr->getGridSize();
            const int tileXMax = xMax / mapPtr->getGridSize();

            collisionInfo.isCollisionY = false;

            for(int tileX = tileXMin; tileX <= tileXMax; tileX++) {
                const int currentTile = mapPtr->getAttributeAt(tileX, tileY);

                // Here we check for ladder tops as well as solid ground.
                // Ladder tops are only "solid" if you're falling "down" on them.
                if(tileIsSolid(currentTile) || (collisionInfo.treatPlatformAsGround && tileIsPlatform(currentTile) && directionY == Directions::Down)) {
                    collisionInfo.isCollisionY = true;
                    collisionInfo.tileX = tileX;
                    collisionInfo.tileY = tileY;
                    collisionInfo.tileType = currentTile;
                    collisionInfo.directionY = directionY;

                    determineCorrection(directionY, collisionInfo);

                    return;
                }
            }
        }
    }
    return;
}
コード例 #7
0
ファイル: Room.cpp プロジェクト: Faianca/hikari
    void Room::traceLadders() {
        for(int x = 0; x < getWidth(); ++x) {
            bool topFound = false;
            bool bottomFound = false;
            int ladderTop = 0;
            int ladderX = 0;
            int ladderBottom = 0;

            for(int y = 0; y < getHeight(); ++y) {
                int attribute = attr[x + (y * getWidth())];

                if(TileAttribute::hasAttribute(attribute, TileAttribute::LADDER)) {
                    if(!topFound) {
                        topFound = true;
                        ladderTop = y;
                        ladderX = x;
                    }

                    // Find ladder at the bottom of the map
                    if(y == getHeight() - 1) {
                        if(topFound) {
                            bottomFound = true;
                            ladderBottom = y + 1;
                        }
                    }
                } else {
                    if(topFound) {
                        if(!bottomFound) {
                            bottomFound = true;
                            ladderBottom = y;
                        }
                    }
                }

                if(topFound && bottomFound) {
                    ladders.emplace_back(
                        BoundingBox<float>(
                            static_cast<float>(((getX() + ladderX) * getGridSize()) + 4  ), // ladder top left X (in pixels)
                            static_cast<float>((getY() + ladderTop) * getGridSize()      ), // ladder top left Y (in pixels)
                            static_cast<float>(getGridSize() - 4 - 4                     ), // ladder width      (in pixels)
                            static_cast<float>((ladderBottom - ladderTop) * getGridSize())  // ladder height     (in pixels)
                        )
                    );

                    HIKARI_LOG(debug4) << "Found ladder at " << ladders.back();

                    topFound = false;
                    bottomFound = false;
                    ladderX = 0;
                    ladderBottom = 0;
                    ladderTop = 0;
                }
            }
        }
    }
コード例 #8
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
void CPlayer::saveGrid()
{
	short numberOfRows = (toupper(getGridSize()) == 'L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize()) == 'L') ? LARGECOLS : SMALLCOLS;	
	std::ofstream;
	string name_output_file;
	string name_output_file_final;
	char size_of_grid;
	cout <<"Enter the name of an output file: ";
	cin >> name_output_file;
	name_output_file_final = name_output_file + ".shp"; 
	ofstream ofs;
	ofs.open(name_output_file_final);
	if(!ofs)
	{
		cout << "could not open file " << name_output_file << endl;
	}
	// print out the grid size for the 1st line of the output file
	else
	{
		if  (getGridSize() == 'L')
		{
			size_of_grid = 'L';
			ofs.put(size_of_grid);
			ofs << endl;
		}
		else if (getGridSize() == 'S')
		{
			size_of_grid = 'S';
			ofs.put(size_of_grid);
			ofs << endl;
		}
		// print out the location of the ship
		// 1st number is the orientation
		// 2nd number is the row
		// 3nd number is the column
		// one ship per line
		for (int i = 1; i < SHIP_SIZE_ARRAYSIZE; i++)
		{
			ofs << static_cast<int>(CDirection::Direction((m_ships[i].getOrientation())));
			ofs << " ";
			ofs << m_ships[i].getCell().getRow();
			ofs << " ";
			ofs << m_ships[i].getCell().getCol();
			ofs << endl;
		}
		cout << name_output_file_final << " is saved." << endl;
		ofs.close();
	}
}
コード例 #9
0
ファイル: QtVSGItem.cpp プロジェクト: creepydragon/r2
QVariant QtVSGItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant& value)
{
    if(change == QGraphicsItem::ItemSelectedChange)
    {
        updateSelection(value.toBool());
    }
    else if(change == QGraphicsItem::ItemPositionChange)
    {
        qreal x = round(value.toPointF().x() / getGridSize()) * getGridSize();
        qreal y = round(value.toPointF().y() / getGridSize()) * getGridSize();
        return QPointF(x, y);
    }

    return QGraphicsPathItem::itemChange(change, value);
}
コード例 #10
0
//----------------------------------------------------------------------------//
void GridLayoutContainer::layout()
{
    std::vector<UDim> colSizes(d_gridWidth, UDim(0, 0));
    std::vector<UDim> rowSizes(d_gridHeight, UDim(0, 0));

    // used to compare UDims
    const float absWidth = getChildContentArea().get().getWidth();
    const float absHeight = getChildContentArea().get().getHeight();

    // first, we need to determine rowSizes and colSizes, this is needed before
    // any layouting work takes place
    for (size_t y = 0; y < d_gridHeight; ++y)
    {
        for (size_t x = 0; x < d_gridWidth; ++x)
        {
            // x and y is the position of window in the grid
            const size_t childIdx =
                mapFromGridToIdx(x, y, d_gridWidth, d_gridHeight);

            Window* window = getChildAtIdx(childIdx);
            const UVector2 size = getBoundingSizeForWindow(window);

            if (CoordConverter::asAbsolute(colSizes[x], absWidth) <
                CoordConverter::asAbsolute(size.d_x, absWidth))
            {
                colSizes[x] = size.d_x;
            }

            if (CoordConverter::asAbsolute(rowSizes[y], absHeight) <
                CoordConverter::asAbsolute(size.d_y, absHeight))
            {
                rowSizes[y] = size.d_y;
            }
        }
    }

    // OK, now in rowSizes[y] is the height of y-th row
    //         in colSizes[x] is the width of x-th column

    // second layouting phase starts now
    for (size_t y = 0; y < d_gridHeight; ++y)
    {
        for (size_t x = 0; x < d_gridWidth; ++x)
        {
            // x and y is the position of window in the grid
            const size_t childIdx = mapFromGridToIdx(x, y,
                                                     d_gridWidth, d_gridHeight);
            Window* window = getChildAtIdx(childIdx);
            const UVector2 offset = getOffsetForWindow(window);
            const UVector2 gridCellOffset = getGridCellOffset(colSizes,
                                                              rowSizes,
                                                              x, y);

            window->setPosition(gridCellOffset + offset);
        }
    }

    // now we just need to determine the total width and height and set it
    setSize(getGridSize(colSizes, rowSizes));
}
コード例 #11
0
void TileMapCollisionResolver::determineCorrection(const Direction& direction, CollisionInfo& collisionInfo) {
    if(!map.expired()) {
        auto mapPtr = map.lock();
        if(mapPtr) {
            const int tileSize = mapPtr->getGridSize();

            tileBounds
            .setPosition(collisionInfo.tileX * tileSize, collisionInfo.tileY * tileSize);

            if(direction == Directions::Left) {
                // Collision happened on the left edge, so return the X for the RIGHT side of the tile.
                collisionInfo.correctedX = tileBounds.getRight();
            } else if(direction == Directions::Right) {
                // Collision happened on the right edge, so just set the X position.
                collisionInfo.correctedX = tileBounds.getLeft();
            } else if(direction == Directions::Up) {
                // Collision happened on the bottom edge, to just set the Y position?
                collisionInfo.correctedY = tileBounds.getBottom();
            } else if(direction == Directions::Down) {
                // Collision happened on the top edge, so take height into consideration?
                collisionInfo.correctedY = tileBounds.getTop();
            }
        }
    }
}
コード例 #12
0
bool OccupancyGrid::saveGridToBinaryFile(std::string filename)
{
  ofstream fout;
  int dimx,dimy,dimz;
  unsigned char val = 0;
  struct stat file_stats;

  getGridSize(dimx, dimy, dimz);

  const char *name  = filename.c_str();
  fout.open(name, ios_base::out | ios_base::binary | ios_base::trunc);

  if (fout.is_open())
  {
    fout.write( (char *) &dimx, sizeof(int));
    fout.write( (char *) &dimy, sizeof(int));
    fout.write( (char *) &dimz, sizeof(int));

    for(int x = 0; x < dimx; x++)
    {
      for(int y = 0; y < dimy; y++)
      {
        for(int z = 0; z < dimz; z++)
        {
          val = getCell(x,y,z);
          fout.write( (char *) &val, sizeof(unsigned char));
        }
      }
    }
  }
  else
  {
    ROS_ERROR("[saveGridToBinaryFile] Failed to open file for writing.\n");
    return false;
  }

  fout.close();

  //verify writing to file was successful
  if(stat(name, &file_stats) == 0)
  {
    ROS_INFO("[saveGridToBinaryFile] The size of the file created is %d kb.\n", int(file_stats.st_size)/1024);
    if(file_stats.st_size == 0)
    {
      ROS_ERROR("[saveGridToBinaryFile] File created is empty. Exiting.\n");
      return false;
    }
  }
  else
  {
    ROS_ERROR("[saveGridToBinaryFile] An error occurred when retrieving size of file created. Exiting.\n");
    return false;
  }

  return true;
}
コード例 #13
0
ファイル: dialog_set_grid.cpp プロジェクト: myutwo/kicad
void DIALOG_SET_GRID::OnOkClick( wxCommandEvent& event )
{
    m_callers_grid_units = getGridUnits();
    m_callers_user_size  = getGridSize();
    m_callers_origin     = getGridOrigin();

    getGridForFastSwitching( m_callers_fast_grid1, m_callers_fast_grid2 );

    EndModal( wxID_OK );
}
コード例 #14
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
CPlayer CPlayer::operator=(const CPlayer& copyCPlayer)
{
	m_whichPlayer = !copyCPlayer.getWhichPlayer(); 
	m_gridSize = copyCPlayer.getGridSize();
	short numberOfRows = (toupper(getGridSize()) == 'L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize()) == 'L') ? LARGECOLS : SMALLCOLS;
	m_piecesLeft = copyCPlayer.getPiecesLeft();
	for (int i = 0; i < SHIP_SIZE_ARRAYSIZE; i++)
		m_ships[i] = copyCPlayer.m_ships[i];
	CCell token(0,0);
	for (int i = 0; i < NUMPLAYERS; i++)
		for (int j = 0; j < numberOfRows; j++)
		{
			for (int k = 0; k <numberOfCols; k++)
			{
				m_gameGrid[i][j][k] = copyCPlayer.getCell(i, token);
				token.increaseCol();
			}
			token.increaseRow();
		}
		return *this;
}
コード例 #15
0
ファイル: QtVSGCommentItem.cpp プロジェクト: creepydragon/r2
void QtVSGCommentItem::mouseMoveEvent(QGraphicsSceneMouseEvent* event)
{
    if(m_inResizeMode)
    {
        QPointF delta = pos() - event->scenePos();

        qreal x = round(delta.x() / getGridSize()) * getGridSize();
        qreal y = round(delta.y() / getGridSize()) * getGridSize();

        x = qAbs(qMin(x, qreal(-32.f)));
        y = qAbs(qMin(y, qreal(-32.f)));

        QPainterPath painter;
        painter.addRect(QRectF(QPointF(0, 0), QPointF(x, y)));
        setPath(painter);

        m_textItem->setY(y);
    }
    else
    {
        QGraphicsItem::mouseMoveEvent(event);
    }
}
コード例 #16
0
void TileMapCollisionResolver::setRoom(std::weak_ptr<Room> newRoom) {
    map = newRoom;

    if(!map.expired()) {
        auto mapPtr = map.lock();
        if(mapPtr) {
            const int tileSize = mapPtr->getGridSize();

            tileBounds
            .setWidth(tileSize)
            .setHeight(tileSize);
        }
    }
}
コード例 #17
0
size_t TestParticleSetting1::fillGrid(std::vector<bool>& level_set) {

  size_t xgridsize, ygridsize, zgridsize;
  double xleft, yleft, zleft, xright, yright, zright;
  double dx, dy, dz;

  getGridSize(xgridsize, ygridsize, zgridsize);
  getDomain(xleft, yleft, zleft, xright, yright, zright);

  dx = (xright-xleft)/xgridsize;
  dy = (yright-yleft)/ygridsize;
  dz = (zright-zleft)/zgridsize;

  level_set.clear();

  size_t size = (xgridsize+1)*(ygridsize+1)*(zgridsize+1);

  level_set.resize(size);

  //Now fill up the grid.
  size_t index;
  for (size_t k = 0; k < zgridsize; ++k) {
    for (size_t j = 0; j < ygridsize; ++j) {
	    for (size_t i = 0; i < xgridsize; ++i) {
        index = i + j*xgridsize + k*xgridsize*ygridsize;
        //A diamond shaped region.
        //double temp = fabs( xleft + i*dx - 0.128) + fabs( yleft + j*dy - 0.128) + fabs( zleft + k*dz - 0.128);
        if ( fabs( xleft + i*dx - 0.128) + fabs( yleft + j*dy - 0.128) + fabs( zleft + k*dz - 0.576) <= 0.128 ) {
	     	  level_set[index] = true;
	     	} else {
	     	  level_set[index] = false;
	     	}     
         
	    }
	  }
  }

  return size;
}
コード例 #18
0
void DIALOG_SET_GRID::OnOkClick( wxCommandEvent& event )
{
    bool success  = getGridSize( m_callers_user_size );

    if( !success )
    {
        wxMessageBox( wxString::Format( _( "Incorrect grid size (size must be >= %.3f mm and <= %.3f mm)"),
            MIN_GRID_SIZE/IU_PER_MM, MAX_GRID_SIZE/IU_PER_MM ) );
        return;
    }

    success = getGridOrigin( m_callers_origin );

    if( !success )
    {
        wxMessageBox( wxString::Format( _( "Incorrect grid origin (coordinates must be >= %.3f mm and <= %.3f mm)" ),
            -MAX_GRID_OFFSET/IU_PER_MM, MAX_GRID_OFFSET/IU_PER_MM ) );
        return;
    }

    getGridForFastSwitching( m_callers_fast_grid1, m_callers_fast_grid2 );

    EndModal( wxID_OK );
}
コード例 #19
0
//debug!vb也应该生成一个新的!
void VertexCluster::generateLOD(float level,ID3D10BufferPtr &vb,ID3D10BufferPtr &ib,UINT &ibLength)  //mVertexValueCreated=true
{

	 //Common::timeBegin();


	D3D10_BUFFER_DESC desc;
	desc.BindFlags= D3D10_BIND_INDEX_BUFFER;
	desc.CPUAccessFlags=0;
	desc.MiscFlags=0;
	desc.Usage=D3D10_USAGE_DEFAULT;

	D3D10_SUBRESOURCE_DATA initData;

	if(level<=0.0f)
	{
		vb=mOriginalVB;
		ib=mOriginalIB;
		ibLength=mIndicesNum;
		return ;
	}

	mTolerance=getGridSize(level);
	mHashTable->init(mTolerance);

	//Common::log("mTolerance",mTolerance);

	int i,ri;
	for(i=0;i<mVerticesNum;i++)
	{
		ri=mWeights[i].mID;
		mHashTable->addVertex(ri,locateVertex(ri),mWeights[i].mWeight); 
	}

	ibLength=0;
	int a,b,c;
	int ra,rb,rc;
	for(i=0;i<mIndicesNum;i+=3)
	{
		a=mIndices[i];
		b=mIndices[i+1];
		c=mIndices[i+2];

		ra=mHashTable->getReplacedID(a);
		rb=mHashTable->getReplacedID(b);
		rc=mHashTable->getReplacedID(c);

		if(ra!=rb && ra!=rc && rb!=rc)
		{
			mLODIB[ibLength++]=ra;
			mLODIB[ibLength++]=rb;
			mLODIB[ibLength++]=rc;


			//Common::log("lod face index a",ra);
			//Common::log("lod face index b",rb);
			//Common::log("lod face index c",rc);
		}
	}

	//for(i=0;i<mVerticesNum;i++)
	//	Common::log("ReplacedID",mHashTable->getReplacedID(i));

	//Common::log("LOD generated! with Indices num",ibLength);
	if(ibLength==0)
	{
		vb=NULL;
		ib=NULL;
		return;
	}
	desc.ByteWidth=sizeof(DWORD)*ibLength;
	initData.pSysMem=mLODIB;
	mDevice->CreateBuffer(&desc,&initData,&ib);


	// for(i=0;i<ibLength;i++)
	//	Common::log("IB",mLODIB[i]);


	desc.BindFlags=D3D10_BIND_VERTEX_BUFFER;
	desc.ByteWidth=mStride*mHashTable->getCellsNum();
	initData.pSysMem=mHashTable->getCellsVB();
	mDevice->CreateBuffer(&desc,&initData,&vb);



	//  for(i=0;i<mHashTable->getCellsNum();i++)
	//	Common::log("LOD VB",*mHashTable->locateVertex(i));



	//Common::log("LOD generating time",Common::timeEnd());
}
コード例 #20
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
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;
}
コード例 #21
0
unsigned int TileMap::getTotalGridSize() const
{
	return totalSizeFromSizeVector(getGridSize());
}
コード例 #22
0
ファイル: CPlayer.cpp プロジェクト: sonminhtran1997/C-project
bool CPlayer::isValidLocation(short whichShip)
{
	short numberOfRows = (toupper(getGridSize())=='L') ? LARGEROWS : SMALLROWS;
	short numberOfCols = (toupper(getGridSize())=='L') ? LARGECOLS : SMALLCOLS;

	// our code
	if (m_ships[whichShip].getOrientation() == CDirection::VERTICAL)
	{
		if(shipSize[whichShip] == 2)
		{
			if(m_ships[whichShip].getCell().getRow() == (numberOfRows - 1))
				return false;
		}
		if (shipSize[whichShip] == 3)
		{
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 1))
				return false;
			if(m_ships[whichShip].getCell().getRow() == (numberOfRows - 2))
				return false;
		}
		if (shipSize[whichShip] == 4)
		{
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 1))
				return false;
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 2))
				return false;
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 3))
				return false;
		}
		if (shipSize[whichShip] == 5)
		{
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 1))
				return false;
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 2))
				return false;
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 3))
				return false;
			if (m_ships[whichShip].getCell().getRow() == (numberOfRows - 4))
				return false;
		}
	} // end for 'V'
	if (m_ships[whichShip].getOrientation() == CDirection::HORIZONTAL)
	{
		if (shipSize[whichShip] == 2)
		{
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 1))
				return false;
		}
		if (shipSize[whichShip] == 3)
		{
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 1))
				return false;
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 2))
				return false;
		}
		if (shipSize[whichShip] == 4)
		{
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 1))
				return false;
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 2))
				return false;
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 3))
				return false;
		}
		if (shipSize[whichShip] == 5)
		{
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 1))
				return false;
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 2))
				return false;
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 3))
				return false;
			if (m_ships[whichShip].getCell().getCol() == (numberOfCols - 4))
				return false;
		}
	} // end for 'H'
	if (m_ships[whichShip].getOrientation() == CDirection::HORIZONTAL)
	{
		int i = static_cast<int>(shipSize[whichShip]);
		for (int x = 0; x < (i-1); x++)
		{
			if (m_gameGrid[0][m_ships[whichShip].getCell().getRow()]
			[m_ships[whichShip].getCell().getCol() + x] != CShip::NOSHIP)
				return false;
		}	
	}
	if (m_ships[whichShip].getOrientation() == CDirection::VERTICAL)
	{
		int i = static_cast<int>(shipSize[whichShip]);
		for (int x = 0; x < i; x++)
		{
			if (m_gameGrid[0][m_ships[whichShip].getCell().getRow() + x]
			[m_ships[whichShip].getCell().getCol()] != CShip::NOSHIP)
				return false;
		}	
	}
	return true;
}
コード例 #23
0
ファイル: selfsimilarity.cpp プロジェクト: 2693/opencv
void SelfSimDescriptor::compute(const Mat& img, vector<float>& descriptors, Size winStride,
                                const vector<Point>& locations) const
{
    CV_Assert( img.depth() == CV_8U );

    winStride.width = std::max(winStride.width, 1);
    winStride.height = std::max(winStride.height, 1);
    Size gridSize = getGridSize(img.size(), winStride);
    int i, nwindows = locations.empty() ? gridSize.width*gridSize.height : (int)locations.size();
    int border = largeSize/2 + smallSize/2;
    int fsize = (int)getDescriptorSize();
    vector<float> tempFeature(fsize+1);
    descriptors.resize(fsize*nwindows + 1);
    Mat ssd(largeSize, largeSize, CV_32F), mappingMask;
    computeLogPolarMapping(mappingMask);

#if 0 //def _OPENMP
    int nthreads = cvGetNumThreads();
    #pragma omp parallel for num_threads(nthreads)
#endif
    for( i = 0; i < nwindows; i++ )
    {
        Point pt;
        float* feature0 = &descriptors[fsize*i];
        float* feature = &tempFeature[0];
        int x, y, j;

        if( !locations.empty() )
        {
            pt = locations[i];
            if( pt.x < border || pt.x >= img.cols - border ||
                pt.y < border || pt.y >= img.rows - border )
            {
                for( j = 0; j < fsize; j++ )
                    feature0[j] = 0.f;
                continue;
            }
        }
        else
            pt = Point((i % gridSize.width)*winStride.width + border,
                       (i / gridSize.width)*winStride.height + border);

        SSD(img, pt, ssd);

        // Determine in the local neighborhood the largest difference and use for normalization
        float var_noise = 1000.f;
        for( y = -1; y <= 1 ; y++ )
            for( x = -1 ; x <= 1 ; x++ )
                var_noise = std::max(var_noise, ssd.at<float>(largeSize/2+y, largeSize/2+x));

        for( j = 0; j <= fsize; j++ )
            feature[j] = FLT_MAX;

        // Derive feature vector before exp(-x) computation
        // Idea: for all  x,a >= 0, a=const.   we have:
        //       max [ exp( -x / a) ] = exp ( -min(x) / a )
        // Thus, determine min(ssd) and store in feature[...]
        for( y = 0; y < ssd.rows; y++ )
        {
            const schar *mappingMaskPtr = mappingMask.ptr<schar>(y);
            const float *ssdPtr = ssd.ptr<float>(y);
            for( x = 0 ; x < ssd.cols; x++ )
            {
                int index = mappingMaskPtr[x];
                feature[index] = std::min(feature[index], ssdPtr[x]);
            }
        }

        var_noise = -1.f/var_noise;
        for( j = 0; j < fsize; j++ )
            feature0[j] = feature[j]*var_noise;
        Mat _f(1, fsize, CV_32F, feature0);
        cv::exp(_f, _f);
    }
}
コード例 #24
0
bool ccVolumeCalcTool::updateGrid()
{
    if (!m_cloud2)
    {
        assert(false);
        return false;
    }

    //cloud bounding-box --> grid size
    ccBBox box = getCustomBBox();
    if (!box.isValid())
    {
        return false;
    }

    unsigned gridWidth = 0, gridHeight = 0;
    if (!getGridSize(gridWidth, gridHeight))
    {
        return false;
    }

    //grid size
    unsigned gridTotalSize = gridWidth * gridHeight;
    if (gridTotalSize == 1)
    {
        if (QMessageBox::question(this, "Unexpected grid size", "The generated grid will only have 1 cell! Do you want to proceed anyway?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
            return false;
    }
    else if (gridTotalSize > 10000000)
    {
        if (QMessageBox::question(this, "Big grid size", "The generated grid will have more than 10.000.000 cells! Do you want to proceed anyway?", QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
            return false;
    }

    //grid step
    double gridStep = getGridStep();
    assert(gridStep != 0);

    //memory allocation
    CCVector3d minCorner = CCVector3d::fromArray(box.minCorner().u);
    if (!m_grid.init(gridWidth, gridHeight, gridStep, minCorner))
    {
        //not enough memory
        ccLog::Error("Not enough memory");
        return false;
    }

    //ground
    ccGenericPointCloud* groundCloud = 0;
    double groundHeight = 0;
    switch (groundComboBox->currentIndex())
    {
    case 0:
        groundHeight =	groundEmptyValueDoubleSpinBox->value();
        break;
    case 1:
        groundCloud = m_cloud1 ? m_cloud1 : m_cloud2;
        break;
    case 2:
        groundCloud = m_cloud2;
        break;
    default:
        assert(false);
        return false;
    }

    //vertical dimension
    const unsigned char Z = getProjectionDimension();
    assert(Z >= 0 && Z <= 2);
    //per-cell Z computation
    ccRasterGrid::ProjectionType projectionType = getTypeOfProjection();

    ccProgressDialog pDlg(true, this);

    ccRasterGrid groundRaster;
    if (groundCloud)
    {
        if (!groundRaster.init(gridWidth, gridHeight, gridStep, minCorner))
        {
            //not enough memory
            ccLog::Error("Not enough memory");
            return false;
        }

        if (groundRaster.fillWith(	groundCloud,
                                    Z,
                                    projectionType,
                                    getFillEmptyCellsStrategy(fillGroundEmptyCellsComboBox) == ccRasterGrid::INTERPOLATE,
                                    ccRasterGrid::INVALID_PROJECTION_TYPE,
                                    &pDlg))
        {
            groundRaster.fillEmptyCells(getFillEmptyCellsStrategy(fillGroundEmptyCellsComboBox), groundEmptyValueDoubleSpinBox->value());
            ccLog::Print(QString("[Volume] Ground raster grid: size: %1 x %2 / heights: [%3 ; %4]").arg(m_grid.width).arg(m_grid.height).arg(m_grid.minHeight).arg(m_grid.maxHeight));
        }
        else
        {
            return false;
        }
    }

    //ceil
    ccGenericPointCloud* ceilCloud = 0;
    double ceilHeight = 0;
    switch (ceilComboBox->currentIndex())
    {
    case 0:
        ceilHeight = ceilEmptyValueDoubleSpinBox->value();
        break;
    case 1:
        ceilCloud = m_cloud1 ? m_cloud1 : m_cloud2;
        break;
    case 2:
        ceilCloud = m_cloud2;
        break;
    default:
        assert(false);
        return false;
    }

    ccRasterGrid ceilRaster;
    if (ceilCloud)
    {
        if (!ceilRaster.init(gridWidth, gridHeight, gridStep, minCorner))
        {
            //not enough memory
            ccLog::Error("Not enough memory");
            return false;
        }

        if (ceilRaster.fillWith(ceilCloud,
                                Z,
                                projectionType,
                                getFillEmptyCellsStrategy(fillCeilEmptyCellsComboBox) == ccRasterGrid::INTERPOLATE,
                                ccRasterGrid::INVALID_PROJECTION_TYPE,
                                &pDlg))
        {
            ceilRaster.fillEmptyCells(getFillEmptyCellsStrategy(fillCeilEmptyCellsComboBox), ceilEmptyValueDoubleSpinBox->value());
            ccLog::Print(QString("[Volume] Ceil raster grid: size: %1 x %2 / heights: [%3 ; %4]").arg(m_grid.width).arg(m_grid.height).arg(m_grid.minHeight).arg(m_grid.maxHeight));
        }
        else
        {
            return false;
        }
    }

    //update grid and compute volume
    {
        pDlg.setMethodTitle(tr("Volume computation"));
        pDlg.setInfo(tr("Cells: %1 x %2").arg(m_grid.width).arg(m_grid.height));
        pDlg.start();
        pDlg.show();
        QCoreApplication::processEvents();
        CCLib::NormalizedProgress nProgress(&pDlg, m_grid.width*m_grid.height);

        ReportInfo repotInfo;
        size_t ceilNonMatchingCount = 0;
        size_t groundNonMatchingCount = 0;
        size_t cellCount = 0;

        //at least one of the grid is based on a cloud
        m_grid.nonEmptyCellCount = 0;
        for (unsigned i = 0; i < m_grid.height; ++i)
        {
            for (unsigned j = 0; j < m_grid.width; ++j)
            {
                ccRasterCell& cell = m_grid.rows[i][j];

                bool validGround = true;
                cell.minHeight = groundHeight;
                if (groundCloud)
                {
                    cell.minHeight = groundRaster.rows[i][j].h;
                    validGround = std::isfinite(cell.minHeight);
                }

                bool validCeil = true;
                cell.maxHeight = ceilHeight;
                if (ceilCloud)
                {
                    cell.maxHeight = ceilRaster.rows[i][j].h;
                    validCeil = std::isfinite(cell.maxHeight);
                }

                if (validGround && validCeil)
                {
                    cell.h = cell.maxHeight - cell.minHeight;
                    cell.nbPoints = 1;

                    repotInfo.volume += cell.h;
                    if (cell.h < 0)
                    {
                        repotInfo.removedVolume -= cell.h;
                    }
                    else if (cell.h > 0)
                    {
                        repotInfo.addedVolume += cell.h;
                    }
                    repotInfo.surface += 1.0;
                    ++m_grid.nonEmptyCellCount; //= matching count
                    ++cellCount;
                }
                else
                {
                    if (validGround)
                    {
                        ++cellCount;
                        ++groundNonMatchingCount;
                    }
                    else if (validCeil)
                    {
                        ++cellCount;
                        ++ceilNonMatchingCount;
                    }
                    cell.h = std::numeric_limits<double>::quiet_NaN();
                    cell.nbPoints = 0;
                }

                cell.avgHeight = (groundHeight + ceilHeight) / 2;
                cell.stdDevHeight = 0;

                if (!nProgress.oneStep())
                {
                    ccLog::Warning("[Volume] Process cancelled by the user");
                    return false;
                }
            }
        }
        m_grid.validCellCount = m_grid.nonEmptyCellCount;

        //count the average number of valid neighbors
        {
            size_t validNeighborsCount = 0;
            size_t count = 0;
            for (unsigned i = 1; i < m_grid.height - 1; ++i)
            {
                for (unsigned j = 1; j < m_grid.width - 1; ++j)
                {
                    ccRasterCell& cell = m_grid.rows[i][j];
                    if (cell.h == cell.h)
                    {
                        for (unsigned k = i - 1; k <= i + 1; ++k)
                        {
                            for (unsigned l = j - 1; l <= j + 1; ++l)
                            {
                                if (k != i || l != j)
                                {
                                    ccRasterCell& otherCell = m_grid.rows[k][l];
                                    if (std::isfinite(otherCell.h))
                                    {
                                        ++validNeighborsCount;
                                    }
                                }
                            }
                        }

                        ++count;
                    }
                }
            }

            if (count)
            {
                repotInfo.averageNeighborsPerCell = static_cast<double>(validNeighborsCount) / count;
            }
        }

        repotInfo.matchingPrecent = static_cast<float>(m_grid.validCellCount * 100) / cellCount;
        repotInfo.groundNonMatchingPercent = static_cast<float>(groundNonMatchingCount * 100) / cellCount;
        repotInfo.ceilNonMatchingPercent = static_cast<float>(ceilNonMatchingCount * 100) / cellCount;
        float cellArea = static_cast<float>(m_grid.gridStep * m_grid.gridStep);
        repotInfo.volume *= cellArea;
        repotInfo.addedVolume *= cellArea;
        repotInfo.removedVolume *= cellArea;
        repotInfo.surface *= cellArea;

        outputReport(repotInfo);
    }

    m_grid.setValid(true);

    return true;
}
コード例 #25
0
bool ccVolumeCalcTool::updateGrid()
{
	if (!m_cloud2)
	{
		assert(false);
		return false;
	}

	//cloud bounding-box --> grid size
	ccBBox box = getCustomBBox();
	if (!box.isValid())
	{
		return false;
	}

	unsigned gridWidth = 0, gridHeight = 0;
	if (!getGridSize(gridWidth, gridHeight))
	{
		return false;
	}

	//grid step
	double gridStep = getGridStep();
	assert(gridStep != 0);

	//ground
	ccGenericPointCloud* groundCloud = 0;
	double groundHeight = 0;
	switch (groundComboBox->currentIndex())
	{
	case 0:
		groundHeight = groundEmptyValueDoubleSpinBox->value();
		break;
	case 1:
		groundCloud = m_cloud1 ? m_cloud1 : m_cloud2;
		break;
	case 2:
		groundCloud = m_cloud2;
		break;
	default:
		assert(false);
		return false;
	}

	//ceil
	ccGenericPointCloud* ceilCloud = 0;
	double ceilHeight = 0;
	switch (ceilComboBox->currentIndex())
	{
	case 0:
		ceilHeight = ceilEmptyValueDoubleSpinBox->value();
		break;
	case 1:
		ceilCloud = m_cloud1 ? m_cloud1 : m_cloud2;
		break;
	case 2:
		ceilCloud = m_cloud2;
		break;
	default:
		assert(false);
		return false;
	}

	ccVolumeCalcTool::ReportInfo reportInfo;

	if (ComputeVolume(	m_grid,
						groundCloud,
						ceilCloud,
						box,
						getProjectionDimension(),
						gridStep,
						gridWidth,
						gridHeight,
						getTypeOfProjection(),
						getFillEmptyCellsStrategy(fillGroundEmptyCellsComboBox),
						reportInfo,
						groundHeight,
						ceilHeight,
						this))
	{	
		outputReport(reportInfo);
		return true;
	}
	else
	{
		return false;
	}
}
コード例 #26
0
ファイル: mainwindow.cpp プロジェクト: Marc34/mupen64plus-qt
void MainWindow::addToGridView(Rom *currentRom, int count)
{
    ClickableWidget *gameGridItem = new ClickableWidget(gridWidget);
    gameGridItem->setMinimumWidth(getGridSize("width"));
    gameGridItem->setMaximumWidth(getGridSize("width"));
    gameGridItem->setGraphicsEffect(getShadow(false));

    //Assign ROM data to widget for use in click events
    gameGridItem->setProperty("fileName", currentRom->fileName);
    gameGridItem->setProperty("directory", currentRom->directory);
    if (currentRom->goodName == getTranslation("Unknown ROM") ||
        currentRom->goodName == getTranslation("Requires catalog file"))
        gameGridItem->setProperty("search", currentRom->internalName);
    else
        gameGridItem->setProperty("search", currentRom->goodName);
    gameGridItem->setProperty("romMD5", currentRom->romMD5);
    gameGridItem->setProperty("zipFile", currentRom->zipFile);

    QGridLayout *gameGridLayout = new QGridLayout(gameGridItem);
    gameGridLayout->setColumnStretch(0, 1);
    gameGridLayout->setColumnStretch(3, 1);
    gameGridLayout->setRowMinimumHeight(1, getImageSize("Grid").height());

    QLabel *gridImageLabel = new QLabel(gameGridItem);
    gridImageLabel->setMinimumHeight(getImageSize("Grid").height());
    gridImageLabel->setMinimumWidth(getImageSize("Grid").width());
    QPixmap image;

    if (currentRom->imageExists) {
        //Use uniform aspect ratio to account for fluctuations in TheGamesDB box art
        Qt::AspectRatioMode aspectRatioMode = Qt::IgnoreAspectRatio;

        //Don't warp aspect ratio though if image is too far away from standard size (JP box art)
        float aspectRatio = float(currentRom->image.width()) / currentRom->image.height();

        if (aspectRatio < 1.1 || aspectRatio > 1.8)
            aspectRatioMode = Qt::KeepAspectRatio;

        image = currentRom->image.scaled(getImageSize("Grid"), aspectRatioMode, Qt::SmoothTransformation);
    } else
        image = QPixmap(":/images/not-found.png").scaled(getImageSize("Grid"), Qt::IgnoreAspectRatio,
                                                         Qt::SmoothTransformation);

    gridImageLabel->setPixmap(image);
    gridImageLabel->setAlignment(Qt::AlignCenter);
    gameGridLayout->addWidget(gridImageLabel, 1, 1);

    if (SETTINGS.value("Grid/label","true") == "true") {
        QLabel *gridTextLabel = new QLabel(gameGridItem);

        //Don't allow label to be wider than image
        gridTextLabel->setMaximumWidth(getImageSize("Grid").width());

        QString text = "";
        QString labelText = SETTINGS.value("Grid/labeltext","Filename").toString();

        text = getRomInfo(labelText, currentRom);

        gridTextLabel->setText(text);

        QString textHex = getColor(SETTINGS.value("Grid/labelcolor","White").toString()).name();
        int fontSize = getGridSize("font");

        gridTextLabel->setStyleSheet("QLabel { font-weight: bold; color: " + textHex + "; font-size: "
                                     + QString::number(fontSize) + "px; }");
        gridTextLabel->setWordWrap(true);
        gridTextLabel->setAlignment(Qt::AlignHCenter | Qt::AlignTop);

        gameGridLayout->addWidget(gridTextLabel, 2, 1);
    }

    gameGridItem->setLayout(gameGridLayout);

    gameGridItem->setMinimumHeight(gameGridItem->sizeHint().height());

    int columnCount = SETTINGS.value("Grid/columncount", "4").toInt();
    gridLayout->addWidget(gameGridItem, count / columnCount + 1, count % columnCount + 1);
    gridWidget->adjustSize();

    connect(gameGridItem, SIGNAL(singleClicked(QWidget*)), this, SLOT(highlightGridWidget(QWidget*)));
    connect(gameGridItem, SIGNAL(doubleClicked(QWidget*)), this, SLOT(launchRomFromWidget(QWidget*)));
}