示例#1
0
void cwEdgeTile::generateVertex() {
    Vertices.clear();

    //vertex spacing
    double spacing = 1.0 / (double)tileSize();

    int numVertexes = numVerticesOnADimension();
    int totalSize = numVertexes * numVertexes;
    Vertices.reserve(totalSize);

    //Create the regualar mesh points
    for(int y = 0; y < numVertexes; y++) {
        for(int x = 0; x < numVertexes; x++) {
            float xPos = x * spacing;
            float yPos = y * spacing;

            QVector2D vertex(xPos, yPos);
            Vertices.append(vertex);
        }
    }

    //Add the points for the half spacing
    double halfSpacing = spacing / 2.0;
    for(int row = 0; row < tileSize(); row++) {
        float yPos = row * spacing + halfSpacing;
        Vertices.append(QVector2D(0.0, yPos));
        Vertices.append(QVector2D(halfSpacing, yPos));
    }

}
void BackgroundImageGeometry::setRepeatY(const FillLayer& fillLayer,
                                         LayoutUnit unsnappedTileHeight,
                                         LayoutUnit snappedAvailableHeight,
                                         LayoutUnit unsnappedAvailableHeight,
                                         LayoutUnit extraOffset) {
  // We would like to identify the phase as a fraction of the image size in the
  // absence of snapping, then re-apply it to the snapped values. This is to
  // handle large positions.
  if (unsnappedTileHeight) {
    LayoutUnit computedYPosition = roundedMinimumValueForLength(
        fillLayer.yPosition(), unsnappedAvailableHeight);
    if (fillLayer.backgroundYOrigin() == BottomEdge) {
      float numberOfTilesInPosition =
          (snappedAvailableHeight - computedYPosition + extraOffset).toFloat() /
          unsnappedTileHeight.toFloat();
      float fractionalPositionWithinTile =
          numberOfTilesInPosition - truncf(numberOfTilesInPosition);
      setPhaseY(LayoutUnit(
          roundf(fractionalPositionWithinTile * tileSize().height())));
    } else {
      float numberOfTilesInPosition =
          (computedYPosition + extraOffset).toFloat() /
          unsnappedTileHeight.toFloat();
      float fractionalPositionWithinTile =
          1.0f - (numberOfTilesInPosition - truncf(numberOfTilesInPosition));
      setPhaseY(LayoutUnit(
          roundf(fractionalPositionWithinTile * tileSize().height())));
    }
  } else {
    setPhaseY(LayoutUnit());
  }
  setSpaceSize(LayoutSize(spaceSize().width(), LayoutUnit()));
}
示例#3
0
    void    ViewPort::setTiles()
    {
        // FIXME: this is just duplicate code with draw() - factor it out
        // TODO: move the loop into a separate fn, that can
        // have a function pointer passed in, so that it's
        // easy to iterate over the ViewPort
        
        const vector2& tile_sz = tileSize();

        const unsigned int& tm_h = tm_.height();
        const unsigned int& tm_w = tm_.width();

        vector2 cmt_pos(0.0, 0.0);

        // x, y will be small
        Tile*       cmt = 0;
        for (unsigned int y = 0; y < tm_h ; ++y) {
            for (unsigned int x = 0; x < tm_w ; ++x) {
                cmt = tm_.tile(x, y);
                assert(cmt != 0);
                if (cmt != 0) {
                    cmt_pos[0] = x;
                    cmt_pos[1] = y;
                    cmt->setPosition(cmt_pos);
                    cmt->setDisplayOffset(start_);
                    cmt->setSize(tile_sz);
                }
            }
        }
    }
示例#4
0
void TerrainGrid::Init()
{
	myTiles.Init(ourTileGridSizeX * ourTileGridSizeY, 1000);

	Vector2f pos;
	Vector2f tileSize(ourTileSize, ourTileSize);

	int index = 0;
	for( index; index < ourTileGridSizeX * 10; ++index )
	{
		myTiles.Add( Tile() );
		myTiles[index].mySprite.SetTexture( 0, tileSize );
		pos = Vector2f( ourTileSize * (index % ourTileGridSizeX), ourTileSize * (index / ourTileGridSizeX));
		myTiles[index].mySprite.SetPosition( pos );
		myTiles[index].myIsSolid = false;
	}
	for( index; index < ourTileGridSizeX * ourTileGridSizeY; ++index )
	{
		myTiles.Add( Tile() );
		myTiles[index].mySprite.SetTexture( Renderer::GetInstance()->CreateTexture( "Sprites//Terrain//Grass.bmp" ), tileSize );
		pos = Vector2f( ourTileSize * (index % ourTileGridSizeX), ourTileSize * (index / ourTileGridSizeX));
		myTiles[index].mySprite.SetPosition( pos );
		myTiles[index].myIsSolid = true;
	}
}
IntSize TileController::tileSize() const
{
    if (m_inLiveResize || m_tileSizeLocked)
        return tileGrid().tileSize();

    const int kLowestCommonDenominatorMaxTileSize = 4 * 1024;
    IntSize maxTileSize(kLowestCommonDenominatorMaxTileSize, kLowestCommonDenominatorMaxTileSize);

#if USE(IOSURFACE)
    IntSize surfaceSizeLimit = IOSurface::maximumSize();
    surfaceSizeLimit.scale(1 / m_deviceScaleFactor);
    maxTileSize = maxTileSize.shrunkTo(surfaceSizeLimit);
#endif
    
    if (owningGraphicsLayer()->platformCALayerUseGiantTiles())
        return maxTileSize;

    IntSize tileSize(kDefaultTileSize, kDefaultTileSize);

    if (m_scrollability == NotScrollable) {
        IntSize scaledSize = expandedIntSize(boundsWithoutMargin().size() * tileGrid().scale());
        tileSize = scaledSize.constrainedBetween(IntSize(kDefaultTileSize, kDefaultTileSize), maxTileSize);
    } else if (m_scrollability == VerticallyScrollable)
        tileSize.setWidth(std::min(std::max<int>(ceilf(boundsWithoutMargin().width() * tileGrid().scale()), kDefaultTileSize), maxTileSize.width()));

    LOG_WITH_STREAM(Scrolling, stream << "TileController::tileSize newSize=" << tileSize);

    m_tileSizeLocked = true;
    return tileSize;
}
示例#6
0
SeaView::SeaView(QWidget* parent)
: KGameCanvasWidget(parent)
, m_delegate(0)
, m_last_f(-1)
{/*
    setAttribute(Qt::WA_OpaquePaintEvent);
    setAttribute(Qt::WA_NoSystemBackground);*/

    // create renderer
    m_renderer = new KBSRenderer(":data/default_theme.svgz");
    m_renderer->resize(tileSize());

    // create screen
    m_screen = new WelcomeScreen(this, font());
    m_screen->hide();

    // create labels
    m_labels[0] = new PlayerLabel(
        m_renderer->render("score_mouse", QSize(32, 32)),
        "Player",
        this);
    m_labels[0]->stackUnder(m_screen);
    m_labels[0]->show();
    m_labels[1] = new PlayerLabel(
        m_renderer->render("score_ai", QSize(32, 32)),
        "Computer",
        this);
    m_labels[1]->stackUnder(m_screen);
    m_labels[1]->show();

    // create fields
    m_fields[0] = new BattleFieldView(this, m_renderer, "background", GRID_SIZE);
    m_fields[0]->stackUnder(m_screen);
    m_fields[0]->show();
    connect(m_fields[0]->screen(), SIGNAL(clicked(Button*)), this, SLOT(buttonClicked(Button*)));
    m_fields[1] = new BattleFieldView(this, m_renderer, "background2", GRID_SIZE);
    m_fields[1]->stackUnder(m_screen);
    m_fields[1]->show();
    connect(m_fields[1]->screen(), SIGNAL(clicked(Button*)), this, SLOT(buttonClicked(Button*)));

    // create stats widgets
    m_stats[0] = new StatsWidget(m_fields[0]->size().width(), m_renderer, this);
    m_stats[0]->stackUnder(m_screen);
    m_stats[0]->show();

    m_stats[1] = new StatsWidget(m_fields[1]->size().width(), m_renderer, this);
    m_stats[1]->stackUnder(m_screen);
    m_stats[1]->show();


    Animator::instance()->start();
    update();

    connect(screen(Sea::Player(0)), SIGNAL(hidden()), this, SLOT(update()));
    connect(screen(Sea::Player(0)), SIGNAL(shown()), this, SLOT(update()));

    setMouseTracking(true);
}
示例#7
0
void CCLayerTilingData::setTileSize(const IntSize& size)
{
    if (tileSize() == size)
        return;

    reset();

    m_tilingData.setMaxTextureSize(size);
}
示例#8
0
FakeTiledLayerChromium::FakeTiledLayerChromium(CCPrioritizedTextureManager* textureManager)
    : TiledLayerChromium()
    , m_fakeTextureUpdater(adoptRef(new FakeLayerTextureUpdater))
    , m_textureManager(textureManager)
{
    setTileSize(tileSize());
    setTextureFormat(GraphicsContext3D::RGBA);
    setBorderTexelOption(CCLayerTilingData::NoBorderTexels);
    setIsDrawable(true); // So that we don't get false positives if any of these tests expect to return false from drawsContent() for other reasons.
}
QPointF OSMARenderMapSource::coordinateFromDisplay(const QPoint &point, int zoom)
{
	int tiles_size = (1 << zoom) * tileSize();

	qreal lat = (((tiles_size / 2) - point.y()) * 2 * M_PI ) / tiles_size;
	lat = rad2deg(asin(tanh(lat)));

	qreal lon = ((point.x() - tiles_size / 2) * 2 * M_PI) / tiles_size;
	lon = rad2deg(lon);

	return QPointF(lon, lat);
}
QPoint OSMARenderMapSource::displayFromCooordinate(const QPointF &coordinate, int zoom)
{
	int tiles_size = (1 << zoom) * tileSize();

	qreal lat_r = atanh(sin(deg2rad(coordinate.y())));
	qreal lon_r = deg2rad(coordinate.x());

	int x =  lon_r * tiles_size / (2 * M_PI) + tiles_size / 2;
	int y = -lat_r * tiles_size / (2 * M_PI) + tiles_size  / 2;

	return QPoint(x, y);
}
示例#11
0
void CubeRender::render()
{
	cuber::setBoxFaces();
	cuber::setRenderRect((int *)&rect() );
    cuber::setFrustum((float *)rayFrameVec());
#if 0
	cuber::drawPyramid((uint *) colorBuffer(),
                (float *) nearDepthBuffer(),
				tileSize(),
				tileX(), tileY(),
				m_devicePyramidPlanes->bufferOnDevice(),
				m_devicePyramidBox->bufferOnDevice() );
#else 
	cuber::drawVoxel((uint *) colorBuffer(),
                (float *) nearDepthBuffer(),
				tileSize(),
				tileX(), tileY(),
				m_deviceVoxels->bufferOnDevice() );
#endif
	CudaBase::CheckCudaError(" render image");
}
示例#12
0
int main() {
	sf::Vector2i levelSize(30, 20);
	sf::Vector2i tileSize(32, 32);
	sf::RenderWindow window(sf::VideoMode(levelSize.x * tileSize.x, levelSize.y * tileSize.y), "Cellular Automata Cave Generation");
	window.setVerticalSyncEnabled(true);

	sf::Texture texture;
	if (!texture.loadFromFile("tileset.png")) {
		std::cout << "Unable to load the texture" << std::endl;
		return 0;
	}
	Tile tileset[] = {
		Tile(texture, sf::IntRect(tileSize.x, 0, tileSize.x, tileSize.y)),
		Tile(texture, sf::IntRect(0, 0, tileSize.x, tileSize.y))
	};
	sf::Font font;
	if (!font.loadFromFile("LCD_Solid.TTF")) {
		std::cout << "Unable to load the font" << std::endl;
		return 0;
	}
	sf::String str(" FPS\n\nPRESS 'G' TO GENERATE A NEW CAVE");
	sf::Text text(str, font, 10);
	text.setPosition(10, 10);
	text.setColor(sf::Color::White);

	TileMap tileMap(levelSize, tileSize, tileset);
	MapGenerator generator(levelSize.x, levelSize.y);
	generator.setIterations(4);
	generator.setDeathThreshold(3);
	generator.setBirthThreshold(4);
	generator.setChanceToStartAlive(50);
	
	int frameCount = 0;
	sf::Clock clock;
	while (window.isOpen()) {
		if (clock.getElapsedTime().asMilliseconds() >= 1000) {
			clock.restart();
			text.setString(std::to_string(frameCount) + str);
			frameCount = 0;
		}
		frameCount++;
		if (generateLevel) {
			tileMap.setMap(generator.generate());
			generateLevel = false;
		}
		processInput(window);
		window.draw(tileMap);
		window.draw(text);
		window.display();
	}
	return 0;
}
示例#13
0
void BackgroundImageGeometry::setSpaceY(LayoutUnit space,
                                        LayoutUnit availableHeight,
                                        LayoutUnit extraOffset) {
  LayoutUnit computedYPosition =
      roundedMinimumValueForLength(Length(), availableHeight);
  setSpaceSize(LayoutSize(spaceSize().width().toInt(), space.round()));
  LayoutUnit actualHeight = tileSize().height() + space;
  setPhaseY(actualHeight
                ? LayoutUnit(roundf(
                      actualHeight -
                      fmodf((computedYPosition + extraOffset), actualHeight)))
                : LayoutUnit());
}
示例#14
0
MainMenuState::MainMenuState(GameApp* app) : GameState(app), m_app(app), m_map(0), backgroundLayer(0), objectsLayer(0)
{
	// Tile size
	vec2 tileSize(64.0f, 64.0f);

	// Create new map, with width == tile, heigh == 32pixels/tile
	m_map = new Map(tileSize.x, tileSize.y);

	// Background layer
	backgroundLayer = new Layer(m_map, "Background", 1.0f, true, false);

	m_map->addLayer(Map::BACKGROUND0, backgroundLayer);

	// Create new sprite GameObject from texture (background sprite) size is same than screen size.
	GameObject* backgroundGameObject = createSpriteGameObject("../assets/menuBG.png", 1280.0f, 720.0f, false);

	// Add GameObject to background layer.
	backgroundLayer->addGameObject(backgroundGameObject);

	// Objects layer
	objectsLayer = new Layer(m_map, "Objects", 1.0f, true, false);

	m_map->addLayer(Map::MAPLAYER0, objectsLayer);

	// Create new start button object, and clip it, white color shall be transparent
	GameObject* startButtonObject = createSpriteGameObject("../assets/buttons.png", 242.0f, 96.0f, 0, 0, 242, 96, false);

	// Add start button to level
	objectsLayer->addGameObject(startButtonObject);

	// Set Start button position
	startButtonObject->setPosition(-6.0f, 2.0f);
	
	// Set button name
	startButtonObject->setName("Start");

	// Create new start button object, and clip it, white color shall be transparent
	GameObject* exitButtonObject = createSpriteGameObject("../assets/buttons.png", 242.0f, 96.0f, 242, 0, 242, 96, false);

	// Add exit button to level
	objectsLayer->addGameObject(exitButtonObject);

	// Set button size
	//exitButtonObject->setSize(tileSize.x / 2.0, tileSize.y / 2.0);

	// Set exit button position
	exitButtonObject->setPosition(-6.0f, 4.5f);

	// Setting object names
	exitButtonObject->setName("Exit");
}
示例#15
0
void dng_area_task::Perform (dng_area_task &task,
				  			 const dng_rect &area,
				  			 dng_memory_allocator *allocator,
				  			 dng_abort_sniffer *sniffer)
	{
	
	dng_point tileSize (task.FindTileSize (area));
		
	task.Start (1, tileSize, allocator, sniffer);
	
	task.ProcessOnThread (0, area, tileSize, sniffer);
			
	task.Finish (1);
	
	}
示例#16
0
void SeaView::update()
{
    int ts = tileSize();

    m_renderer->resize(ts);

    m_fields[0]->update();
    m_fields[1]->update();
    int actual_width =
        m_fields[0]->size().width() +
        m_fields[1]->size().width() +
        GAP;

    m_fields[0]->moveTo(
        (width() - actual_width) / 2,
        PlayerLabel::HEIGHT + LABEL_SPACING * 2);
    if (!screen(Sea::Player(0))->active()) {
        m_labels[0]->show();
        m_labels[0]->moveTo(m_fields[0]->pos().x(), LABEL_SPACING);
        m_labels[0]->update();
    } else {
        m_labels[0]->hide();
    }
    m_stats[0]->moveTo(m_fields[0]->pos().x(),
        height() - StatsWidget::HEIGHT - MARGIN);
    m_stats[0]->setWidth(m_fields[0]->size().width());
    m_stats[0]->update();

    m_fields[1]->moveTo(
        m_fields[0]->pos().x() + m_fields[0]->size().width() + GAP,
        m_fields[0]->pos().y());
    if (!screen(Sea::Player(0))->active()) {
        m_labels[1]->show();
        m_labels[1]->moveTo(m_fields[1]->pos().x(), LABEL_SPACING);
        m_labels[1]->update();
    } else {
        m_labels[1]->hide();
    }
    m_stats[1]->moveTo(m_fields[1]->pos().x(),
        height() - StatsWidget::HEIGHT - MARGIN);
    m_stats[1]->setWidth(m_fields[0]->size().width());
    m_stats[1]->update();

    m_screen->moveTo(0, 0);
    m_screen->resize(QSize(m_fields[1]->pos().x() + m_fields[1]->size().width(),
                           m_fields[0]->size().height()));
}
LevelLayerComponent::LevelLayerComponent(int layerIdx, NLTmxMap* pTilemap, std::map<std::string, Texture*>* pTilesetTexture, RenderWindow* pWindow)
{
	m_pWindow = pWindow;
	m_iTileSize = pTilemap->tileWidth;

	NLTmxMapLayer* layer = pTilemap->layers[layerIdx];
	int size = layer->width * layer->height;

	// go over all elements in the layer
	for (int i = 0; i < size; i++)
	{
		int grid = layer->data[i];

		if (grid == 0)	continue;

		// get tileset and tileset texture
		NLTmxMapTileset* tileset = pTilemap->getTilesetForGrid(grid);
		Vector2i tileSize(pTilemap->tileWidth, pTilemap->tileHeight);
		Texture* texture = pTilesetTexture->at(tileset->name);
		assert(texture != nullptr);

		// horizontal tile count in tileset texture
		int tileCountX = texture->getSize().x / tileSize.x;

		// calcualte position of tile
		Vector2f position;
		position.x = (i % layer->width) * (float)tileSize.x;
		position.y = (i / layer->width) * (float)tileSize.y;

		// calculate 2d idx of tile in tileset texture
		int idx = grid - tileset->firstGid;
		int idxX = idx % tileCountX;
		int idxY = idx / tileCountX;

		// calculate source area of tile in tileset texture
		IntRect source(idxX * tileSize.x, idxY * tileSize.y, tileSize.x, tileSize.y);

		//create tile and put it into a layer
		Sprite* sprite = new Sprite();
		sprite->setTexture(*texture);
		sprite->setTextureRect(source);
		sprite->setPosition(position.x, position.y);

		m_pLayerSprites.push_back(sprite);
	}
}
示例#18
0
void Frustum::tile( F32 *left, F32 *right, F32 *top, F32 *bottom, U32 numTiles, const Point2I& curTile, Point2F overlap )
{
   if (numTiles == 1)
      return;

   Point2F tileSize( ( *right - *left ) / (F32)numTiles, 
                     ( *top - *bottom ) / (F32)numTiles );
   
   F32 leftOffset   = tileSize.x*overlap.x;
   F32 rightOffset  = tileSize.x*overlap.x*2;
   F32 bottomOffset = tileSize.y*overlap.y;
   F32 topOffset    = tileSize.y*overlap.y*2;

   *left += tileSize.x * curTile.x - leftOffset;
   *right = *left + tileSize.x + rightOffset;
   *bottom += tileSize.y * curTile.y - bottomOffset;
   *top = *bottom + tileSize.y + topOffset;
}
示例#19
0
/**
   Sets the tile size.  If the tile size is the same, this function does nothing.

   This will also generate the geometry for the tile.

   The tile size must be divisible by two.  The number of vertics is size + 1 per
   dimension

  */
void cwTile::setTileSize(int size) {
    size = size - size % 2; //Make it even
    if(tileSize() == size) { return; }
    TileSize = size;

    //Generate in the subclasses
    generate();

    TriangleIndexBuffer.bind();
    TriangleIndexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw);
    TriangleIndexBuffer.allocate(Indexes.data(), Indexes.size() * sizeof(GLuint));
    TriangleIndexBuffer.release();

    TriangleVertexBuffer.bind();
    TriangleVertexBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw);
    TriangleVertexBuffer.allocate(Vertices.data(), Vertices.size() * sizeof(QVector2D));
    TriangleVertexBuffer.release();
}
示例#20
0
// Private Method(s)
	// Setup Tile Positions
void Grid::setupTilePositions()
{
	int tilesSquared = static_cast<int>(sqrt(mTilePositions.size()));
	int curCol = 0, curRow = 0;

	sf::FloatRect outlineRect = mOutline.getGlobalBounds();
	sf::Vector2f tileSize(mOutline.getSize().x / tilesSquared, mOutline.getSize().y / tilesSquared);
	for (auto& tilePos : mTilePositions) {
		tilePos = sf::Vector2f(outlineRect.left + curCol * tileSize.x,
							   outlineRect.top + curRow * tileSize.y);
		curCol++;

		if (curCol % tilesSquared == 0) {
			curRow++;
			curCol = 0;
		}
	}
}
示例#21
0
void Frustum::offsetFrustum(Point4F offset)
{
   Point2F tileSize( ( mNearRight - mNearLeft ), 
                     ( mNearTop - mNearBottom ));
   
   F32 leftOffset   = tileSize.x*offset.x;
   F32 bottomOffset = tileSize.y*(1.0f-offset.w);
   F32 rightOffset  = tileSize.x*offset.z;
   F32 topOffset    = tileSize.y*(1.0f-offset.y);

   mNearLeft += leftOffset;
   mNearRight = mNearLeft + rightOffset;
   mNearBottom += bottomOffset;
   mNearTop = mNearBottom + topOffset;

   // todo: update planes also
//   mDirty = true;
//   _update(); // maybe
}
示例#22
0
void DisplayGrid::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
	int amtX = obsMap->getWidth();
	int amtY = obsMap->getHeight();
	int sizeX = getSize().x;
	int sizeY = getSize().y;
	int tileX, tileY;
	sf::Vector2f tileSize(sizeX / amtX, sizeY / amtY);
	sf::RectangleShape tile(tileSize);
	sf::Vector2f pos = getPosition();
	for (int x = 0; x < amtX; x++)
	{
		for (int y = 0; y < amtY; y++)
		{
			tileX = pos.x + tileSize.x * x;
			tileY = pos.y + tileSize.y * y;
			tile.setPosition(tileX, tileY);
			tile.setFillColor(getTileColor(obsMap->at(x, y)));
			tile.setOutlineColor(getOutlineColor());
			tile.setOutlineThickness(getOutlineThickness());
			target.draw(tile);
		}
	}
}
示例#23
0
void TileController::adjustTileCoverageRect(FloatRect& coverageRect, const FloatSize& newSize, const FloatRect& previousVisibleRect, const FloatRect& visibleRect, float contentsScale) const
{
    // If the page is not in a window (for example if it's in a background tab), we limit the tile coverage rect to the visible rect.
    if (!m_isInWindow) {
        coverageRect = visibleRect;
        return;
    }

#if PLATFORM(IOS)
    // FIXME: unify the iOS and Mac code.
    UNUSED_PARAM(previousVisibleRect);
    
    if (m_tileCoverage == CoverageForVisibleArea || MemoryPressureHandler::singleton().isUnderMemoryPressure()) {
        coverageRect = visibleRect;
        return;
    }

    double horizontalMargin = tileSize().width() / contentsScale;
    double verticalMargin = tileSize().height() / contentsScale;

    double currentTime = monotonicallyIncreasingTime();
    double timeDelta = currentTime - m_velocity.lastUpdateTime;

    FloatRect futureRect = visibleRect;
    futureRect.setLocation(FloatPoint(
        futureRect.location().x() + timeDelta * m_velocity.horizontalVelocity,
        futureRect.location().y() + timeDelta * m_velocity.verticalVelocity));

    if (m_velocity.horizontalVelocity) {
        futureRect.setWidth(futureRect.width() + horizontalMargin);
        if (m_velocity.horizontalVelocity < 0)
            futureRect.setX(futureRect.x() - horizontalMargin);
    }

    if (m_velocity.verticalVelocity) {
        futureRect.setHeight(futureRect.height() + verticalMargin);
        if (m_velocity.verticalVelocity < 0)
            futureRect.setY(futureRect.y() - verticalMargin);
    }

    if (!m_velocity.horizontalVelocity && !m_velocity.verticalVelocity) {
        if (m_velocity.scaleChangeRate > 0) {
            coverageRect = visibleRect;
            return;
        }
        futureRect.setWidth(futureRect.width() + horizontalMargin);
        futureRect.setHeight(futureRect.height() + verticalMargin);
        futureRect.setX(futureRect.x() - horizontalMargin / 2);
        futureRect.setY(futureRect.y() - verticalMargin / 2);
    }

    // Can't use m_tileCacheLayer->bounds() here, because the size of the underlying platform layer
    // hasn't been updated for the current commit.
    IntSize contentSize = expandedIntSize(newSize);
    if (futureRect.maxX() > contentSize.width())
        futureRect.setX(contentSize.width() - futureRect.width());
    if (futureRect.maxY() > contentSize.height())
        futureRect.setY(contentSize.height() - futureRect.height());
    if (futureRect.x() < 0)
        futureRect.setX(0);
    if (futureRect.y() < 0)
        futureRect.setY(0);

    coverageRect.unite(futureRect);
    return;
#else
    UNUSED_PARAM(contentsScale);

    // FIXME: look at how far the document can scroll in each dimension.
    FloatSize coverageSize = visibleRect.size();

    bool largeVisibleRectChange = !previousVisibleRect.isEmpty() && !visibleRect.intersects(previousVisibleRect);

    // Inflate the coverage rect so that it covers 2x of the visible width and 3x of the visible height.
    // These values were chosen because it's more common to have tall pages and to scroll vertically,
    // so we keep more tiles above and below the current area.
    float widthScale = 1;
    float heightScale = 1;

    if (m_tileCoverage & CoverageForHorizontalScrolling && !largeVisibleRectChange)
        widthScale = 2;

    if (m_tileCoverage & CoverageForVerticalScrolling && !largeVisibleRectChange)
        heightScale = 3;
    
    coverageSize.scale(widthScale, heightScale);

    FloatRect coverageBounds = boundsForSize(newSize);
    
    FloatRect coverage = expandRectWithinRect(visibleRect, coverageSize, coverageBounds);
    LOG_WITH_STREAM(Scrolling, stream << "TileController::computeTileCoverageRect newSize=" << newSize << " mode " << m_tileCoverage << " expanded to " << coverageSize << " bounds with margin " << coverageBounds << " coverage " << coverage);
    coverageRect.unite(coverage);
#endif
}
示例#24
0
IntRect CCLayerTilingData::tileRect(const Tile* tile) const
{
    IntRect tileRect = m_tilingData.tileBoundsWithBorder(tile->i(), tile->j());
    tileRect.setSize(tileSize());
    return tileRect;
}
示例#25
0
bool ossimKakaduJ2kReader::open()
{
   static const char MODULE[] = "ossimKakaduJ2kReader::open";

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " entered...\n";
   }
   
   bool result = false;
   
   if(isOpen())
   {
      closeEntry();
   }

   // Open up a stream to the file.
   theFileStr.open(theImageFile.c_str(), ios::in | ios::binary);
   if ( theFileStr.good() )
   {
      //---
      // Check for the Start Of Codestream (SOC) and Size (SIZ) markers which
      // are required as first and second fields in the main header.
      //---
      ossim_uint16 soc;
      ossim_uint16 siz;
      theFileStr.read((char*)&soc,  2);
      theFileStr.read((char*)&siz,  2);
      
      if (ossim::byteOrder() == OSSIM_LITTLE_ENDIAN) // Alway big endian.
      {
         ossimEndian().swap(soc);
         ossimEndian().swap(siz);
      }

      if ( (soc == SOC_MARKER) && (siz == SIZ_MARKER) )
      {
         // Read in and store the size record.
         theSizRecord.parseStream(theFileStr);

         // Position to start of code stream prior to create call.
         theFileStr.seekg(0);
 
         //---
         // Initialize the codestream.  The class ossimKakaduNitfReader is a
         // kdu_compressed source so we feed ourself to the codestream.
         //
         // TODO:  Currently no kdu_thread_env.  This should be implemented for
         // speed...
         //---
         
         //---
         // Construct multi-threaded processing environment if required.
         // Temp hard coded to a single thread.
         //---
         
         if (theThreadEnv)
         {
            theThreadEnv->terminate(NULL, true);
            theThreadEnv->destroy();
         }
         else
         {
            theThreadEnv = new kdu_thread_env();
         }
         
         theThreadEnv->create(); // Creates the single "owner" thread

         // Check for threads in prefs file.
         ossim_uint32 threads = 1;
         const char* lookup = ossimPreferences::instance()->findPreference("kakadu_threads");
         if ( lookup )
         {
            threads = ossimString::toUInt32(lookup);
            if ( threads > 1 )
            {
               for (ossim_uint32 nt=1; nt < threads; ++nt)
               {
                  if ( !theThreadEnv->add_thread() )
                  {
                     if (traceDebug())
                     {
                        ossimNotify(ossimNotifyLevel_WARN)
                           << "Unable to create thread!\n";
                     }
                  }
               }
            }
         }
         
         theOpenTileThreadQueue = theThreadEnv->add_queue(NULL,NULL,"open_tile_q");
         
         theCodestream.create(this, theThreadEnv);
         
         if ( theCodestream.exists() )
         {
            //---
            // We have to store things here in this non-const method because
            // NONE of the kakadu methods are const.
            //---
            theMinDwtLevels = theCodestream.get_min_dwt_levels();
            
            theCodestream.set_persistent(); // ????
            theCodestream.enable_restart(); // ????
            
            kdu_dims region_of_interest;
            region_of_interest.pos.x = 0;
            region_of_interest.pos.y = 0;
            region_of_interest.size.x = getNumberOfSamples(0);
            region_of_interest.size.y = getNumberOfLines(0);

            theCodestream.apply_input_restrictions(
               0, // first_component
               0, // max_components (0 = all remaining will appear)
               0, // highest resolution level
               0, // max_layers (0 = all layers retained)
               &region_of_interest, // expanded out to block boundary.
               //KDU_WANT_CODESTREAM_COMPONENTS);
               KDU_WANT_OUTPUT_COMPONENTS);
            
            // Set the scalar:
            theScalarType = theSizRecord.getScalarType();
            if (theScalarType != OSSIM_SCALAR_UNKNOWN)
            {
               //---
               // NOTE: Please leave commented out code for now.
               //---
               // Capture the sub image offset.
               // theSubImageOffset.x = theSizRecord.theXOsiz;
               // theSubImageOffset.y = theSizRecord.theYOsiz;
               
               // Initialize the image rect.
               theImageRect = ossimIrect(0,
                                         0,
                                         theSizRecord.theXsiz-1,
                                         theSizRecord.theYsiz-1);

               // Initialize the cache.
               if (theCacheId != -1)
               {
                  ossimAppFixedTileCache::instance()->deleteCache(theCacheId);
                  theCacheId = -1;
               }
               ossimIpt tileSize(theSizRecord.theXTsiz, theSizRecord.theYTsiz);

               // Stretch to tile boundary for the cache.
               ossimIrect fullImgRect = theImageRect;
               fullImgRect.stretchToTileBoundary(tileSize);
               
               // Set up the tile cache.
               theCacheId = ossimAppFixedTileCache::instance()->
                  newTileCache(fullImgRect, tileSize);

               // Add the sub image rect after the 
               
               // Initialize the tile we will return.
               initializeTile();

               // Call the base complete open to pick up overviews.
               completeOpen();
               
               // We should be good now so set the return result to true.
               result = true;

               if (traceDebug())
               {
                  ossimNotify(ossimNotifyLevel_DEBUG)
                     << "\nSIZ marker segment"
                     << theSizRecord
                     << "theCodestream.get_num_components(false): "
                     << theCodestream.get_num_components(false)
                     << "\ntheCodestream.get_num_components(true): "
                     << theCodestream.get_num_components(true)
                     << "\ntheCodestream.get_bit_depth(0, true): "
                     << theCodestream.get_bit_depth(0, true)
                     << "\ntheCodestream.get_signed(0, true): "
                     << theCodestream.get_signed(0, true)
                     << "\ntheCodestream.get_min_dwt_levels(): "
                     << theCodestream.get_min_dwt_levels()
                     << "\ntheImageRect: " << theImageRect
                     << "\nFull image rect: " << fullImgRect
                     << "\nthreads: " << threads
                     << "\n";
                  
                  vector<ossimDpt> decimations;
                  getDecimationFactors(decimations);
                  for (ossim_uint32 i = 0; i < decimations.size(); ++i)
                  {
                     ossimNotify(ossimNotifyLevel_DEBUG)
                        << theCodestream.get_min_dwt_levels()
                        << "Decimation factor[" << i << "]: "
                        << decimations[i]
                        << "\nsamples[" << i << "]: "
                        << getNumberOfSamples(i)
                        << "\nlines[" << i << "]: "
                        << getNumberOfLines(i)
                        << std::endl;
                     
                  }
               }
            }
               
         } // matches: if ( theCodestream.exists() )
         
      } //  matches: if ( (soc == SOC_MARKER) && (siz == SIZ_MARKER) )
      
   } // matches: if ( theFileStr.good() )
   else
   {
      if(traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << MODULE << " ERROR:"
            << "\nCannot open:  " << theImageFile.c_str() << endl;
      }
   }

   if (traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " exit status = " << (result?"true":"false\n")
         << std::endl;
   }

   return result;
}
void AbstractDngDecompressor::decompressThreaded(
    const RawDecompressorThread* t) const {
  assert(t);
  assert(mRaw->dim.x > 0);
  assert(mRaw->dim.y > 0);
  assert(mRaw->getCpp() > 0);
  assert(mBps > 0 && mBps <= 32);

  if (compression == 1) {
    for (size_t i = t->start; i < t->end && i < slices.size(); i++) {
      auto e = &slices[i];

      UncompressedDecompressor decompressor(e->bs, mRaw);

      size_t thisTileLength =
          e->offY + e->height > static_cast<uint32>(mRaw->dim.y)
              ? mRaw->dim.y - e->offY
              : e->height;

      if (thisTileLength == 0)
        ThrowRDE("Tile is empty. Can not decode!");

      iPoint2D tileSize(mRaw->dim.x, thisTileLength);
      iPoint2D pos(0, e->offY);

      // FIXME: does bytestream have correct byteorder from the src file?
      bool big_endian = e->bs.getByteOrder() == Endianness::big;

      // DNG spec says that if not 8 or 16 bit/sample, always use big endian
      if (mBps != 8 && mBps != 16)
        big_endian = true;

      try {
        const int inputPitchBits = mRaw->getCpp() * mRaw->dim.x * mBps;
        assert(inputPitchBits > 0);

        const int inputPitch = inputPitchBits / 8;
        if (inputPitch == 0)
          ThrowRDE("Data input pitch is too short. Can not decode!");

        decompressor.readUncompressedRaw(tileSize, pos, inputPitch, mBps,
                                         big_endian ? BitOrder_MSB
                                                    : BitOrder_LSB);
      } catch (RawDecoderException& err) {
        mRaw->setError(err.what());
      } catch (IOException& err) {
        mRaw->setError(err.what());
      }
    }
  } else if (compression == 7) {
    for (size_t i = t->start; i < t->end && i < slices.size(); i++) {
      auto e = &slices[i];
      LJpegDecompressor d(e->bs, mRaw);
      try {
        d.decode(e->offX, e->offY, mFixLjpeg);
      } catch (RawDecoderException& err) {
        mRaw->setError(err.what());
      } catch (IOException& err) {
        mRaw->setError(err.what());
      }
    }
    /* Deflate compression */
  } else if (compression == 8) {
#ifdef HAVE_ZLIB
    std::unique_ptr<unsigned char[]> uBuffer;
    for (size_t i = t->start; i < t->end && i < slices.size(); i++) {
      auto e = &slices[i];

      DeflateDecompressor z(e->bs, mRaw, mPredictor, mBps);
      try {
        z.decode(&uBuffer, e->width, e->height, e->offX, e->offY);
      } catch (RawDecoderException& err) {
        mRaw->setError(err.what());
      } catch (IOException& err) {
        mRaw->setError(err.what());
      }
    }
#else
#pragma message                                                                \
    "ZLIB is not present! Deflate compression will not be supported!"
    ThrowRDE("deflate support is disabled.");
#endif
    /* Lossy DNG */
  } else if (compression == 0x884c) {
#ifdef HAVE_JPEG
    /* Each slice is a JPEG image */
    for (size_t i = t->start; i < t->end && i < slices.size(); i++) {
      auto e = &slices[i];
      JpegDecompressor j(e->bs, mRaw);
      try {
        j.decode(e->offX, e->offY);
      } catch (RawDecoderException& err) {
        mRaw->setError(err.what());
      } catch (IOException& err) {
        mRaw->setError(err.what());
      }
    }
#else
#pragma message "JPEG is not present! Lossy JPEG DNG will not be supported!"
    ThrowRDE("jpeg support is disabled.");
#endif
  } else
    mRaw->setError("AbstractDngDecompressor: Unknown compression");
}
示例#27
0
int main(int iArgC, char *cArgV[])
{
#ifdef __GLIBCXX__
	// Set a better exception handler
	std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
#endif

	// Disable stdin/printf/etc. sync for a speed boost
	std::ios_base::sync_with_stdio(false);

	// Declare the supported options.
	po::options_description poActions("Actions");
	poActions.add_options()
		("info,i",
			"display information about the map, including attributes/metadata")

		("print,p", po::value<int>(),
			"print the given layer in ASCII")

		("render,r", po::value<std::string>(),
			"render the map to the given .png file")
	;

	po::options_description poOptions("Options");
	poOptions.add_options()
		("type,t", po::value<std::string>(),
			"specify the map type (default is autodetect)")
		("graphics,g", po::value<std::string>(),
			"filename storing game graphics (required with --render)")
		("script,s",
			"format output suitable for script parsing")
		("force,f",
			"force open even if the map is not in the given format")
		("list-types",
			"list supported file types")
	;

	po::options_description poHidden("Hidden parameters");
	poHidden.add_options()
		("map", "map file to manipulate")
		("help", "produce help message")
	;

	po::options_description poVisible("");
	poVisible.add(poActions).add(poOptions);

	po::options_description poComplete("Parameters");
	poComplete.add(poActions).add(poOptions).add(poHidden);
	po::variables_map mpArgs;

	std::string strFilename, strType;
	std::map<gm::ImagePurpose, gm::Map::GraphicsFilename> manualGfx;

	bool bScript = false; // show output suitable for script parsing?
	bool bForceOpen = false; // open anyway even if map not in given format?
	int iRet = RET_OK;
	try {
		po::parsed_options pa = po::parse_command_line(iArgC, cArgV, poComplete);

		// Parse the global command line options
		for (auto& i : pa.options) {
			if (i.string_key.empty()) {
				// If we've already got an map filename, complain that a second one
				// was given (probably a typo.)
				if (!strFilename.empty()) {
					std::cerr << "Error: unexpected extra parameter (multiple map "
						"filenames given?!)" << std::endl;
					return 1;
				}
				assert(i.value.size() > 0);  // can't have no values with no name!
				strFilename = i.value[0];
			} else if (i.string_key.compare("help") == 0) {
				std::cout <<
					"Copyright (C) 2010-2015 Adam Nielsen <*****@*****.**>\n"
					"This program comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
					"and you are welcome to change and redistribute it under certain conditions;\n"
					"see <http://www.gnu.org/licenses/> for details.\n"
					"\n"
					"Utility to manipulate map files used by games to store data files.\n"
					"Build date " __DATE__ " " __TIME__ << "\n"
					"\n"
					"Usage: gamemap <map> <action> [action...]\n" << poVisible << "\n"
					<< std::endl;
				return RET_OK;
			} else if (
				(i.string_key.compare("t") == 0) ||
				(i.string_key.compare("type") == 0)
			) {
				strType = i.value[0];
			} else if (
				(i.string_key.compare("g") == 0) ||
				(i.string_key.compare("graphics") == 0)
			) {
				std::string purpose, temp;
				gm::Map::GraphicsFilename gf;
				bool a = split(i.value[0], '=', &purpose, &temp);
				bool b = split(temp, ':', &gf.type, &gf.filename);
				if (!a || !b) {
					std::cerr << "Malformed -g/--graphics parameter.  Must be of the "
						"form purpose=type:filename.\n"
						"Use --help or --list-types for details." << std::endl;
					return RET_BADARGS;
				}
				bool found = false;
				for (unsigned int i = 0; i < (unsigned int)gm::ImagePurpose::ImagePurposeCount; i++) {
					gm::ImagePurpose p = (gm::ImagePurpose)i;
					if (purpose.compare(toString(p)) == 0) {
						manualGfx[p] = gf;
						found = true;
					}
				}
				if (!found) {
					std::cerr << "No match for tileset purpose: " << purpose << "\n"
						<< "Use --list-types for details." << std::endl;
					return RET_BADARGS;
				}
			} else if (
				(i.string_key.compare("s") == 0) ||
				(i.string_key.compare("script") == 0)
			) {
				bScript = true;
			} else if (
				(i.string_key.compare("f") == 0) ||
				(i.string_key.compare("force") == 0)
			) {
				bForceOpen = true;
			} else if (
				(i.string_key.compare("list-types") == 0)
			) {
				std::cout << "Tileset purposes: (--graphics purpose=type:file)\n";
				for (unsigned int i = 0; i < (unsigned int)gm::ImagePurpose::ImagePurposeCount; i++) {
					gm::ImagePurpose p = (gm::ImagePurpose)i;
					std::cout << "  " << toString(p) << "\n";
				}

				std::cout << "\nTileset types: (--graphics purpose=type:file)\n";
				for (auto& tilesetType : gg::TilesetManager::formats()) {
					std::string code = tilesetType->code();
					std::cout << "  " << code;
					int len = code.length();
					if (len < 20) std::cout << std::string(20-code.length(), ' ');
					std::cout << ' ' << tilesetType->friendlyName();
					auto ext = tilesetType->fileExtensions();
					if (ext.size()) {
						auto i = ext.begin();
						std::cout << " (*." << *i;
						for (i++; i != ext.end(); i++) {
							std::cout << "; *." << *i;
						}
						std::cout << ")";
					}
					std::cout << '\n';
				}

				std::cout << "\nMap types: (--type)\n";
				for (auto& mapType : gm::MapManager::formats()) {
					std::string code = mapType->code();
					std::cout << "  " << code;
					int len = code.length();
					if (len < 20) std::cout << std::string(20 - code.length(), ' ');
					std::cout << ' ' << mapType->friendlyName();
					auto ext = mapType->fileExtensions();
					if (ext.size()) {
						auto i = ext.begin();
						std::cout << " (*." << *i;
						for (i++; i != ext.end(); i++) {
							std::cout << "; *." << *i;
						}
						std::cout << ")";
					}
					std::cout << '\n';
				}

				return RET_OK;
			}
		}

		if (strFilename.empty()) {
			std::cerr << "Error: no game map filename given" << std::endl;
			return RET_BADARGS;
		}
		std::cout << "Opening " << strFilename << " as type "
			<< (strType.empty() ? "<autodetect>" : strType) << std::endl;

		std::unique_ptr<stream::inout> content;
		try {
			content = std::make_unique<stream::file>(strFilename, false);
		} catch (const stream::open_error& e) {
			std::cerr << "Error opening " << strFilename << ": " << e.what()
				<< std::endl;
			return RET_SHOWSTOPPER;
		}

		gm::MapManager::handler_t mapType;
		if (strType.empty()) {
			// Need to autodetect the file format.
			for (auto& mapTestType : gm::MapManager::formats()) {
				gm::MapType::Certainty cert = mapTestType->isInstance(*content);
				switch (cert) {
					case gm::MapType::Certainty::DefinitelyNo:
						// Don't print anything (TODO: Maybe unless verbose?)
						break;
					case gm::MapType::Certainty::Unsure:
						std::cout << "File could be a " << mapTestType->friendlyName()
							<< " [" << mapTestType->code() << "]" << std::endl;
						// If we haven't found a match already, use this one
						if (!mapType) mapType = mapTestType;
						break;
					case gm::MapType::Certainty::PossiblyYes:
						std::cout << "File is likely to be a " << mapTestType->friendlyName()
							<< " [" << mapTestType->code() << "]" << std::endl;
						// Take this one as it's better than an uncertain match
						mapType = mapTestType;
						break;
					case gm::MapType::Certainty::DefinitelyYes:
						std::cout << "File is definitely a " << mapTestType->friendlyName()
							<< " [" << mapTestType->code() << "]" << std::endl;
						mapType = mapTestType;
						// Don't bother checking any other formats if we got a 100% match
						goto finishTesting;
				}
				if (cert != gm::MapType::Certainty::DefinitelyNo) {
					// We got a possible match, see if it requires any suppdata
					auto suppList = mapTestType->getRequiredSupps(*content, strFilename);
					if (suppList.size() > 0) {
						// It has suppdata, see if it's present
						std::cout << "  * This format requires supplemental files..." << std::endl;
						bool bSuppOK = true;
						for (auto& i : suppList) {
							try {
								auto suppStream = std::make_unique<stream::file>(i.second, false);
							} catch (const stream::open_error&) {
								bSuppOK = false;
								std::cout << "  * Could not find/open " << i.second
									<< ", map is probably not "
									<< mapTestType->code() << std::endl;
								break;
							}
						}
						if (bSuppOK) {
							// All supp files opened ok
							std::cout << "  * All supp files present, map is likely "
								<< mapTestType->code() << std::endl;
							// Set this as the most likely format
							mapType = mapTestType;
						}
					}
				}
			}
finishTesting:
			if (!mapType) {
				std::cerr << "Unable to automatically determine the file type.  Use "
					"the --type option to manually specify the file format." << std::endl;
				return RET_BE_MORE_SPECIFIC;
			}
		} else {
			mapType = gm::MapManager::byCode(strType);
			if (!mapType) {
				std::cerr << "Unknown file type given to -t/--type: " << strType
					<< std::endl;
				return RET_BADARGS;
			}
		}

		assert(mapType != NULL);

		// Check to see if the file is actually in this format
		if (!mapType->isInstance(*content)) {
			if (bForceOpen) {
				std::cerr << "Warning: " << strFilename << " is not a "
					<< mapType->friendlyName() << ", open forced." << std::endl;
			} else {
				std::cerr << "Invalid format: " << strFilename << " is not a "
					<< mapType->friendlyName() << "\n"
					<< "Use the -f option to try anyway." << std::endl;
				return RET_BE_MORE_SPECIFIC;
			}
		}

		// See if the format requires any supplemental files
		camoto::SuppData suppData;
		for (auto& i : mapType->getRequiredSupps(*content, strFilename)) {
			try {
				std::cerr << "Opening supplemental file " << i.second << std::endl;
				suppData[i.first] = std::make_unique<stream::file>(i.second, false);
			} catch (const stream::open_error& e) {
				std::cerr << "Error opening supplemental file " << i.second << ": "
					<< e.what() << std::endl;
				// Continue anyway in case the file is optional
			}
		}

		// Open the map file
		std::shared_ptr<gm::Map> pMap = mapType->open(std::move(content), suppData);
		assert(pMap);

		// File type of inserted files defaults to empty, which means 'generic file'
		std::string strLastFiletype;

		// Run through the actions on the command line
		for (auto& i : pa.options) {
			if (i.string_key.compare("info") == 0) {
				listAttributes(pMap.get(), bScript);

				std::cout << (bScript ? "gfx_filename_count=" : "Number of graphics filenames: ")
					<< pMap->graphicsFilenames().size() << "\n";
				int fileNum = 0;
				for (auto& a : pMap->graphicsFilenames()) {
					if (bScript) {
						std::cout << "gfx_file" << fileNum << "_name=" << a.second.filename << "\n";
						std::cout << "gfx_file" << fileNum << "_type=" << a.second.type << "\n";
						std::cout << "gfx_file" << fileNum << "_purpose=" << (unsigned int)a.first << "\n";
					} else {
						std::cout << "Graphics file " << fileNum+1 << ": " << a.second.filename
							<< " [";
						switch (a.first) {
							case gm::ImagePurpose::GenericTileset1:    std::cout << "Generic tileset 1"; break;
							case gm::ImagePurpose::BackgroundImage:    std::cout << "Background image"; break;
							case gm::ImagePurpose::BackgroundTileset1: std::cout << "Background tileset 1"; break;
							case gm::ImagePurpose::BackgroundTileset2: std::cout << "Background tileset 2"; break;
							case gm::ImagePurpose::ForegroundTileset1: std::cout << "Foreground tileset 1"; break;
							case gm::ImagePurpose::ForegroundTileset2: std::cout << "Foreground tileset 2"; break;
							case gm::ImagePurpose::SpriteTileset1:     std::cout << "Sprite tileset 1"; break;
							case gm::ImagePurpose::FontTileset1:       std::cout << "Font tileset 1"; break;
							case gm::ImagePurpose::FontTileset2:       std::cout << "Font tileset 2"; break;
							default:
								std::cout << "Unknown purpose <fix this>";
								break;
						}
						std::cout << " of type " << a.second.type << "]\n";
					}
					fileNum++;
				}

				std::cout << (bScript ? "map_type=" : "Map type: ");
				auto map2d = std::dynamic_pointer_cast<gm::Map2D>(pMap);
				if (map2d) {
					std::cout << (bScript ? "2d" : "2D grid-based") << "\n";
#define CAP(o, c, v)        " " __STRING(c) << ((v & o::Caps::c) ? '+' : '-')
#define MAP2D_CAP(c)        CAP(gm::Map2D,        c, mapCaps)
#define MAP2D_LAYER_CAP(c)  CAP(gm::Map2D::Layer, c, layerCaps)

					auto mapCaps = map2d->caps();
					if (bScript) {
						std::cout << "map_caps=" << (unsigned int)mapCaps << "\n";
					} else {
						std::cout << "Map capabilities:"
							<< MAP2D_CAP(HasViewport)
							<< MAP2D_CAP(HasMapSize)
							<< MAP2D_CAP(SetMapSize)
							<< MAP2D_CAP(HasTileSize)
							<< MAP2D_CAP(SetTileSize)
							<< MAP2D_CAP(AddPaths)
							<< "\n"
						;
					}
					auto mapTileSize = map2d->tileSize();
					std::cout << (bScript ? "tile_width=" : "Tile size: ") << mapTileSize.x
						<< (bScript ? "\ntile_height=" : "x") << mapTileSize.y << "\n";

					auto mapSize = map2d->mapSize();
					std::cout
						<< (bScript ? "map_width=" : "Map size: ") << mapSize.x
						<< (bScript ? "\nmap_height=" : "x") << mapSize.y
						<< (bScript ? "" : " tiles")
						<< "\n";

					if (mapCaps & gm::Map2D::Caps::HasViewport) {
						auto vp = map2d->viewport();
						std::cout << (bScript ? "viewport_width=" : "Viewport size: ")
							<< vp.x
							<< (bScript ? "\nviewport_height=" : "x") << vp.y
							<< (bScript ? "" : " pixels") << "\n";
					}

					unsigned int layerCount = map2d->layers().size();
					std::cout << (bScript ? "layercount=" : "Layer count: ")
						<< layerCount << "\n";
					unsigned int layerIndex = 0;
					for (auto& layer : map2d->layers()) {
						std::string prefix;
						if (bScript) {
							std::stringstream ss;
							ss << "layer" << layerIndex << '_';
							prefix = ss.str();
							std::cout << prefix << "name=" << layer->title() << "\n";
						} else {
							prefix = "  ";
							std::cout << "Layer " << layerIndex + 1 << ": \"" << layer->title()
								<< "\"\n";
						}
						auto layerCaps = layer->caps();
						if (bScript) std::cout << prefix << "caps="
							<< (unsigned int)layerCaps << "\n";
						else std::cout << prefix << "Capabilities:"
							<< MAP2D_LAYER_CAP(HasOwnSize)
							<< MAP2D_LAYER_CAP(SetOwnSize)
							<< MAP2D_LAYER_CAP(HasOwnTileSize)
							<< MAP2D_LAYER_CAP(SetOwnTileSize)
							<< MAP2D_LAYER_CAP(HasPalette)
							<< MAP2D_LAYER_CAP(UseImageDims)
							<< "\n"
						;

						gg::Point layerTileSize;
						bool layerTileSame;
						if (layerCaps & gm::Map2D::Layer::Caps::HasOwnTileSize) {
							layerTileSize = layer->tileSize();
							layerTileSame = false;
						} else {
							layerTileSize = mapTileSize;
							layerTileSame = true;
						}
						std::cout << prefix << (bScript ? "tile_width=" : "Tile size: ")
							<< layerTileSize.x;
						if (bScript) std::cout << "\n" << prefix << "tile_height=";
						else std::cout << "x";
						std::cout << layerTileSize.y;
						if (layerTileSame && (!bScript)) {
							std::cout << " (same as map)";
						}
						std::cout << "\n";

						gg::Point layerSize;
						bool layerSame;
						if (layerCaps & gm::Map2D::Layer::Caps::HasOwnSize) {
							layerSize = layer->layerSize();
							layerSame = false;
						} else {
							// Convert from map tilesize to layer tilesize, leaving final
							// pixel dimensions unchanged
							layerSize.x = mapSize.x * mapTileSize.x / layerTileSize.x;
							layerSize.y = mapSize.y * mapTileSize.y / layerTileSize.y;
							layerSame = true;
						}
						std::cout << prefix << (bScript ? "width=" : "Layer size: ")
							<< layerSize.x;
						if (bScript) std::cout << "\n" << prefix << "height=";
						else std::cout << "x";
						std::cout << layerSize.y;
						if (layerSame && (!bScript)) {
							std::cout << " (same as map)";
						}
						std::cout << "\n";

						layerIndex++;
					}

				} else {
					std::cout << (bScript ? "unknown" : "Unknown!  Fix this!") << "\n";
				}

			} else if (i.string_key.compare("print") == 0) {
				auto map2d = std::dynamic_pointer_cast<gm::Map2D>(pMap);
				if (map2d) {
					unsigned int targetLayer = strtoul(i.value[0].c_str(), NULL, 10);
					if (targetLayer == 0) {
						std::cerr << "Invalid layer index passed to --print.  Use --info "
							"to list layers in this map." << std::endl;
						iRet = RET_BADARGS;
						continue;
					}
					if (targetLayer > map2d->layers().size()) {
						std::cerr << "Invalid layer index passed to --print.  Use --info "
							"to list layers in this map." << std::endl;
						iRet = RET_BADARGS;
						continue;
					}

					auto layer = map2d->layers().at(targetLayer - 1);
					// If this fails, the map format returned a null pointer for the layer
					assert(layer);

					// Figure out the layer size
					gg::Point layerSize, tileSize;
					getLayerDims(*map2d, *layer, &layerSize, &tileSize);

					auto items = layer->items();
					auto t = items.begin();
					unsigned int numItems = items.size();
					if (t != items.end()) {
						for (unsigned int y = 0; y < layerSize.y; y++) {
							for (unsigned int x = 0; x < layerSize.x; x++) {
								for (unsigned int i = 0; i < numItems; i++) {
									if ((t->pos.x == x) && (t->pos.y == y)) break;
									t++;
									if (t == items.end()) t = items.begin();
								}
								if ((t->pos.x != x) || (t->pos.y != y)) {
									// Grid position with no tile!
									std::cout << "     ";
								} else {
									std::cout << std::hex << std::setw(4)
										<< (unsigned int)t->code << ' ';
								}
							}
							std::cout << "\n";
						}
					} else {
						std::cout << "Layer is empty!" << std::endl;
					}

				} else {
					std::cerr << "Support for printing this map type has not yet "
						"been implemented!" << std::endl;
				}

			} else if (i.string_key.compare("render") == 0) {
				// Don't need to check i.value[0], program_options does that for us

				auto map2d = std::dynamic_pointer_cast<gm::Map2D>(pMap);
				if (map2d) {
					gm::TilesetCollection allTilesets;

					for (auto& a : manualGfx) {
						if (!bScript) {
							std::cout << "Loading " << a.second.type << " from "
								<< a.second.filename << std::endl;
						}
						allTilesets[a.first] = openTileset(a.second.filename, a.second.type);
					}

					for (auto& a : pMap->graphicsFilenames()) {
						if (allTilesets.find(a.first) == allTilesets.end()) {
							if (a.second.filename.empty()) {
								std::cerr << toString(a.first) << " is required, and must "
									"be specified manually with --graphics." << std::endl;
								iRet = RET_BADARGS;
							} else {
								// This tileset hasn't been specified on the command line, but the
								// map format handler has given us a filename, so open the file
								// suggested from the map.
								allTilesets[a.first] = openTileset(a.second.filename, a.second.type);
							}
						} else {
							if (!a.second.filename.empty()) {
								std::cout << toString(a.first) << " overridden on command-line\n";
							}
						}
					}

					if (allTilesets.empty()) {
						std::cerr << "No tilesets were loaded, map cannot be rendered.  "
							"Use --graphics to specify a tileset." << std::endl;
						iRet = RET_BADARGS;
					} else {
						map2dToPng(*map2d, allTilesets, i.value[0]);
					}
				} else {
					std::cerr << PROGNAME ": Rendering this type of map is not yet "
						"implemented." << std::endl;
					return RET_SHOWSTOPPER;
				}

			// Ignore --type/-t
			} else if (i.string_key.compare("type") == 0) {
			} else if (i.string_key.compare("t") == 0) {
			// Ignore --script/-s
			} else if (i.string_key.compare("script") == 0) {
			} else if (i.string_key.compare("s") == 0) {
			// Ignore --force/-f
			} else if (i.string_key.compare("force") == 0) {
			} else if (i.string_key.compare("f") == 0) {

			}
		} // for (all command line elements)
		//pMap->flush();
	} catch (const po::error& e) {
		std::cerr << PROGNAME ": " << e.what()
			<< "  Use --help for help." << std::endl;
		return RET_BADARGS;
	} catch (const stream::error& e) {
		std::cerr << PROGNAME ": " << e.what()
			<< "  Use --help for help." << std::endl;
		return RET_SHOWSTOPPER;
	}

	return iRet;
}
示例#28
0
void MapWidget::loadMap(QString const & filename) {
    // read file

    QFile qf(filename);
    if (!qf.open(QIODevice::ReadOnly)) throw qf.errorString();

    QByteArray jsn_in = qf.readAll();
    qf.close();
    if (jsn_in.isEmpty()) throw QString("Empty file");

    // parse file

    QJsonDocument jsn_doc;
    if (filename.endsWith("json")) {
        jsn_doc = QJsonDocument::fromJson(jsn_in);
    } else {
        jsn_doc = QJsonDocument::fromBinaryData(jsn_in);
    }
    if (jsn_doc.isNull()) throw QString("Failed to validate JSON data");
    if (!jsn_doc.isObject()) throw QString("Top level JSON value is not an object");
    QJsonObject jsn_map = jsn_doc.object();

    // load generic map info

    QJsonObject::const_iterator it;
    it = jsn_map.find("rows");
    if (it == jsn_map.end()) throw QString("File not contains 'rows'");
    if (!it.value().isDouble()) throw QString("'rows' is not a number");
    int rows = int(it.value().toDouble());

    it = jsn_map.find("cols");
    if (it == jsn_map.end()) throw QString("File not contains 'cols'");
    if (!it.value().isDouble()) throw QString("'cols' is not a number");
    int cols = int(it.value().toDouble());

    // load tiles FIXME: each key must be in [0; jsn_tiles.size()-1] or assertion happens

    it = jsn_map.find("tiles");
    if (it == jsn_map.end()) throw QString("File not contains 'tiles'");
    if (!it.value().isObject()) throw QString("'cells' is not an object");
    QJsonObject jsn_tiles = it.value().toObject();
    QVector<MapTile> tiles(jsn_tiles.size());
    QSize tileSize(-1, -1);
    int prev_tile_id = -1;
    for(QJsonObject::const_iterator i = jsn_tiles.begin(); i != jsn_tiles.end(); ++i) {
        int tile_id = i.key().toInt();
        if (tile_id - prev_tile_id != 1) throw QString("Non-monotonic tile keys");
        if (!i.value().isString()) throw QString("Incorrect tile's path");
        QImage im(i.value().toString());
        if (im.isNull()) throw QString("Can't open image");
        if (tileSize.isEmpty()) {
            tileSize = im.size();
        } else if (tileSize != im.size()) {
            throw QString("Tile's dimensions not same");
        }
        tiles[tile_id] = MapTile(i.value().toString(), im);
        prev_tile_id = tile_id;
    }

    // load cells

    QVector<int> cells(cols * rows);
    it = jsn_map.find("cells");
    if (it == jsn_map.end()) throw QString("File not contains 'cells'");
    if (!it.value().isArray()) throw QString("'cells' is not an array");
    QJsonArray jsn_cells = it.value().toArray();
    if (jsn_cells.size() != cols * rows) throw QString("Incorrect 'cells' length");
    int index = -1;
    for(QJsonArray::const_iterator i = jsn_cells.begin(); i != jsn_cells.end(); ++i) {
        if (!(*i).isDouble()) throw QString("Not number in 'cells'");
        int val = int((*i).toDouble());
        if (val < -1 || val >= tiles.size()) throw QString("Incorrect range in 'cells'");
        if (val > 0 && false == tiles[val].isValid()) throw QString("Incorrect link in 'cells'");
        cells[++index] = val;
    }

    // if everything is fine
    mCells = cells;
    mTiles = tiles;
    mRows = rows;
    mCols = cols;
    mTileSize = tileSize;
    mViewportPos = QPointF(.0f, .0f);
    mCellUnderMouse = QPoint(-1, -1);
    mSelectionBegin = NULL;
    mSelectionEnd = NULL;
    mScale = 1.0f;

    update();
}
示例#29
0
SlamKeyFrame *SlamMapExpander::addKeyFrame()
{
	ProfileSection s("addKeyFrame");
	mStatus = ESlamMapExpanderStatus::AddingFrame;

	DTSLAM_LOG << "---------------------\n"
				<< "Adding new key frame, ID=" << mData->frame->getTimestamp() << "!\n"
				<< "---------------------\n";

	/////////////////////////////////////////////
	//Check if we need to start a new region because of scale mismatch
	if (mRegion->getFirstTriangulationFrame() && mData->poseType == EPoseEstimationType::Essential)
	{
		DTSLAM_LOG << "\n-------------------------\nBeginning new region\n-------------------------\n";

		//Create new active region
		mRegion = mSlam->getMap().createRegion();

		//Duplicate reference key frame
		SlamKeyFrame *referenceFrameOld = mData->essentialReferenceFrame;
		mRegion->setPreviousRegionSourceFrame(referenceFrameOld);

		std::unique_ptr<SlamKeyFrame> referenceFrameNew = referenceFrameOld->copyWithoutFeatures();
		referenceFrameNew->setPose(std::unique_ptr<Pose3D>(new FullPose3D())); //Identity

		//Duplicate features
		std::unordered_map<SlamFeature*, SlamFeature*> featureMap;
		mData->frame->getMeasurements().clear();
		for (auto &mPtr : referenceFrameOld->getMeasurements())
		{
			auto &m = *mPtr;
			SlamFeature *newFeature = mRegion->createFeature2D(*referenceFrameNew, m.getPositions()[0], m.getPositionXns()[0], m.getOctave());
			featureMap.insert(std::make_pair(&m.getFeature(), newFeature));
		}

		//Replace features in refined match
		std::vector<FeatureMatch> newRefinedMatches;
		std::vector<bool> newRefinedMatchesInliers;
		for (int i = 0, end = mRefinedMatches.size(); i!=end; ++i)
		{
			auto &match = mRefinedMatches[i];
			auto &m = match.measurement;

			//Check if feature is in new region
			auto itFeatureMap = featureMap.find(&m.getFeature());
			if (itFeatureMap != featureMap.end())
			{
				//Feature in new region, copy
				newRefinedMatches.push_back(FeatureMatch(FeatureProjectionInfo(), NULL, SlamFeatureMeasurement(itFeatureMap->second, &m.getKeyFrame(), m.getPositions(), m.getPositionXns(), m.getOctave()), match.trackLength));
				newRefinedMatchesInliers.push_back(mRefinedMatchesInliers[i]);
			}
		}
		mRefinedMatches = std::move(newRefinedMatches);

		//Add reference frame for new region
		mRegion->addKeyFrame(std::move(referenceFrameNew));

		//Update active region
		mSlam->setActiveRegion(mRegion);


		//Transform essential pose to new reference frame (where referenceFrame is at the origin)
		Pose3D &oldEssentialPose = mData->frame->getPose();
		mData->frame->setPose(std::unique_ptr<Pose3D>(new FullPose3D(FullPose3D::MakeRelativePose(referenceFrameOld->getPose(), oldEssentialPose))));

		mData->essentialReferenceFrame = mRegion->getKeyFrames().front().get();
		int newCount = checkRefinedMatchesForTriangulations();
		DTSLAM_LOG << "After checking again " << newCount << "/" << mRefinedMatches.size() << " matches ready for triangulation.\n";
	}

	/////////////////////////////////////////////
	//Add measurements to matched features
	int triangulateCount=0;
	for (int i = 0, end = mRefinedMatches.size(); i != end; ++i)
	{
		FeatureMatch &match = mRefinedMatches[i];
		SlamFeature &feature = match.measurement.getFeature();

		if (feature.getStatus() == SlamFeatureStatus::Invalid)
			continue; //Skip features that were deleted in the process

		//Add measurements
		std::unique_ptr<SlamFeatureMeasurement> measurement(new SlamFeatureMeasurement(match.measurement));

		mData->frame->getMeasurements().push_back(measurement.get());
		feature.getMeasurements().push_back(std::move(measurement));

		//Triangulate
		if (mRefinedMatchesReadyForTriangulation[i] && !feature.is3D())
		{
			SlamFeatureMeasurement *m1;
			SlamFeatureMeasurement *m2;
			float angle;
			feature.getMeasurementsForTriangulation(m1,m2,angle);
			if(m1 && m2) // && angle > mMinTriangulationAngle
			{
				mRegion->convertTo3D(feature,*m1,*m2);
				triangulateCount++;
			}
		}
	}
	DTSLAM_LOG << "Features triangulated: " << triangulateCount << "\n";

	/////////////////////////////////////////////
	//Add new 2D features
	int newKeyPointCount=0;
	cv::Size2i imageSize = mData->frame->getImage(0).size();
	for (int octave = 0; octave<mData->frame->getPyramid().getOctaveCount(); ++octave)
	{
		const int scale = 1<<octave;

		//FeatureGridIndexer<KeyPointData> keypoints = mData->frame->getKeyPoints(octave).applyNonMaximaSuppresion(scale*PatchWarper::kPatchRightSize);
		//auto &keypoints = mData->frame->getKeyPoints(octave);
		cv::Size2i tileSize(scale*FLAGS_FrameKeypointGridSize, scale*FLAGS_FrameKeypointGridSize);
		auto keypoints = FeatureGridIndexer<KeyPointData>::ApplyNonMaximaSuppresion(mData->frame->getKeyPoints(octave), imageSize, tileSize, scale*PatchWarper::kPatchRightSize);
		for (auto &keyPoint : keypoints)
		{
			int cellX = keyPoint.position.x / mFeatureCoverageMaskScale;
			int cellY = keyPoint.position.y / mFeatureCoverageMaskScale;

			if(mFeatureCoverageMask(cellY,cellX) != ECellCoveredByOld)
			{
				//Add new 2D feature
				mRegion->createFeature2D(*mData->frame, keyPoint.position, keyPoint.xn, octave);
				newKeyPointCount++;
			}
		}
	}
	DTSLAM_LOG << "New 2D features added: " << newKeyPointCount << "\n";

	/////////////////////////////////////////////
	//Add key frame
	SlamKeyFrame *res = mData->frame.get();

	mData->frame->mOriginalRegionID = mRegion->getId();
	mRegion->addKeyFrame(std::move(mData->frame));

	mStatus = ESlamMapExpanderStatus::Inactive;
	return res;
}
示例#30
0
dng_point dng_area_task::FindTileSize (const dng_rect &area) const
	{
	
	dng_rect repeatingTile1 = RepeatingTile1 ();
	dng_rect repeatingTile2 = RepeatingTile2 ();
	dng_rect repeatingTile3 = RepeatingTile3 ();
	
	if (repeatingTile1.IsEmpty ())
		{
		repeatingTile1 = area;
		}
	
	if (repeatingTile2.IsEmpty ())
		{
		repeatingTile2 = area;
		}
	
	if (repeatingTile3.IsEmpty ())
		{
		repeatingTile3 = area;
		}
		
	uint32 repeatV = Min_uint32 (Min_uint32 (repeatingTile1.H (),
											 repeatingTile2.H ()),
											 repeatingTile3.H ());
	
	uint32 repeatH = Min_uint32 (Min_uint32 (repeatingTile1.W (),
											 repeatingTile2.W ()),
											 repeatingTile3.W ());
	
	dng_point maxTileSize  = MaxTileSize ();

	dng_point tileSize (maxTileSize);
	
	tileSize.v = Min_int32 (tileSize.v, repeatV);
	tileSize.h = Min_int32 (tileSize.h, repeatH);
						
	uint32 countV = (repeatV + tileSize.v - 1) / tileSize.v;
	uint32 countH = (repeatH + tileSize.h - 1) / tileSize.h;
	
	tileSize.v = (repeatV + countV - 1) / countV;
	tileSize.h = (repeatH + countH - 1) / countH;
	
	dng_point unitCell = UnitCell ();
	
	tileSize.v = ((tileSize.v + unitCell.v - 1) / unitCell.v) * unitCell.v;
	tileSize.h = ((tileSize.h + unitCell.h - 1) / unitCell.h) * unitCell.h;
	
	if (tileSize.v > maxTileSize.v)
		{
		tileSize.v = (maxTileSize.v / unitCell.v) * unitCell.v;
		}
		
	if (tileSize.h > maxTileSize.h)
		{
		tileSize.h = (maxTileSize.h / unitCell.h) * unitCell.h;
		}
		
	return tileSize;
	
	}