void World::CreateNamedRT(String worldName)
{
    Graphics* g = context->GetSubsystem<Graphics>();
    int w = g->GetWidth();
    int h = g->GetHeight();


    renderTexture = SharedPtr<Texture2D>(new Texture2D(context));


    if (renderTexture)
    {
        renderTexture->SetSize(w, h, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
        renderTexture->SetFilterMode(FILTER_NEAREST);
        renderTexture->SetName(worldName);

        ResourceCache* cache = context->GetSubsystem<ResourceCache>();
        cache->AddManualResource(renderTexture);


        RenderSurface* surface = renderTexture->GetRenderSurface();
        surface->SetUpdateMode(RenderSurfaceUpdateMode::SURFACE_UPDATEALWAYS);
        surface->SetViewport(0, camera.vp);

    }
}
Beispiel #2
0
static void drawedge(PathNode* from, PathNode* to, uint32 rgb)
{
	RenderSurface* screen = GUIApp::get_instance()->getScreen();
	sint32 cx, cy, cz;

	GUIApp::get_instance()->getGameMapGump()->GetCameraLocation(cx, cy, cz);

	Pentagram::Rect d;
	screen->GetSurfaceDims(d);

	sint32 x0, y0, x1, y1;

	cx = from->state.x - cx;
	cy = from->state.y - cy;
	cz = from->state.z - cz;

	x0 = (d.w/2) + (cx - cy)/2;
	y0 = (d.h/2) + (cx + cy)/4 - cz*2;

	GUIApp::get_instance()->getGameMapGump()->GetCameraLocation(cx, cy, cz);

	cx = to->state.x - cx;
	cy = to->state.y - cy;
	cz = to->state.z - cz;

	x1 = (d.w/2) + (cx - cy)/2;
	y1 = (d.h/2) + (cx + cy)/4 - cz*2;

	screen->DrawLine32(rgb, x0, y0, x1, y1);
}
Beispiel #3
0
void RTTScene::CreateScene()
{
	rttScene_ = new Scene(context_);
	rttScene_->CreateComponent<Octree>();

	Node* zoneNode = rttScene_->CreateChild("Zone");
	Zone* zone = zoneNode->CreateComponent<Zone>();
	zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
	zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
	zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
	zone->SetFogStart(10.0f);
	zone->SetFogEnd(100.0f);

	//用来指定ViewPort时的定位
	rttCameraNode_ = rttScene_->CreateChild("Camera");
	Camera* camera = rttCameraNode_->CreateComponent<Camera>();
	
	Light* light = rttCameraNode_->CreateComponent<Light>();
	light->SetLightType(LIGHT_POINT);

	renderTexture = new Texture2D(context_);
	//设置当前场景的ViewPort
	renderTexture->SetSize(_width,_height,Graphics::GetRGBFormat(),TEXTURE_RENDERTARGET);
	RenderSurface* surface = renderTexture->GetRenderSurface();
	renderTexture->SetFilterMode(FILTER_BILINEAR);

	Viewport* rttViewPort = new Viewport(context_,rttScene_,camera);
	surface->SetViewport(0,rttViewPort);
}
void UISceneView::QueueUpdate()
{
    if (!autoUpdate_)
    {
        RenderSurface* surface = renderTexture_->GetRenderSurface();
        if (surface)
            surface->QueueUpdate();
    }
}
void UISceneView::SetAutoUpdate(bool enable)
{
    if (enable != autoUpdate_)
    {
        autoUpdate_ = enable;
        RenderSurface* surface = renderTexture_->GetRenderSurface();
        if (surface)
            surface->SetUpdateMode(autoUpdate_ ? SURFACE_UPDATEALWAYS : SURFACE_MANUALUPDATE);
    }
}
Beispiel #6
0
void Adaptor::ReplaceSurface( Dali::RenderSurface& surface )
{
  // adaptor implementation needs the implementation of
  RenderSurface* internalSurface = dynamic_cast<Internal::Adaptor::RenderSurface*>( &surface );
  DALI_ASSERT_ALWAYS( internalSurface && "Incorrect surface" );

  mSurface = internalSurface;

  SurfaceSizeChanged( internalSurface->GetPositionSize() );

  // flush the event queue to give update and render threads chance
  // to start processing messages for new camera setup etc as soon as possible
  ProcessCoreEvents();

  // this method is synchronous
  mUpdateRenderController->ReplaceSurface(internalSurface);
}
Beispiel #7
0
static void drawdot(sint32 x, sint32 y, sint32 z, int size, uint32 rgb)
{
	RenderSurface* screen = GUIApp::get_instance()->getScreen();
	sint32 cx, cy, cz;

	GUIApp::get_instance()->getGameMapGump()->GetCameraLocation(cx, cy, cz);

	Pentagram::Rect d;
	screen->GetSurfaceDims(d);
	x -= cx;
	y -= cy;
	z -= cz;
	sint32 x0,y0;
	x0 = (d.w/2) + (x - y)/2;
	y0 = (d.h/2) + (x + y)/4 - z*2;
	screen->Fill32(rgb, x0-size, y0-size, 2*size+1, 2*size+1);
}
Beispiel #8
0
void Water::SetupViewport()
{
    Graphics* graphics = GetContext()->m_Graphics.get();
    Renderer* renderer = GetContext()->m_Renderer.get();
    ResourceCache* cache = GetContext()->m_ResourceCache.get();

    // Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
    SharedPtr<Viewport> viewport(new Viewport(GetContext(), scene_, cameraNode_->GetComponent<Camera>()));
    renderer->SetViewport(0, viewport);

    // Create a mathematical plane to represent the water in calculations
    waterPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition());
    // Create a downward biased plane for reflection view clipping. Biasing is necessary to avoid too aggressive clipping
    waterClipPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition() -
                            Vector3(0.0f, 0.1f, 0.0f));

    // Create camera for water reflection
    // It will have the same farclip and position as the main viewport camera, but uses a reflection plane to modify
    // its position when rendering
    reflectionCameraNode_ = cameraNode_->CreateChild();
    Camera* reflectionCamera = reflectionCameraNode_->CreateComponent<Camera>();
    reflectionCamera->setFarClipDistance(750.0);
    reflectionCamera->SetViewMask(0x7fffffff); // Hide objects with only bit 31 in the viewmask (the water plane)
    reflectionCamera->SetAutoAspectRatio(false);
    reflectionCamera->SetUseReflection(true);
    reflectionCamera->SetReflectionPlane(waterPlane_);
    reflectionCamera->SetUseClipping(true); // Enable clipping of geometry behind water plane
    reflectionCamera->SetClipPlane(waterClipPlane_);
    // The water reflection texture is rectangular. Set reflection camera aspect ratio to match
    reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());
    // View override flags could be used to optimize reflection rendering. For example disable shadows
    //reflectionCamera->SetViewOverrideFlags(VO_DISABLE_SHADOWS);

    // Create a texture and setup viewport for water reflection. Assign the reflection texture to the diffuse
    // texture unit of the water material
    int texSize = 1024;
    SharedPtr<Texture2D> renderTexture(new Texture2D(GetContext()));
    renderTexture->SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
    renderTexture->SetFilterMode(FILTER_BILINEAR);
    RenderSurface* surface = renderTexture->GetRenderSurface();
    SharedPtr<Viewport> rttViewport(new Viewport(GetContext(), scene_, reflectionCamera));
    surface->SetViewport(0, rttViewport);
    Material* waterMat = cache->GetResource<Material>("Materials/Water.xml");
    waterMat->SetTexture(TU_DIFFUSE, renderTexture);
}
Beispiel #9
0
static void drawbox(Item* item)
{
	RenderSurface* screen = GUIApp::get_instance()->getScreen();
	sint32 cx, cy, cz;

	GUIApp::get_instance()->getGameMapGump()->GetCameraLocation(cx, cy, cz);

	Pentagram::Rect d;
	screen->GetSurfaceDims(d);

	sint32 ix, iy, iz;
	item->getLocation(ix, iy, iz);

	sint32 xd, yd, zd;
	item->getFootpadWorld(xd, yd, zd);

	ix -= cx;
	iy -= cy;
	iz -= cz;

	sint32 x0,y0,x1,y1,x2,y2,x3,y3;

	x0 = (d.w/2) + (ix - iy)/2;
	y0 = (d.h/2) + (ix + iy)/4 - iz*2;

	x1 = (d.w/2) + (ix - iy)/2;
	y1 = (d.h/2) + (ix + iy)/4 - (iz+zd)*2;

	x2 = (d.w/2) + (ix-xd - iy)/2;
	y2 = (d.h/2) + (ix-xd + iy)/4 - iz*2;

	x3 = (d.w/2) + (ix - iy+yd)/2;
	y3 = (d.h/2) + (ix + iy-yd)/4 - iz*2;

	screen->Fill32(0xFF0000FF, x0-1, y0-1, 3, 3);

	screen->DrawLine32(0xFF00FF00, x0, y0, x1, y1);
	screen->DrawLine32(0xFF00FF00, x0, y0, x2, y2);
	screen->DrawLine32(0xFF00FF00, x0, y0, x3, y3);
}
// ---------------------------------------------------------------------------------------------------------
LVEDRENDERINGENGINE_API void __stdcall LvEd_End()
{
    RenderContext* rc = RenderContext::Inst();
    RenderSurface* surface = s_engineData->pRenderSurface;

    s_engineData->basicRenderer->End();    
    LineRenderer::Inst()->RenderAll(rc);
    ErrorHandler::ClearError();    
    LvEdFonts::FontRenderer::Inst()->FlushPrintRequests( rc );
    
    if(surface->GetType() == RenderSurface::kSwapChain)
    {        
        RenderWorldAxis();
        SwapChain* swapchain = static_cast<SwapChain*>(surface);
        HRESULT hr = swapchain->GetDXGISwapChain()->Present(0,0);
        Logger::IsFailureLog(hr, L"presenting swapchain");
    }

    s_engineData->renderableSorter.ClearLists();    
    s_engineData->pRenderSurface = NULL;    
    RenderContext::Inst()->LightEnvDirty = false; 
}
void UISceneView::OnResize(const IntVector2 &newSize)
{
    if (newSize.x_ == size_.x_ && newSize.y_ == size_.y_)
        return;

    int width = newSize.x_;
    int height = newSize.y_;

    if (width > 0 && height > 0)
    {
        viewport_->SetRect(IntRect(0, 0, width, height));
        renderTexture_->SetSize(width, height, rttFormat_, TEXTURE_RENDERTARGET);
        depthTexture_->SetSize(width, height, Graphics::GetDepthStencilFormat(), TEXTURE_DEPTHSTENCIL);

        RenderSurface* surface = renderTexture_->GetRenderSurface();
        surface->SetViewport(0, viewport_);
        surface->SetUpdateMode(autoUpdate_ ? SURFACE_UPDATEALWAYS : SURFACE_MANUALUPDATE);
        surface->SetLinkedDepthStencil(depthTexture_->GetRenderSurface());

        size_ = newSize;

    }
}
Beispiel #12
0
void GameMain::WaterSetup(Urho3D::String waterNodeName) 
{
	ResourceCache* cache = GetSubsystem<ResourceCache>();
	Graphics* graphics = GetSubsystem<Graphics>();

	Node* waterNode_ = scene_->GetChild("waterNode",true);
	StaticModel* waterMesh = waterNode_->GetComponent<StaticModel>();
	waterMesh->SetViewMask(0x80000000);
	world.camera.waterPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition()); 
	world.camera.waterClipPlane_ = Plane(waterNode_->GetWorldRotation() * Vector3(0.0f, 1.0f, 0.0f), waterNode_->GetWorldPosition() - Vector3(0.0f, 0.1f, 0.0f));
	world.camera.reflectionCameraNode_ = world.camera.node_->CreateChild();
	Camera* reflectionCamera = world.camera.reflectionCameraNode_->CreateComponent<Camera>();
	
	reflectionCamera->SetFarClip(1000.0);
	reflectionCamera->SetFov(75.0f);
	

	reflectionCamera->SetViewMask(0x7fffffff); // Hide objects with only bit 31 in the viewmask (the water plane)
	reflectionCamera->SetAutoAspectRatio(false);
	reflectionCamera->SetUseReflection(true);
	reflectionCamera->SetReflectionPlane(world.camera.waterPlane_);
	reflectionCamera->SetUseClipping(true); // Enable clipping of geometry behind water plane
	reflectionCamera->SetClipPlane(world.camera.waterClipPlane_);
	reflectionCamera->SetAspectRatio((float)graphics->GetWidth() / (float)graphics->GetHeight());

	int texSize = 1024;
	SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
	renderTexture->SetSize(texSize, texSize, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
	renderTexture->SetFilterMode(FILTER_BILINEAR);
	RenderSurface* surface = renderTexture->GetRenderSurface();
	SharedPtr<Viewport> rttViewport(new Viewport(context_, scene_, reflectionCamera));
	surface->SetViewport(0, rttViewport);
	Material* waterMat = cache->GetResource<Material>("Materials/Water.xml");
	waterMat->SetTexture(TU_DIFFUSE, renderTexture);

}
LVEDRENDERINGENGINE_API bool __stdcall LvEd_SaveRenderSurfaceToFile(ObjectGUID renderSurfaceId, wchar_t *fileName)
{
    ErrorHandler::ClearError();
       
    if(fileName == NULL || wcslen(fileName) == 0 )
    {
        ErrorHandler::SetError(ErrorType::UnknownError, L"%s: filename is empty", __WFUNCTION__);
        return false;
    }

    DirectX::ScratchImage scratchImg; 
    RenderSurface* renderSurface = reinterpret_cast<RenderSurface*>(renderSurfaceId);
    
    HRESULT hr = CaptureTexture(gD3D11->GetDevice(),::gD3D11->GetImmediateContext(),
        (ID3D11Resource*)renderSurface->GetColorBuffer()->GetTex(),scratchImg);
    if(FAILED(hr)) return false;
        
    const DirectX::Image* img = scratchImg.GetImage(0,0,0);

    ImageData imgdata;
    imgdata.InitFrom(img);
    imgdata.SaveToFile(fileName);   
    return SUCCEEDED(hr);
}
Beispiel #14
0
void RenderToTexture::CreateScene()
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();

    {
        // Create the scene which will be rendered to a texture
        rttScene_ = new Scene(context_);

        // Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
        rttScene_->CreateComponent<Octree>();

        // Create a Zone for ambient light & fog control
        Node* zoneNode = rttScene_->CreateChild("Zone");
        Zone* zone = zoneNode->CreateComponent<Zone>();
        // Set same volume as the Octree, set a close bluish fog and some ambient light
        zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
        zone->SetAmbientColor(Color(0.05f, 0.1f, 0.15f));
        zone->SetFogColor(Color(0.1f, 0.2f, 0.3f));
        zone->SetFogStart(10.0f);
        zone->SetFogEnd(100.0f);

        // Create randomly positioned and oriented box StaticModels in the scene
        const unsigned NUM_OBJECTS = 2000;
        for (unsigned i = 0; i < NUM_OBJECTS; ++i)
        {
            Node* boxNode = rttScene_->CreateChild("Box");
            boxNode->SetPosition(Vector3(Random(200.0f) - 100.0f, Random(200.0f) - 100.0f, Random(200.0f) - 100.0f));
            // Orient using random pitch, yaw and roll Euler angles
            boxNode->SetRotation(Quaternion(Random(360.0f), Random(360.0f), Random(360.0f)));
            StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
            boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
            boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));

            // Add our custom Rotator component which will rotate the scene node each frame, when the scene sends its update event.
            // Simply set same rotation speed for all objects
            Rotator* rotator = boxNode->CreateComponent<Rotator>();
            rotator->SetRotationSpeed(Vector3(10.0f, 20.0f, 30.0f));
        }

        // Create a camera for the render-to-texture scene. Simply leave it at the world origin and let it observe the scene
        rttCameraNode_ = rttScene_->CreateChild("Camera");
        Camera* camera = rttCameraNode_->CreateComponent<Camera>();
        camera->SetFarClip(100.0f);

        // Create a point light to the camera scene node
        Light* light = rttCameraNode_->CreateComponent<Light>();
        light->SetLightType(LIGHT_POINT);
        light->SetRange(30.0f);
    }

    {
        // Create the scene in which we move around
        scene_ = new Scene(context_);

        // Create octree, use also default volume (-1000, -1000, -1000) to (1000, 1000, 1000)
        scene_->CreateComponent<Octree>();

        // Create a Zone component for ambient lighting & fog control
        Node* zoneNode = scene_->CreateChild("Zone");
        Zone* zone = zoneNode->CreateComponent<Zone>();
        zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));
        zone->SetAmbientColor(Color(0.1f, 0.1f, 0.1f));
        zone->SetFogStart(100.0f);
        zone->SetFogEnd(300.0f);

        // Create a directional light without shadows
        Node* lightNode = scene_->CreateChild("DirectionalLight");
        lightNode->SetDirection(Vector3(0.5f, -1.0f, 0.5f));
        Light* light = lightNode->CreateComponent<Light>();
        light->SetLightType(LIGHT_DIRECTIONAL);
        light->SetColor(Color(0.2f, 0.2f, 0.2f));
        light->SetSpecularIntensity(1.0f);

        // Create a "floor" consisting of several tiles
        for (int y = -5; y <= 5; ++y)
        {
            for (int x = -5; x <= 5; ++x)
            {
                Node* floorNode = scene_->CreateChild("FloorTile");
                floorNode->SetPosition(Vector3(x * 20.5f, -0.5f, y * 20.5f));
                floorNode->SetScale(Vector3(20.0f, 1.0f, 20.f));
                StaticModel* floorObject = floorNode->CreateComponent<StaticModel>();
                floorObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
                floorObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));
            }
        }

        // Create a "screen" like object for viewing the second scene. Construct it from two StaticModels, a box for the frame
        // and a plane for the actual view
        {
            Node* boxNode = scene_->CreateChild("ScreenBox");
            boxNode->SetPosition(Vector3(0.0f, 10.0f, 0.0f));
            boxNode->SetScale(Vector3(21.0f, 16.0f, 0.5f));
            StaticModel* boxObject = boxNode->CreateComponent<StaticModel>();
            boxObject->SetModel(cache->GetResource<Model>("Models/Box.mdl"));
            boxObject->SetMaterial(cache->GetResource<Material>("Materials/Stone.xml"));

            Node* screenNode = scene_->CreateChild("Screen");
            screenNode->SetPosition(Vector3(0.0f, 10.0f, -0.27f));
            screenNode->SetRotation(Quaternion(-90.0f, 0.0f, 0.0f));
            screenNode->SetScale(Vector3(20.0f, 0.0f, 15.0f));
            StaticModel* screenObject = screenNode->CreateComponent<StaticModel>();
            screenObject->SetModel(cache->GetResource<Model>("Models/Plane.mdl"));

            // Create a renderable texture (1024x768, RGB format), enable bilinear filtering on it
            SharedPtr<Texture2D> renderTexture(new Texture2D(context_));
            renderTexture->SetSize(1024, 768, Graphics::GetRGBFormat(), TEXTURE_RENDERTARGET);
            renderTexture->SetFilterMode(FILTER_BILINEAR);

            // Create a new material from scratch, use the diffuse unlit technique, assign the render texture
            // as its diffuse texture, then assign the material to the screen plane object
            SharedPtr<Material> renderMaterial(new Material(context_));
            renderMaterial->SetTechnique(0, cache->GetResource<Technique>("Techniques/DiffUnlit.xml"));
            renderMaterial->SetTexture(TU_DIFFUSE, renderTexture);
            screenObject->SetMaterial(renderMaterial);

            // Get the texture's RenderSurface object (exists when the texture has been created in rendertarget mode)
            // and define the viewport for rendering the second scene, similarly as how backbuffer viewports are defined
            // to the Renderer subsystem. By default the texture viewport will be updated when the texture is visible
            // in the main view
            RenderSurface* surface = renderTexture->GetRenderSurface();
            SharedPtr<Viewport> rttViewport(new Viewport(context_, rttScene_, rttCameraNode_->GetComponent<Camera>()));
            surface->SetViewport(0, rttViewport);
        }

        // Create the camera which we will move around. Limit far clip distance to match the fog
        cameraNode_ = scene_->CreateChild("Camera");
        Camera* camera = cameraNode_->CreateComponent<Camera>();
        camera->SetFarClip(300.0f);

        // Set an initial position for the camera scene node above the plane
        cameraNode_->SetPosition(Vector3(0.0f, 7.0f, -30.0f));
    }
}
Beispiel #15
0
void Pathfinder::newNode(PathNode* oldnode, PathfindingState& state,
						 unsigned int steps)
{
	PathNode* newnode = new PathNode();
	nodelist.push_back(newnode); // for garbage collection
	newnode->state = state;
	newnode->parent = oldnode;
	newnode->depth = oldnode->depth + 1;
	newnode->stepsfromparent = 0;
	
	double sqrddist;
	
	sqrddist = ((newnode->state.x - oldnode->state.x)*
				(newnode->state.x - oldnode->state.x));
	sqrddist += ((newnode->state.y - oldnode->state.y)*
				 (newnode->state.y - oldnode->state.y));
	sqrddist += ((newnode->state.z - oldnode->state.z)*
				 (newnode->state.z - oldnode->state.z));
	
	unsigned int dist;
	dist = static_cast<unsigned int>(std::sqrt(sqrddist));
	
	int turn = 0;
	
	if (oldnode->depth > 0) {
		turn = state.direction - oldnode->state.direction;
		if (turn < 0) turn = -turn;
		if (turn > 4) turn = 8 - turn;
	}
	
	newnode->cost = oldnode->cost + dist + 32*turn; //!! constant

	bool done = checkTarget(newnode);
	if (done)
		newnode->heuristicTotalCost = 0;
	else
		costHeuristic(newnode);

#if 0
	perr << "trying dir " << state.direction;

	if (steps > 0) {
		perr << ", " << steps << " steps";
	}
	perr << " from ("
		 << oldnode->state.x << "," << oldnode->state.y << ") to ("
		 << newnode->state.x << "," << newnode->state.y
		 << "), cost = " << newnode->cost << ", heurtotcost = "
		 << newnode->heuristicTotalCost << std::endl;
#endif

#ifdef DEBUG
	if (actor->getObjId() == visualdebug_actor) {
		RenderSurface* screen = GUIApp::get_instance()->getScreen();
		screen->BeginPainting();
		drawpath(newnode, 0xFFFFFF00, done);
		screen->EndPainting();
		SDL_Delay(250);
		if (!done) {
			screen->BeginPainting();
			drawpath(newnode, 0xFFB0B000, done);
			screen->EndPainting();
		}
	}
#endif

	nodes.push(newnode);	
}
static osgViewer::View* load(const std::string& file, const osgDB::ReaderWriter::Options* /*option*/)
{
    osg::ref_ptr<CameraConfig> config = new CameraConfig;
    //std::cout << "Parse file " << file << std::endl;
    config->parseFile(file);

    RenderSurface* rs = 0;
    Camera* cm = 0;
    std::map<RenderSurface*,osg::ref_ptr<osg::GraphicsContext> > surfaces;
    osg::ref_ptr<osgViewer::View> _view = new osgViewer::View;

    if (config->getNumberOfCameras()==1)
    {
        cm = config->getCamera(0);
        rs = cm->getRenderSurface();
        if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window) return 0;

        osg::ref_ptr<const osg::GraphicsContext::Traits> traits;
        osg::ref_ptr<osg::GraphicsContext> gc;
        if (surfaces.find(rs) != surfaces.end())
        {
            gc = surfaces[rs];
            traits = gc.valid() ? gc->getTraits() : 0;
        }
        else
        {
            osg::GraphicsContext::Traits* newtraits = buildTrait(*rs);

#if 0
            osg::GraphicsContext::ScreenIdentifier si;
            si.readDISPLAY();

            if (si.displayNum>=0) newtraits->displayNum = si.displayNum;
            if (si.screenNum>=0) newtraits->screenNum = si.screenNum;
#endif

            gc = osg::GraphicsContext::createGraphicsContext(newtraits);

            surfaces[rs] = gc.get();
            traits = gc.valid() ? gc->getTraits() : 0;
        }

        // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl;

        if (gc.valid())
        {
            OSG_INFO<<"  GraphicsWindow has been created successfully."<<std::endl;

            osg::ref_ptr<osg::Camera> camera = _view->getCamera();

            camera->setGraphicsContext(gc.get());

            int x,y;
            unsigned int width,height;
            cm->applyLens();
            cm->getProjectionRectangle(x, y, width, height);
            camera->setViewport(new osg::Viewport(x, y, width, height));

            GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
            camera->setDrawBuffer(buffer);
            camera->setReadBuffer(buffer);
            camera->setProjectionMatrix(osg::Matrixd(cm->getProjectionMatrix()));
            camera->setViewMatrix(osg::Matrixd(cm->getPositionAndAttitudeMatrix()));

            #if 0
            std::cout << "Matrix Projection " << projection << std::endl;
            std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl;
            // will work only if it's a post multyply in the producer camera
            std::cout << "Matrix View " << view << std::endl;
            std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl;
            #endif
        }
        else
        {
            OSG_INFO<<"  GraphicsWindow has not been created successfully."<<std::endl;
            return 0;
        }

    }
    else
    {
        for (int i = 0; i < (int)config->getNumberOfCameras(); i++)
        {
            cm = config->getCamera(i);
            rs = cm->getRenderSurface();
            if (rs->getDrawableType() != osgProducer::RenderSurface::DrawableType_Window)
                continue;

            osg::ref_ptr<const osg::GraphicsContext::Traits> traits;
            osg::ref_ptr<osg::GraphicsContext> gc;
            if (surfaces.find(rs) != surfaces.end())
            {
                gc = surfaces[rs];
                traits = gc.valid() ? gc->getTraits() : 0;
            }
            else
            {
                osg::GraphicsContext::Traits* newtraits = buildTrait(*rs);

    #if 0
                osg::GraphicsContext::ScreenIdentifier si;
                si.readDISPLAY();

                if (si.displayNum>=0) newtraits->displayNum = si.displayNum;
                if (si.screenNum>=0) newtraits->screenNum = si.screenNum;
    #endif

                gc = osg::GraphicsContext::createGraphicsContext(newtraits);

                surfaces[rs] = gc.get();
                traits = gc.valid() ? gc->getTraits() : 0;
            }

            // std::cout << rs->getWindowName() << " " << rs->getWindowOriginX() << " " << rs->getWindowOriginY() << " " << rs->getWindowWidth() << " " << rs->getWindowHeight() << std::endl;

            if (gc.valid())
            {
                OSG_INFO<<"  GraphicsWindow has been created successfully."<<std::endl;

                osg::ref_ptr<osg::Camera> camera = new osg::Camera;
                camera->setGraphicsContext(gc.get());


                int x,y;
                unsigned int width,height;
                cm->applyLens();
                cm->getProjectionRectangle(x, y, width, height);
                camera->setViewport(new osg::Viewport(x, y, width, height));

                GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT;
                camera->setDrawBuffer(buffer);
                camera->setReadBuffer(buffer);

                osg::Matrix projection(cm->getProjectionMatrix());

                osg::Matrix offset = osg::Matrix::identity();
                cm->setViewByMatrix(offset);
                osg::Matrix view = osg::Matrix(cm->getPositionAndAttitudeMatrix());

                // setup projection from parent
                osg::Matrix offsetProjection = osg::Matrix::inverse(_view->getCamera()->getProjectionMatrix()) * projection;
                _view->addSlave(camera.get(), offsetProjection, view);

                #if 0
                std::cout << "Matrix Projection " << projection << std::endl;
                std::cout << "Matrix Projection master " << _view->getCamera()->getProjectionMatrix() << std::endl;
                // will work only if it's a post multyply in the producer camera
                std::cout << "Matrix View " << view << std::endl;
                std::cout << _view->getCamera()->getProjectionMatrix() * offsetProjection << std::endl;
                #endif
            }
            else
            {
                OSG_INFO<<"  GraphicsWindow has not been created successfully."<<std::endl;
                return 0;
            }
        }
    }

    // std::cout << "done" << std::endl;
    return _view.release();
}
Beispiel #17
0
void GameMapGump::ConCmd_dumpMap(const Console::ArgvType &)
{
	// We only support 32 bits per pixel for now
	if (RenderSurface::format.s_bpp != 32) return;

	// Save because we're going to potentially break the game by enlarging
	// the fast area and available object IDs.
	std::string savefile = "@save/dumpmap";
	GUIApp::get_instance()->saveGame(savefile, "Pre-dumpMap save");

	// Increase number of available object IDs.
	ObjectManager::get_instance()->allow64kObjects();

	// Actual size 
	sint32 awidth = 8192;
	sint32 aheight = 8192;

	sint32 xpos = 0;
	sint32 ypos = 0;

	sint32 left = 16384;
	sint32 right = -16384;
	sint32 top = 16384;
	sint32 bot = -16384;

	sint32 camheight = 256;

	// Work out the map limit we do this very coarsly
	// Now render the map
	for (sint32 y = 0; y < 64; y++)
	{
		for (sint32 x = 0; x < 64; x++)
		{
			const std::list<Item *> *list =
				World::get_instance()->getCurrentMap()->getItemList(x,y);

			// Should iterate the items!
			// (items could extend outside of this chunk and they have height)
			if (list && list->size() != 0) 
			{
				sint32 l = (x*512 - y*512)/4 - 128;
				sint32 r = (x*512 - y*512)/4 + 128;
				sint32 t = (x*512 + y*512)/8 - 256;
				sint32 b = (x*512 + y*512)/8;

				t -= 256; // approx. adjustment for height of items in chunk

				if (l < left) left = l;
				if (r > right) right = r;
				if (t < top) top = t;
				if (b > bot) bot = b;
			}
		}
	}

	if (right == -16384) return;

	// camera height
	bot += camheight;
	top += camheight;

	awidth = right-left;
	aheight = bot-top;

	ypos = top;
	xpos = left;

	// Buffer Size
	sint32 bwidth = awidth;
	sint32 bheight = 256;

	// Tile size
	sint32 twidth = bwidth/8;
	sint32 theight = bheight;


	GameMapGump* g = new GameMapGump(0, 0, twidth, theight);

	// HACK: Setting both INVISIBLE and TRANSPARENT flags on the Avatar
	// will make him completely invisible.
	getMainActor()->setFlag(Item::FLG_INVISIBLE);
	getMainActor()->setExtFlag(Item::EXT_TRANSPARENT);
	World::get_instance()->getCurrentMap()->setWholeMapFast();

	RenderSurface* s = RenderSurface::CreateSecondaryRenderSurface(bwidth,
																   bheight);
	Texture* t = s->GetSurfaceAsTexture();
	// clear buffer
	std::memset(t->buffer, 0, 4*bwidth*bheight);


	// Write tga header
	std::string filename = "@home/mapdump";
	char buf[32];
	sprintf(buf, "%02d",  World::get_instance()->getCurrentMap()->getNum());
	filename += buf;
	filename += ".png";
	ODataSource *ds = FileSystem::get_instance()->WriteFile(filename);
	std::string pngcomment = "Map ";
	pngcomment += buf;
	pngcomment += ", dumped by Pentagram.";

	PNGWriter* pngw = new PNGWriter(ds);
	pngw->init(awidth, aheight, pngcomment);

	// Now render the map
	for (sint32 y = 0; y < aheight; y+=theight)
	{
		for (sint32 x = 0; x < awidth; x+=twidth)
		{
			// Work out 'effective' and world coords
			sint32 ex = xpos+x+twidth/2;
			sint32 ey = ypos+y+theight/2;
			sint32 wx = ex*2 + ey*4;
			sint32 wy = ey*4 - ex*2;

			s->SetOrigin(x,y%bheight);
			CameraProcess::SetCameraProcess(
				new CameraProcess(wx+4*camheight, wy+4*camheight, camheight));
			g->Paint(s, 256, false);

		}

		// Write out the current buffer
		if (((y+theight)%bheight) == 0) {
			for (int i = 0; i < bwidth*bheight; ++i) {
				// Convert to correct pixel format
				uint8 r, g, b;
				UNPACK_RGB8(t->buffer[i],r,g,b);
				uint8 *buf = reinterpret_cast<uint8*>(&t->buffer[i]);
				buf[0] = b; buf[1] = g; buf[2] = r; buf[3] = 0xFF;
			}

			pngw->writeRows(bheight, t);

			// clear buffer for next set
			std::memset(t->buffer, 0, 4*bwidth*bheight);
		}
	}

	pngw->finish();
	delete pngw;

	delete ds;

	delete g;
	delete s;

	// Reload
	GUIApp::get_instance()->loadGame(savefile);

	pout << "Map stored in " << filename << "." << std::endl;
}
// todo: move this code to C# side.
// Renders world axis at the bottom-left corner.
static void RenderWorldAxis()
{
    RenderContext* rc = RenderContext::Inst();
    RenderSurface* surface = s_engineData->pRenderSurface;
    LineRenderer *lr = LineRenderer::Inst();
    Camera& cam = rc->Cam();    
    float margin = 36; // margin in pixels
    float xl = 28; // axis length in pixels.
    float vw = (float)surface->GetWidth();
    float vh = (float)surface->GetHeight();
    Matrix view = cam.View();    
    view.M41 = -vw/2 + margin;
    view.M42 = -vh/2 + margin;
    view.M43 = -xl;
    
    float3 look = cam.CamLook();    
    bool perspective = !cam.IsOrtho();

    // for orthographic hide one of the axis depending on view-type
    const float epsilon  = 0.001f; // use relatively large number for this test.
    bool renderX = perspective || abs(look.x) < epsilon;
    bool renderY = perspective || abs(look.y) < epsilon;
    bool renderZ = perspective || abs(look.z) < epsilon;
    
    Matrix proj = Matrix::CreateOrthographic(vw,vh,1,10000);
    cam.SetViewProj(view,proj);

    float3 centerV(0,0,0);
    // draw x,y,z
    if(renderX)
        lr->DrawLine(centerV,float3(xl,0,0),float4(1,0,0,1));    
    if(renderY)
        lr->DrawLine(centerV,float3(0,xl,0),float4(0,1,0,1));    
    if(renderZ)
        lr->DrawLine(centerV,float3(0,0,xl),float4(0,0,1,1));       

    lr->RenderAll(rc);

    Font* font = s_engineData->AxisFont;
    if(font)
    {   
        float fh = font->GetFontSize();
        float fhh = fh /2.0f;
        FontRenderer* fr = LvEdFonts::FontRenderer::Inst();
        Matrix vp = view * proj;
                
        // draw x,y,z
        if(renderX)
        {
            float3 xpos = surface->Project(float3(xl,fhh,0),vp);
            fr->DrawText(font,L"X",(int)xpos.x,(int)xpos.y,float4(1,0,0,1));
        }

        if(renderY)
        {
            float3 ypos = surface->Project(float3(0,xl+fhh,0),vp);
            fr->DrawText(font,L"Y",(int)ypos.x,(int)ypos.y,float4(0,1,0,1));
        }

        if(renderZ)
        {
            float3 zpos = surface->Project(float3(0,fhh,xl),vp);
            int ycoord =(int) ((zpos.y + fh) > vh ? vh - fh : zpos.y);
            fr->DrawText(font,L"Z",(int)zpos.x,ycoord,float4(0,0,1,1));
        }
        fr->FlushPrintRequests( rc );
    }    
    
}
LVEDRENDERINGENGINE_API bool __stdcall LvEd_FrustumPick(ObjectGUID renderSurface, float viewxform[], float projxform[],float* rect, HitRecord** hits, int* count)
{
    ErrorHandler::ClearError();
    *hits = 0;
    *count = 0;
    float w = rect[2];
    float h = rect[3];

    if(w == 0 || h == 0)
    {
        return false;
    }


    // init camera.
    Matrix view = viewxform;
    Matrix proj = projxform;
    RenderContext::Inst()->Cam().SetViewProj(view,proj);  
    
    // same code used for rendering.
    s_engineData->pickCollector.ClearLists();
    s_engineData->pickCollector.SetFlags( RenderContext::Inst()->State()->GetGlobalRenderFlags() );

    s_engineData->GameLevel->GetRenderables(&s_engineData->pickCollector, RenderContext::Inst());
   
    RenderSurface* pRenderSurface = reinterpret_cast<RenderSurface*>(renderSurface);

    float3 corners[8];
    float x0 = rect[0];
    float y0 = rect[1];
    float x1 = x0 + w;
    float y1 = y0 + h;       
           
    Matrix viewProj = view * proj;
    Matrix invWVP; // inverse of world view projection matrix.
    s_engineData->HitRecords.clear();
    float3 zeroVector(0,0,0);
    Frustum fr; // frustum in local space.
    for(auto it = s_engineData->pickCollector.GetList().begin(); it != s_engineData->pickCollector.GetList().end(); it++)
    {
        RenderableNode& r = (*it);
        if(r.mesh == NULL) continue;

        invWVP = r.WorldXform * viewProj;
        invWVP.Invert();

        corners[0] = pRenderSurface->Unproject(float3(x0,y1,0),invWVP);
        corners[4] = pRenderSurface->Unproject(float3(x0,y1,1),invWVP);

        corners[1] = pRenderSurface->Unproject(float3(x1,y1,0),invWVP);
        corners[5] = pRenderSurface->Unproject(float3(x1,y1,1),invWVP);

        corners[2] = pRenderSurface->Unproject(float3(x1,y0,0),invWVP);
        corners[6] = pRenderSurface->Unproject(float3(x1,y0,1),invWVP);

        corners[3] = pRenderSurface->Unproject(float3(x0,y0,0),invWVP);
        corners[7] = pRenderSurface->Unproject(float3(x0,y0,1),invWVP);
        fr.InitFromCorners(corners);

        int test = FrustumAABBIntersect(fr,r.mesh->bounds);                
        if(test)
        {
            if(test == 1 
                && r.GetFlag(RenderableNode::kTestAgainstBBoxOnly) == false
                && r.mesh != NULL 
                && r.mesh->primitiveType == PrimitiveType::TriangleList)
            {
                Mesh* mesh = r.mesh;
               
                Triangle tr;                
                bool triHit = FrustumMeshIntersect(fr, 
                     &mesh->pos[0],
                   (uint32_t)mesh->pos.size(),
                   &mesh->indices[0],
                   (uint32_t)mesh->indices.size());
                
                if( triHit == false) continue;               
            }
            
            HitRecord hit;
            hit.objectId = r.objectId;
            hit.index = 0;
            hit.hitPt = zeroVector;
            hit.normal = zeroVector;
            hit.nearestVertex = zeroVector;
            hit.distance = 0;
            hit.hasNormal = false;
            hit.hasNearestVertex = false;
            s_engineData->HitRecords.push_back(hit);
        }
    }

    // return the results to the C#. 
    if(s_engineData->HitRecords.size() > 0)
    {
        *hits = &s_engineData->HitRecords[0];
        *count = (int)s_engineData->HitRecords.size();
    }
    return *count > 0;
}
Beispiel #20
0
bool Pathfinder::pathfind(std::vector<PathfindingAction>& path)
{
#if 0
	pout << "Actor " << actor->getObjId();

	if (targetitem) {
		pout << " pathfinding to item: ";
		targetitem->dumpInfo();
	} else {
		pout << " pathfinding to (" << targetx << "," << targety << "," << targetz << ")" << std::endl;
	}
#endif

#ifdef DEBUG
	if (actor->getObjId() == visualdebug_actor) {
		RenderSurface* screen = GUIApp::get_instance()->getScreen();
		screen->BeginPainting();
		if (targetitem)
			drawbox(targetitem);
		else
			drawdot(targetx, targety, targetz, 2, 0xFF0000FF);
		screen->EndPainting();
	}
#endif


	path.clear();

	PathNode* startnode = new PathNode();
	startnode->state = start;
	startnode->cost = 0;
	startnode->parent = 0;
	startnode->depth = 0;
	startnode->stepsfromparent = 0;
	nodelist.push_back(startnode);
	nodes.push(startnode);

	unsigned int expandednodes = 0;
	const unsigned int NODELIMIT_MIN = 30;	//! constant
	const unsigned int NODELIMIT_MAX = 200;	//! constant
	bool found = false;
	Uint32 starttime = SDL_GetTicks();

	while (expandednodes < NODELIMIT_MAX && !nodes.empty() && !found) {
		PathNode* node = nodes.top(); nodes.pop();

#if 0
		pout << "Trying node: (" << node->state.x << "," << node->state.y
			 << "," << node->state.z << ") target=(" << targetx << ","
			 << targety << "," << targetz << ")" << std::endl;
#endif

		if (checkTarget(node)) {
			// done!

			// find path length
			PathNode* n = node;
			unsigned int length = 0;
			while (n->parent) {
				n = n->parent;
				length++;
			}
#if 0
			pout << "Pathfinder: path found (length = " << length << ")"
				 << std::endl;
#endif

			unsigned int i = length;
			if (length > 0) length++; // add space for final 'stand' action
			path.resize(length);

			// now backtrack through the nodes to assemble the final animation
			while (node->parent) {
				PathfindingAction action;
				action.action = node->state.lastanim;
				action.direction = node->state.direction;
				action.steps = node->stepsfromparent;
				path[--i] = action;
#if 0
				pout << "anim = " << node->state.lastanim << ", dir = "
					 << node->state.direction << ", steps = "
					 << node->stepsfromparent << std::endl;
#endif

				//TODO: check how turns work
				//TODO: append final 'stand' animation

				node = node->parent;
			}

			if (length) {
				if (node->state.combat)
					path[length-1].action = Animation::combatStand;
				else
					path[length-1].action = Animation::stand;
				path[length-1].direction = path[length-2].direction;
			}

			expandtime = SDL_GetTicks() - starttime;
			return true;
		}

		expandNode(node);
		expandednodes++;

		if(expandednodes >= NODELIMIT_MIN && ((expandednodes) % 5) == 0)
		{
			Uint32 elapsed_ms = SDL_GetTicks() - starttime;
			if(elapsed_ms > 350) break;
		}
	}

	expandtime = SDL_GetTicks() - starttime;

#if 0
	static sint32 pfcalls = 0;
	static sint32 pftotaltime = 0;
	pfcalls++;
	pftotaltime += expandtime;
	pout << "maxout average = " << (pftotaltime / pfcalls) << "ms." << std::endl;
#endif

	return false;
}