Ejemplo n.º 1
0
        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed)
            {
#if DIRECTX
                if (disposing)
                {
                    if (_resourceView != null)
                    {
                        _resourceView.Dispose();
                        _resourceView = null;
                    }

                    if (_texture != null)
                    {
                        _texture.Dispose();
                        _texture = null;
                    }
                }
#elif OPENGL
                GraphicsDevice.AddDisposeAction(() =>
                {
                    GL.DeleteTextures(1, ref glTexture);
                    GraphicsExtensions.CheckGLError();
                    glTexture = -1;
                });

                glLastSamplerState = null;
#endif
            }
            base.Dispose(disposing);
        }
Ejemplo n.º 2
0
        public Resource Load(ResourceInformation info)
        {
            if (info.GetBool("IsCubemap"))
            {
                return(LoadCubemap(info));
            }

            SharpDX.Toolkit.Graphics.Texture2D    texture = SharpDX.Toolkit.Graphics.Texture2D.Load(device, info.Filepath);
            SharpDX.Direct3D11.ShaderResourceView textureView;
            bool isLinearData = info.GetBool("IsLinear");

            if (isLinearData)
            {
                textureView = new SharpDX.Direct3D11.ShaderResourceView(device, texture);
            }
            else
            {
                SharpDX.Direct3D11.ImageLoadInformation imageInfo = new SharpDX.Direct3D11.ImageLoadInformation();

                imageInfo.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource;
                imageInfo.Format    = SharpDX.DXGI.Format.R8G8B8A8_UNorm_SRgb;
                imageInfo.Filter    = SharpDX.Direct3D11.FilterFlags.SRgb | SharpDX.Direct3D11.FilterFlags.None;

                SharpDX.Direct3D11.Resource sRGBTexture = SharpDX.Direct3D11.Texture2D.FromFile(device, info.Filepath, imageInfo);
                textureView = new SharpDX.Direct3D11.ShaderResourceView(device, sRGBTexture);
            }

            Texture fearTexture = new Texture(texture, textureView);

            return(fearTexture);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Maps the data contained in a subresource to a memory pointer, and denies the GPU access to that subresource.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="subresource">The subresource.</param>
        /// <param name="mode">The mode.</param>
        /// <param name="flags">The flags.</param>
        /// <param name="stream">The output stream containing the pointer.</param>
        /// <returns>The locked <see cref="SharpDX.DataBox"/></returns>
        /// <unmanaged>HRESULT ID3D11DeviceContext::Map([In] ID3D11Resource* pResource,[In] unsigned int Subresource,[In] D3D11_MAP MapType,[In] D3D11_MAP_FLAG MapFlags,[Out] D3D11_MAPPED_SUBRESOURCE* pMappedResource)</unmanaged>
        public SharpDX.DataBox MapSubresource(SharpDX.Direct3D11.Resource resource, int subresource, SharpDX.Direct3D11.MapMode mode, SharpDX.Direct3D11.MapFlags flags, out DataStream stream)
        {
            int mipLevels;

            switch (resource.Dimension)
            {
            case ResourceDimension.Buffer:
                return(MapSubresource((Buffer)resource, mode, flags, out stream));

            case ResourceDimension.Texture1D:
                var texture1D = (Texture1D)resource;
                mipLevels = texture1D.Description.MipLevels;
                return(MapSubresource(texture1D, subresource % mipLevels, subresource / mipLevels, mode, flags, out stream));

            case ResourceDimension.Texture2D:
                var texture2D = (Texture2D)resource;
                mipLevels = texture2D.Description.MipLevels;
                return(MapSubresource(texture2D, subresource % mipLevels, subresource / mipLevels, mode, flags, out stream));

            case ResourceDimension.Texture3D:
                var texture3D = (Texture3D)resource;
                mipLevels = texture3D.Description.MipLevels;
                return(MapSubresource(texture3D, subresource % mipLevels, subresource / mipLevels, mode, flags, out stream));

            default:
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "MapSubresource is not supported for Resource [{0}]", resource.Dimension));
            }
        }
Ejemplo n.º 4
0
        internal SharpDX.Direct3D11.Resource GetTexture()
        {
            if (_texture == null)
                _texture = CreateTexture();

            return _texture;
        }
Ejemplo n.º 5
0
        internal SharpDX.Direct3D11.Resource GetTexture()
        {
            if (_texture == null)
            {
                _texture = CreateTexture();
            }

            return(_texture);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// <p>Gets a reference to the data contained in a subresource, and denies the GPU access to that subresource.</p>
        /// </summary>
        /// <param name="resourceRef"><dd>  <p>A reference to a <strong><see cref="SharpDX.Direct3D11.Resource"/></strong> interface.</p> </dd></param>
        /// <param name="subresource"><dd>  <p>Index number of the subresource.</p> </dd></param>
        /// <param name="mapType"><dd>  <p>Specifies the CPU's read and write permissions for a resource. For possible values, see <strong><see cref="SharpDX.Direct3D11.MapMode"/></strong>.</p> </dd></param>
        /// <param name="mapFlags"><dd>  <p> <strong>Flag</strong> that specifies what the CPU should do when the GPU is busy. This flag is optional.</p> </dd></param>
        /// <param name="mappedResourceRef"><dd>  <p>A reference to the mapped subresource (see <strong><see cref="SharpDX.DataBox"/></strong>).</p> </dd></param>
        /// <returns>The mapped subresource (see <strong><see cref="SharpDX.DataBox"/></strong>). If <see cref="MapFlags.DoNotWait"/> is used and the resource is still being used by the GPU, this method return an empty DataBox whose property <see cref="DataBox.IsEmpty"/> returns <c>true</c>.<p>This method also throws an exception with the code <strong><see cref="SharpDX.DXGI.ResultCode.DeviceRemoved"/></strong> if <em>MapType</em> allows any CPU read access and the video card has been removed.</p><p>For more information about these error codes, see DXGI_ERROR.</p></returns>
        /// <remarks>
        /// <p>If you call <strong>Map</strong> on a deferred context, you can only pass <strong><see cref="SharpDX.Direct3D11.MapMode.WriteDiscard"/></strong>, <strong><see cref="SharpDX.Direct3D11.MapMode.WriteNoOverwrite"/></strong>, or both to the <em>MapType</em> parameter. Other <strong><see cref="SharpDX.Direct3D11.MapMode"/></strong>-typed values are not supported for a deferred context.</p><p>The Direct3D 11.1 runtime, which is available starting with Windows Developer Preview, can  map shader resource views (SRVs) of dynamic buffers with <strong><see cref="SharpDX.Direct3D11.MapMode.WriteNoOverwrite"/></strong>.  The Direct3D 11 and earlier runtimes limited mapping to vertex or index buffers.</p>
        /// If <see cref="MapFlags.DoNotWait"/> is used and the resource is still being used by the GPU, this method return an empty DataBox whose property <see cref="DataBox.IsEmpty"/> returns <c>true</c>.
        /// </remarks>
        /// <msdn-id>ff476457</msdn-id>
        /// <unmanaged>HRESULT ID3D11DeviceContext::Map([In] ID3D11Resource* pResource,[In] unsigned int Subresource,[In] D3D11_MAP MapType,[In] D3D11_MAP_FLAG MapFlags,[Out] D3D11_MAPPED_SUBRESOURCE* pMappedResource)</unmanaged>
        /// <unmanaged-short>ID3D11DeviceContext::Map</unmanaged-short>
        public SharpDX.DataBox MapSubresource(SharpDX.Direct3D11.Resource resourceRef, int subresource, SharpDX.Direct3D11.MapMode mapType, SharpDX.Direct3D11.MapFlags mapFlags)
        {
            var box    = default(DataBox);
            var result = MapSubresource(resourceRef, subresource, mapType, mapFlags, out box);

            if ((mapFlags & MapFlags.DoNotWait) != 0 && result == DXGI.ResultCode.WasStillDrawing)
            {
                return(box);
            }
            result.CheckError();
            return(box);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Updates the subresource safe method.
        /// </summary>
        /// <param name="dstResourceRef">The DST resource ref.</param>
        /// <param name="dstSubresource">The DST subresource.</param>
        /// <param name="dstBoxRef">The DST box ref.</param>
        /// <param name="pSrcData">The p SRC data.</param>
        /// <param name="srcRowPitch">The SRC row pitch.</param>
        /// <param name="srcDepthPitch">The SRC depth pitch.</param>
        /// <param name="srcBytesPerElement">The size in bytes per pixel/block element.</param>
        /// <param name="isCompressedResource">if set to <c>true</c> the resource is a block/compressed resource</param>
        /// <returns></returns>
        /// <remarks>
        /// This method is implementing the <a href="http://blogs.msdn.com/b/chuckw/archive/2010/07/28/known-issue-direct3d-11-updatesubresource-and-deferred-contexts.aspx">workaround for deferred context</a>.
        /// </remarks>
        internal unsafe bool UpdateSubresourceSafe(SharpDX.Direct3D11.Resource dstResourceRef, int dstSubresource, SharpDX.Direct3D11.ResourceRegion?dstBoxRef, System.IntPtr pSrcData, int srcRowPitch, int srcDepthPitch, int srcBytesPerElement, bool isCompressedResource)
        {
            bool needWorkaround = false;

            // Check thread support just once as it won't change during the life of this instance.
            if (!isCheckThreadingSupport)
            {
                bool supportsConcurrentResources;
                Device.CheckThreadingSupport(out supportsConcurrentResources, out supportsCommandLists);
                isCheckThreadingSupport = true;
            }

            if (dstBoxRef.HasValue)
            {
                if (TypeInfo == DeviceContextType.Deferred)
                {
                    // If this deferred context doesn't support command list, we need to perform the workaround
                    needWorkaround = !supportsCommandLists;
                }
            }

            // Adjust the pSrcData pointer if needed
            IntPtr pAdjustedSrcData = pSrcData;

            if (needWorkaround)
            {
                var alignedBox = dstBoxRef.Value;

                // convert from pixels to blocks
                if (isCompressedResource)
                {
                    alignedBox.Left   /= 4;
                    alignedBox.Right  /= 4;
                    alignedBox.Top    /= 4;
                    alignedBox.Bottom /= 4;
                }

                pAdjustedSrcData = (IntPtr)(((byte *)pSrcData) - (alignedBox.Front * srcDepthPitch) - (alignedBox.Top * srcRowPitch) - (alignedBox.Left * srcBytesPerElement));
            }

            UpdateSubresource(dstResourceRef, dstSubresource, dstBoxRef, pAdjustedSrcData, srcRowPitch, srcDepthPitch);

            return(needWorkaround);
        }
Ejemplo n.º 8
0
        public override void Dispose()
        {
#if DIRECTX
            if (_resourceView != null)
            {
                _resourceView.Dispose();
                _resourceView = null;
            }

            if (_texture != null)
            {
                _texture.Dispose();
                _texture = null;
            }
#elif OPENGL
            GL.DeleteTextures(1, ref glTexture);
            GraphicsExtensions.CheckGLError();
#endif
            base.Dispose();
        }
Ejemplo n.º 9
0
        public BackBuffer(Dx10Device device10, Dx11ChainedDevice device11)
        {
            try
            {
                _device10 = device10;
                _device11 = device11;

                _backBuffer = Resource.FromSwapChain <Texture2D>(device11.SwapChain, 0);
                _renderView = new RenderTargetView(device11.Device, _backBuffer);

                Texture2DDescription descriptor = _backBuffer.Description;
                {
                    descriptor.MipLevels         = 1;
                    descriptor.ArraySize         = 1;
                    descriptor.Format            = Format.B8G8R8A8_UNorm;
                    descriptor.SampleDescription = new SampleDescription(1, 0);
                    descriptor.Usage             = SharpDX.Direct3D11.ResourceUsage.Default;
                    descriptor.BindFlags         = SharpDX.Direct3D11.BindFlags.RenderTarget | SharpDX.Direct3D11.BindFlags.ShaderResource;
                    descriptor.CpuAccessFlags    = SharpDX.Direct3D11.CpuAccessFlags.None;
                    descriptor.OptionFlags       = SharpDX.Direct3D11.ResourceOptionFlags.SharedKeyedmutex;
                };

                _textureD3D11 = new Texture2D(device11.Device, descriptor);

                _factory2D = new Factory(FactoryType.MultiThreaded);

                using (SharpDX.DXGI.Resource sharedResource = _textureD3D11.QueryInterface <SharpDX.DXGI.Resource>())
                    using (SharpDX.Direct3D10.Texture2D backBuffer10 = device10.Device.OpenSharedResource <SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle))
                    {
                        _surface        = backBuffer10.QueryInterface <Surface>();
                        _renderTarget2D = new RenderTarget(_factory2D, _surface, GetRenderTargetProperties());
                    }
            }
            catch
            {
                Dispose();
                throw;
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Copy a multisampled resource into a non-multisampled resource.
 /// </summary>
 /// <remarks>
 /// This API is most useful when re-using the resulting render target of one render pass as an input to a second render pass. The source and destination resources must be the same resource type and have the same dimensions. In addition, they must have compatible formats. There are three scenarios for this:  ScenarioRequirements Source and destination are prestructured and typedBoth the source and destination must have identical formats and that format must be specified in the Format parameter. One resource is prestructured and typed and the other is prestructured and typelessThe typed resource must have a format that is compatible with the typeless resource (i.e. the typed resource is DXGI_FORMAT_R32_FLOAT and the typeless resource is DXGI_FORMAT_R32_TYPELESS). The format of the typed resource must be specified in the Format parameter. Source and destination are prestructured and typelessBoth the source and destination must have the same typeless format (i.e. both must have DXGI_FORMAT_R32_TYPELESS), and the Format parameter must specify a format that is compatible with the source and destination (i.e. if both are DXGI_FORMAT_R32_TYPELESS then DXGI_FORMAT_R32_FLOAT could be specified in the Format parameter). For example, given the DXGI_FORMAT_R16G16B16A16_TYPELESS format:  The source (or dest) format could be DXGI_FORMAT_R16G16B16A16_UNORM The dest (or source) format could be DXGI_FORMAT_R16G16B16A16_FLOAT    ?
 /// </remarks>
 /// <param name="source">Source resource. Must be multisampled. </param>
 /// <param name="sourceSubresource">&gt;The source subresource of the source resource. </param>
 /// <param name="destination">Destination resource. Must be a created with the <see cref="SharpDX.Direct3D11.ResourceUsage.Default"/> flag and be single-sampled. See <see cref="SharpDX.Direct3D11.Resource"/>. </param>
 /// <param name="destinationSubresource">A zero-based index, that identifies the destination subresource. Use {{D3D11CalcSubresource}} to calculate the index. </param>
 /// <param name="format">A <see cref="SharpDX.DXGI.Format"/> that indicates how the multisampled resource will be resolved to a single-sampled resource.  See remarks. </param>
 /// <unmanaged>void ID3D11DeviceContext::ResolveSubresource([In] ID3D11Resource* pDstResource,[In] int DstSubresource,[In] ID3D11Resource* pSrcResource,[In] int SrcSubresource,[In] DXGI_FORMAT Format)</unmanaged>
 public void ResolveSubresource(SharpDX.Direct3D11.Resource source, int sourceSubresource, SharpDX.Direct3D11.Resource destination, int destinationSubresource, SharpDX.DXGI.Format format)
 {
     ResolveSubresource_(destination, destinationSubresource, source, sourceSubresource, format);
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Copy a region from a source resource to a destination resource.
 /// </summary>
 /// <remarks>
 /// The source box must be within the size of the source resource. The destination offsets, (x, y, and z) allow the source box to be offset when writing into the destination resource; however, the dimensions of the source box and the offsets must be within the size of the resource. If the resources are buffers, all coordinates are in bytes; if the resources are textures, all coordinates are in texels. {{D3D11CalcSubresource}} is a helper function for calculating subresource indexes. CopySubresourceRegion performs the copy on the GPU (similar to a memcpy by the CPU). As a consequence, the source and destination resources:  Must be different subresources (although they can be from the same resource). Must be the same type. Must have compatible DXGI formats (identical or from the same type group). For example, a DXGI_FORMAT_R32G32B32_FLOAT texture can be copied to an DXGI_FORMAT_R32G32B32_UINT texture since both of these formats are in the DXGI_FORMAT_R32G32B32_TYPELESS group. May not be currently mapped.  CopySubresourceRegion only supports copy; it does not support any stretch, color key, blend, or format conversions. An application that needs to copy an entire resource should use <see cref="SharpDX.Direct3D11.DeviceContext.CopyResource_"/> instead. CopySubresourceRegion is an asynchronous call which may be added to the command-buffer queue, this attempts to remove pipeline stalls that may occur when copying data. See performance considerations for more details. Note??If you use CopySubresourceRegion with a depth-stencil buffer or a multisampled resource, you must copy the whole subresource. In this situation, you must pass 0 to the DstX, DstY, and DstZ parameters and NULL to the pSrcBox parameter. In addition, source and destination resources, which are represented by the pSrcResource and pDstResource parameters, should have identical sample count values. Example The following code snippet copies a box (located at (120,100),(200,220)) from a source texture into a region (10,20),(90,140) in a destination texture.
 /// <code> D3D11_BOX sourceRegion;
 /// sourceRegion.left = 120;
 /// sourceRegion.right = 200;
 /// sourceRegion.top = 100;
 /// sourceRegion.bottom = 220;
 /// sourceRegion.front = 0;
 /// sourceRegion.back = 1; pd3dDeviceContext-&gt;CopySubresourceRegion( pDestTexture, 0, 10, 20, 0, pSourceTexture, 0, &amp;sourceRegion ); </code>
 ///
 ///  Notice, that for a 2D texture, front and back are set to 0 and 1 respectively.
 /// </remarks>
 /// <param name="source">A reference to the source resource (see <see cref="SharpDX.Direct3D11.Resource"/>). </param>
 /// <param name="sourceSubresource">Source subresource index. </param>
 /// <param name="sourceRegion">A reference to a 3D box (see <see cref="SharpDX.Direct3D11.ResourceRegion"/>) that defines the source subresources that can be copied. If NULL, the entire source subresource is copied. The box must fit within the source resource. </param>
 /// <param name="destination">A reference to the destination resource (see <see cref="SharpDX.Direct3D11.Resource"/>). </param>
 /// <param name="destinationSubResource">Destination subresource index. </param>
 /// <param name="dstX">The x-coordinate of the upper left corner of the destination region. </param>
 /// <param name="dstY">The y-coordinate of the upper left corner of the destination region. For a 1D subresource, this must be zero. </param>
 /// <param name="dstZ">The z-coordinate of the upper left corner of the destination region. For a 1D or 2D subresource, this must be zero. </param>
 /// <msdn-id>ff476394</msdn-id>
 /// <unmanaged>void ID3D11DeviceContext::CopySubresourceRegion([In] ID3D11Resource* pDstResource,[In] unsigned int DstSubresource,[In] unsigned int DstX,[In] unsigned int DstY,[In] unsigned int DstZ,[In] ID3D11Resource* pSrcResource,[In] unsigned int SrcSubresource,[In, Optional] const D3D11_BOX* pSrcBox)</unmanaged>
 /// <unmanaged-short>ID3D11DeviceContext::CopySubresourceRegion</unmanaged-short>
 public void CopySubresourceRegion(SharpDX.Direct3D11.Resource source, int sourceSubresource, SharpDX.Direct3D11.ResourceRegion?sourceRegion, SharpDX.Direct3D11.Resource destination, int destinationSubResource, int dstX = 0, int dstY = 0, int dstZ = 0)
 {
     CopySubresourceRegion_(destination, destinationSubResource, dstX, dstY, dstZ, source, sourceSubresource, sourceRegion);
 }
Ejemplo n.º 12
0
        protected override void Dispose(bool disposing)
		{
            if (!IsDisposed)
            {
#if DIRECTX
                if (disposing)
                {
                    if (_resourceView != null)
                    {
                        _resourceView.Dispose();
                        _resourceView = null;
                    }

                    if (_texture != null)
                    {
                        _texture.Dispose();
                        _texture = null;
                    }
                }
#elif OPENGL
                GraphicsDevice.AddDisposeAction(() =>
                    {
                        GL.DeleteTextures(1, ref glTexture);
                        GraphicsExtensions.CheckGLError();
                        glTexture = -1;
                    });

                glLastSamplerState = null;
#endif
            }
            base.Dispose(disposing);
		}
Ejemplo n.º 13
0
        public void Render()
        {
            if (!readyToRender)
            {
                return;
            }


            if (SyncLayerNeeded)
            {
                NetControl.SyncLayersUiThread();
            }

            if (SyncTourNeeded)
            {
                NetControl.SyncTourUiThread();
            }

            if (Tile.fastLoad)
            {
                Tile.fastLoadAutoReset = true;
            }

            if (!TourPlayer.Playing)
            {
                Earth3d.MainWindow.CrossFadeFrame = false;
            }



            Int64 ticks = HiResTimer.TickCount;

            double elapsedSeconds = ((double)(ticks - lastRenderTickCount)) / HiResTimer.Frequency;

            if (!rift)
            {

                if (Properties.Settings.Default.TargetFrameRate != 0 && !(Properties.Settings.Default.FrameSync && Properties.Settings.Default.TargetFrameRate == 60))
                {
                    int frameRate = Properties.Settings.Default.TargetFrameRate;


                    if (elapsedSeconds < (1.0 / (double)frameRate))
                    {
                        return;
                    }
                }
            }

            lastRenderTickCount = ticks;

            lastFrameTime = (Math.Min(.1, elapsedSeconds));

            //Update MetaNow to current realtime for entire frame to render exactly on time
            SpaceTimeController.MetaNow = DateTime.Now;


            LoadTileBudget = 1;

            if (IsPaused() || !Initialized)
            {
                System.Threading.Thread.Sleep(100);
                return;
            }



            if (ProjectorServer)
            {
                UpdateNetworkStatus();
            }


            //oculus rift support
            rift = StereoMode == StereoModes.OculusRift;
            if (rift)
            {
                GetRiftSample();
            }

            if (!megaFrameDump)
            {
                TileCache.PurgeLRU();
            }

            TileCache.DecimateQueue();

            Tile.imageQuality = Properties.Settings.Default.ImageQuality;

            Tile.CurrentRenderGeneration++;
            IconCacheEntry.CurrentFrame = Tile.CurrentRenderGeneration;

            Tile.lastDeepestLevel = Tile.deepestLevel;
            Tile.TilesInView = 0;
            Tile.TrianglesRendered = 0;
            Tile.TilesTouched = 0;


            if (ZoomFactor == 0 || TargetZoom == 0 || double.IsNaN(ZoomFactor) || double.IsNaN(TargetZoom))
            {
                ZoomFactor = TargetZoom = 360;
            }

            if (contextPanel != null)
            {
                contextPanel.QueueProgress = TileCache.QueuePercent;
            }

            TileCache.InitNextWaitingTile();

            // reset dome matrix Cache
            DomeMatrixFresh = false;


            if (mover != null)
            {
                SpaceTimeController.Now = mover.CurrentDateTime;
            }
            else
            {
                SpaceTimeController.UpdateClock();
                LayerManager.UpdateLayerTime();
            }

            if (uiController != null)
            {
                {
                    uiController.PreRender(this);
                }
            }

            if (Space)
            {
                Planets.UpdatePlanetLocations(false);
            }
            else if (CurrentImageSet.DataSetType == ImageSetType.SolarSystem)
            {
                // todo allow update of focus planet
                Planets.UpdatePlanetLocations(true);
                Planets.UpdateOrbits(0);
            }

            UpdateSpaceNavigator();
            UpdateXInputState();
            UpdateNetControlState();
            if (mover != null)
            {
                UpdateMover(mover);
            }
            else
            {
                if (!SandboxMode)
                {
                    if (SolarSystemTrack == SolarSystemObjects.Undefined | (SolarSystemTrack == SolarSystemObjects.Custom && viewCamera.ViewTarget == Vector3d.Empty))
                    {
                        SolarSystemTrack = SolarSystemObjects.Sun;
                    }
                }
            }

            UpdateViewParameters();

            if (SolarSystemMode)
            {
                if (SolarSystemTrack != SolarSystemObjects.Custom)
                {
                    viewCamera.ViewTarget = Planets.GetPlanet3dLocation(SolarSystemTrack);
                }
            }

            ClampZoomValues();

            if (blink)
            {
                TimeSpan ts = DateTime.Now - lastBlink;
                if (ts.TotalMilliseconds > 500)
                {
                    if (StudyOpacity > 0)
                    {
                        StudyOpacity = 0;
                    }
                    else
                    {
                        StudyOpacity = 100;
                    }
                    lastBlink = DateTime.Now;
                }
            }

            LayerManager.PrepTourLayers();

            if (Settings.MasterController)
            {
                SendMove();
            }



            if (contextPanel != null)
            {

                contextPanel.QueueProgress = TileCache.QueuePercent;

                if (Space)
                {
                    contextPanel.ViewLevel = fovAngle;
                    contextPanel.RA = RA;
                    contextPanel.Dec = Dec;

                    if (constellationCheck != null)
                    {
                        constellation = this.constellationCheck.FindConstellationForPoint(RA, Dec);
                        contextPanel.Constellation = Constellations.FullName(Constellation);
                    }
                }
                else if (SolarSystemMode || SandboxMode)
                {
                    if (SandboxMode)
                    {
                        contextPanel.Sandbox = true;
                        contextPanel.Distance = SolarSystemCameraDistance;
                    }
                    else
                    {
                        contextPanel.Sandbox = false;
                        contextPanel.Distance = SolarSystemCameraDistance;
                    }


                    if (!SandboxMode && (viewCamera.Target != SolarSystemObjects.Custom && viewCamera.Target != SolarSystemObjects.Undefined))
                    {
                        Vector3d pnt = Coordinates.GeoTo3dDouble(ViewLat, ViewLong + 90);

                        Matrix3d EarthMat = Planets.EarthMatrixInv;


                        pnt = Vector3d.TransformCoordinate(pnt, EarthMat);
                        pnt.Normalize();


                        Vector2d radec = Coordinates.CartesianToLatLng(pnt);

                        if (viewCamera.Target != SolarSystemObjects.Earth)
                        {
                            if (radec.X < 0)
                            {
                                radec.X += 360;
                            }
                        }

                        contextPanel.RA = radec.X;
                        contextPanel.Dec = radec.Y;
                    }
                    else
                    {
                        contextPanel.RA = ViewLong;
                        contextPanel.Dec = ViewLat;
                    }
                    contextPanel.Constellation = null;
                }
                else if (PlanetLike)
                {
                    contextPanel.Sandbox = false;
                    contextPanel.Distance = SolarSystemCameraDistance / UiTools.KilometersPerAu * 370;
                    contextPanel.RA = ViewLong;
                    contextPanel.Dec = ViewLat;
                    contextPanel.Constellation = null;
                }
                else
                {
                    contextPanel.Sandbox = false;
                    contextPanel.ViewLevel = fovAngle;
                    contextPanel.RA = ViewLong;
                    contextPanel.Dec = ViewLat;
                    contextPanel.Constellation = null;
                }
            }

            //Capture this state once to avoid race condition where its false now, but changes before the frame is done
            bool tilesAllLoaded = TileCache.QueuePercent == 100;

            if (!megaFrameDump)
            {
               

                if (StereoMode != StereoModes.Off && (!Space || rift))
                {
                    RenderContext11.ViewPort = new SharpDX.ViewportF(0, 0, ViewWidth, ViewHeight, 0.0f, 1.0f);

                    // Ensure that the dome depth/stencil buffer matches our requirements
                    if (domeZbuffer != null)
                    {
                        if (domeZbuffer.Width != ViewWidth || domeZbuffer.Height != ViewHeight)
                        {
                            domeZbuffer.Dispose();
                            GC.SuppressFinalize(domeZbuffer);
                            domeZbuffer = null;
                        }
                    }

                    if (leftEye != null)
                    {
                        if (leftEye.RenderTexture.Height != ViewHeight || leftEye.RenderTexture.Width != ViewWidth)
                        {
                            leftEye.Dispose();
                            GC.SuppressFinalize(leftEye);
                            leftEye = null;
                        }
                    }

                    if (rightEye != null)
                    {
                        if (rightEye.RenderTexture.Height != ViewHeight || rightEye.RenderTexture.Width != ViewWidth)
                        {
                            rightEye.Dispose();
                            GC.SuppressFinalize(rightEye);
                            rightEye = null;
                        }
                    }

                    if (stereoRenderTextureLeft != null)
                    {
                        if (stereoRenderTextureLeft.RenderTexture.Height != ViewHeight || stereoRenderTextureLeft.RenderTexture.Width != ViewWidth)
                        {
                            stereoRenderTextureLeft.Dispose();
                            GC.SuppressFinalize(stereoRenderTextureLeft);
                            stereoRenderTextureLeft = null;

                            stereoRenderTextureRight.Dispose();
                            GC.SuppressFinalize(stereoRenderTextureRight);
                            stereoRenderTextureRight = null;
                        }
                    }


                    if (leftEye == null)
                    {
                        leftEye = new RenderTargetTexture(ViewWidth, ViewHeight, 1);
                    }

                    if (rightEye == null)
                    {
                        rightEye = new RenderTargetTexture(ViewWidth, ViewHeight, 1);
                    }

                    if (RenderContext11.MultiSampleCount > 1)
                    {
                        if (rift)
                        {
                            // When multisample anti-aliasing is enabled, render to an offscreen buffer and then
                            // resolve to the left and then the right eye textures. 
                            if (stereoRenderTextureLeft == null)
                            {
                                stereoRenderTextureLeft = new RenderTargetTexture(leftEyeWidth, leftEyeHeight, riftFormat);
                            }

                            if (stereoRenderTextureRight == null)
                            {
                                stereoRenderTextureRight = new RenderTargetTexture(leftEyeWidth, leftEyeHeight, riftFormat);
                            }

                            if (leftDepthBuffer == null)
                            {
                                leftDepthBuffer = new DepthBuffer(ViewWidth, ViewHeight);
                            }

                            if (rightDepthBuffer == null)
                            {
                                rightDepthBuffer = new DepthBuffer(ViewWidth, ViewHeight);
                            }

                            int eye = 0;
                            var swapTexture = eyeTexture[(int)eye];
                            swapTexture.AdvanceToNextView();

                            RenderFrame(stereoRenderTextureLeft.renderView, leftDepthBuffer.DepthView, RenderTypes.LeftEye, ViewWidth, ViewHeight);


                            SharpDX.Direct3D11.Resource dest = new SharpDX.Direct3D11.Resource(swapTextures[eye].Textures[swapTexture.CurrentIndex].Texture);
                            RenderContext11.PrepDevice.ImmediateContext.ResolveSubresource(stereoRenderTextureLeft.RenderTexture.Texture, 0,
                                                                                            dest, 0,
                                                                                           riftFormat);

                            eye = 1;
                            swapTexture = eyeTexture[(int)eye];
                            swapTexture.AdvanceToNextView();

                            if (Properties.Settings.Default.RiftMonoMode)
                            {
                                // Resolve a single buffer for each eye, cuts rendering cost in half

                                dest = new SharpDX.Direct3D11.Resource(swapTextures[eye].Textures[swapTexture.CurrentIndex].Texture);

                                RenderContext11.PrepDevice.ImmediateContext.ResolveSubresource(stereoRenderTextureLeft.RenderTexture.Texture, 0,
                                                                                               dest, 0,
                                                                                               riftFormat);
                            }
                            else
                            {
                                RenderFrame(stereoRenderTextureRight.renderView, rightDepthBuffer.DepthView, RenderTypes.RightEye, ViewWidth, ViewHeight);

                                dest = new SharpDX.Direct3D11.Resource(swapTextures[eye].Textures[swapTexture.CurrentIndex].Texture);
                                RenderContext11.PrepDevice.ImmediateContext.ResolveSubresource(stereoRenderTextureRight.RenderTexture.Texture, 0,
                                                                                               dest, 0,
                                                                                               riftFormat);
                            }
                        }
                        else
                        {
                            // When multisample anti-aliasing is enabled, render to an offscreen buffer and then
                            // resolve to the left and then the right eye textures. 
                            if (stereoRenderTextureLeft == null)
                            {
                                stereoRenderTextureLeft = new RenderTargetTexture(leftEyeWidth, leftEyeHeight);
                            }

                            if (stereoRenderTextureRight == null)
                            {
                                stereoRenderTextureRight = new RenderTargetTexture(leftEyeWidth, leftEyeHeight);
                            }

                            RenderFrame(stereoRenderTextureLeft.renderView, domeZbuffer.DepthView, RenderTypes.LeftEye, ViewWidth, ViewHeight);

                            RenderContext11.PrepDevice.ImmediateContext.ResolveSubresource(stereoRenderTextureLeft.RenderTexture.Texture, 0,
                                                                                           leftEye.RenderTexture.Texture, 0,
                                                                                           RenderContext11.DefaultColorFormat);

                            RenderFrame(stereoRenderTextureRight.renderView, domeZbuffer.DepthView, RenderTypes.RightEye, ViewWidth, ViewHeight);

                            RenderContext11.PrepDevice.ImmediateContext.ResolveSubresource(stereoRenderTextureRight.RenderTexture.Texture, 0,
                                                                                           rightEye.RenderTexture.Texture, 0,
                                                                                           RenderContext11.DefaultColorFormat);

                        }
                    }
                    else
                    {
                        if (rift)
                        {
                            int eye = 0;
                            var swapTexture = eyeTexture[(int)eye];
                            swapTexture.AdvanceToNextView();

                            RenderFrame(swapTexture.CurrentView, swapTexture.DepthStencilView, RenderTypes.LeftEye, leftEyeWidth, leftEyeHeight);

                            eye = 1;
                            swapTexture = eyeTexture[(int)eye];
                            swapTexture.AdvanceToNextView();

                            RenderFrame(swapTexture.CurrentView, swapTexture.DepthStencilView, RenderTypes.RightEye, rightEyeWidth, rightEyeHeight);
                        }
                        else
                        {
                            // When anti-aliasing is not enabled, render directly to the left and right eye textures.
                            RenderFrame(leftEye.renderView, domeZbuffer.DepthView, RenderTypes.LeftEye, ViewWidth, ViewHeight);
                            RenderFrame(rightEye.renderView, domeZbuffer.DepthView, RenderTypes.RightEye, ViewWidth, ViewHeight);
                        }
                    }

                    if (StereoMode == StereoModes.InterlineEven || StereoMode == StereoModes.InterlineOdd)
                    {
                        RenderSteroPairInterline(leftEye, rightEye);
                    }
                    else if (StereoMode == StereoModes.AnaglyphMagentaGreen || StereoMode == StereoModes.AnaglyphRedCyan || StereoMode == StereoModes.AnaglyphYellowBlue)
                    {
                        RenderSteroPairAnaglyph(leftEye, rightEye);
                    }
                    else if (StereoMode == StereoModes.OculusRift)
                    {
                        hmd.SubmitFrame(riftFrameIndex, ref layerEyeFov.Header);
                        riftFrameIndex++;

                        RenderTextureToScreen(mirror.ResourceView, mirrorTexture.Description.Width, mirrorTexture.Description.Height);

                    }
                    else
                    {
                        if (StereoMode == StereoModes.CrossEyed)
                        {

                            RenderSteroPairSideBySide(rightEye, leftEye);
                        }
                        else
                        {
                            RenderSteroPairSideBySide(leftEye, rightEye);
                        }
                    }
                }
                else if (Settings.DomeView)
                {
                    int cubeFaceSize = 512;
                    if (usingLargeTextures)
                    {
                        cubeFaceSize = 1024;
                    }

                    if (CaptureVideo && dumpFrameParams.Dome)
                    {
                        cubeFaceSize = 2048;
                    }



                    if (usingLargeTextures != Properties.Settings.Default.LargeDomeTextures)
                    {
                        refreshDomeTextures = true;
                    }

                    if (currentCubeFaceSize != cubeFaceSize)
                    {
                        refreshDomeTextures = true;
                    }

                    if (refreshDomeTextures)
                    {
                        usingLargeTextures = Properties.Settings.Default.LargeDomeTextures;
                        for (int face = 0; face < 5; face++)
                        {
                            if (domeCube[face] != null)
                            {
                                domeCube[face].Dispose();
                                GC.SuppressFinalize(domeCube[face]);
                                domeCube[face] = null;
                            }
                        }
                        if (domeZbuffer != null)
                        {
                            domeZbuffer.Dispose();
                            GC.SuppressFinalize(domeZbuffer);
                            domeZbuffer = null;
                        }
                        if (domeCubeFaceMultisampled != null)
                        {
                            domeCubeFaceMultisampled.Dispose();
                            GC.SuppressFinalize(domeCubeFaceMultisampled);
                            domeCubeFaceMultisampled = null;
                        }
                    }


                    // Ensure that the dome depth/stencil buffer matches our requirements
                    if (domeZbuffer != null)
                    {
                        if (domeZbuffer.Width != cubeFaceSize || domeZbuffer.Height != cubeFaceSize)
                        {
                            domeZbuffer.Dispose();
                            GC.SuppressFinalize(domeZbuffer);
                            domeZbuffer = null;
                        }
                    }

                    if (domeZbuffer == null)
                    {
                        domeZbuffer = new DepthBuffer(cubeFaceSize, cubeFaceSize);
                    }

                    if (domeCubeFaceMultisampled == null && RenderContext11.MultiSampleCount > 1)
                    {
                        domeCubeFaceMultisampled = new RenderTargetTexture(cubeFaceSize, cubeFaceSize);
                    }

                    for (int face = 0; face < 5; face++)
                    {
                        if (domeCube[face] == null)
                        {
                            domeCube[face] = new RenderTargetTexture(cubeFaceSize, cubeFaceSize, 1);
                            currentCubeFaceSize = cubeFaceSize;
                            refreshDomeTextures = false;
                        }

                        if (RenderContext11.MultiSampleCount > 1)
                        {
                            // When MSAA is enabled, we render each face to the same multisampled render target,
                            // then resolve to a different texture for each face. This saves memory and works around
                            // the fact that multisample textures are not permitted to have mipmaps.
                            RenderFrame(domeCubeFaceMultisampled.renderView, domeZbuffer.DepthView, (RenderTypes)face, cubeFaceSize, cubeFaceSize);
                            RenderContext11.PrepDevice.ImmediateContext.ResolveSubresource(domeCubeFaceMultisampled.RenderTexture.Texture, 0,
                                                                                           domeCube[face].RenderTexture.Texture, 0,
                                                                                           RenderContext11.DefaultColorFormat);
                        }
                        else
                        {
                            RenderFrame(domeCube[face].renderView, domeZbuffer.DepthView, (RenderTypes)face, cubeFaceSize, cubeFaceSize);
                        }
                        RenderContext11.PrepDevice.ImmediateContext.GenerateMips(domeCube[face].RenderTexture.ResourceView);
                    }

                    if (Properties.Settings.Default.DomeTypeIndex > 0)
                    {
                        RenderWarpedFisheye();
                    }
                    else
                    {
                        if (CaptureVideo && dumpFrameParams.Dome)
                        {
                            if (!dumpFrameParams.WaitDownload || tilesAllLoaded)
                            {
                                RenderDomeMaster();
                            }
                        }
                        RenderFisheye(false);
                    }

                }
                else if (config.UseDistrotionAndBlend)
                {
                    if (undistorted == null)
                    {
                        undistorted = new RenderTargetTexture(config.Width, config.Height);
                    }


                    // Ensure that the dome depth/stencil buffer matches our requirements
                    if (domeZbuffer != null)
                    {
                        if (domeZbuffer.Width != config.Width || domeZbuffer.Height != config.Height)
                        {
                            domeZbuffer.Dispose();
                            GC.SuppressFinalize(domeZbuffer);
                            domeZbuffer = null;
                        }
                    }

                    if (domeZbuffer == null)
                    {
                        domeZbuffer = new DepthBuffer(config.Width, config.Height);

                    }


                    // * If there's no multisampling, draw directly into the undistorted texture
                    // * When multisampling is on, draw into an intermediate buffer, then resolve 
                    //   it into the undistorted texture
                    RenderFrame(undistorted.renderView, domeZbuffer.DepthView, RenderTypes.Normal, config.Width, config.Height);

                    RenderDistort();
                }
                else if (Properties.Settings.Default.FlatScreenWarp)
                {
                    if (undistorted == null)
                    {
                        undistorted = new RenderTargetTexture(ViewWidth, renderWindow.ClientRectangle.Height);
                    }

                    if (domeZbuffer != null)
                    {
                        if (domeZbuffer.Width != ViewWidth || domeZbuffer.Height != renderWindow.ClientRectangle.Height)
                        {
                            domeZbuffer.Dispose();
                            GC.SuppressFinalize(domeZbuffer);
                            domeZbuffer = null;
                        }
                    }

                    if (domeZbuffer == null)
                    {
                        domeZbuffer = new DepthBuffer(ViewWidth, renderWindow.ClientRectangle.Height);

                    }


                    RenderFrame(undistorted.renderView, domeZbuffer.DepthView, RenderTypes.Normal, ViewWidth, renderWindow.ClientRectangle.Height);
                    RenderFlatDistort();

                }
                else
                {
                    if (renderWindow.ClientSize.Height != RenderContext11.DisplayViewport.Height ||
                                renderWindow.ClientSize.Width != RenderContext11.DisplayViewport.Width)
                    {
                        RenderContext11.Resize(renderWindow);
                    }
                    RenderFrame(null, null, RenderTypes.Normal, RenderContext11.DisplayViewport.Width, RenderContext11.DisplayViewport.Height);
                }
            }
            UpdateStats();

            lastRender = HiResTimer.TickCount;

            if (CaptureVideo)
            {
                if (!dumpFrameParams.WaitDownload || tilesAllLoaded)
                {
                    if (!dumpFrameParams.Dome)
                    {
                        Int64 ticksa = HiResTimer.TickCount;
                        SaveFrame();
                    }
                    SpaceTimeController.NextFrame();
                }
                if (SpaceTimeController.DoneDumping())
                {
                    SpaceTimeController.CancelFrameDump = false;
                    DomeFrameDumping();
                }
            }

            if (Tile.fastLoadAutoReset)
            {
                Tile.fastLoad = false;
                Tile.fastLoadAutoReset = false;
            }

        }
Ejemplo n.º 14
0
        public Pipeline(int frameCount, System.Drawing.Size size, System.IntPtr windowHandle)
        {
            // Fields
            FrameCount = frameCount;
            Size       = size;

            // Pipeline
            var d3d12Device = new SharpDX.Direct3D12.Device(null, SharpDX.Direct3D.FeatureLevel.Level_12_1);

            var queueDescription     = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct);
            var commandQueue         = d3d12Device.CreateCommandQueue(queueDescription);
            var swapChainDescription = new SharpDX.DXGI.SwapChainDescription()
            {
                BufferCount       = frameCount,
                ModeDescription   = new SharpDX.DXGI.ModeDescription(Size.Width, Size.Height, new SharpDX.DXGI.Rational(60, 1), SharpDX.DXGI.Format.R8G8B8A8_UNorm),
                Usage             = SharpDX.DXGI.Usage.RenderTargetOutput,
                SwapEffect        = SharpDX.DXGI.SwapEffect.FlipDiscard,
                OutputHandle      = windowHandle,
                Flags             = SharpDX.DXGI.SwapChainFlags.None,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
                IsWindowed        = true
            };
            var rtvHeapDescription = new SharpDX.Direct3D12.DescriptorHeapDescription()
            {
                DescriptorCount = frameCount,
                Flags           = SharpDX.Direct3D12.DescriptorHeapFlags.None,
                Type            = SharpDX.Direct3D12.DescriptorHeapType.RenderTargetView
            };
            var renderTargetViewHeap = d3d12Device.CreateDescriptorHeap(rtvHeapDescription);
            var rtvHandle            = renderTargetViewHeap.CPUDescriptorHandleForHeapStart;
            var dxgiFactory          = new SharpDX.DXGI.Factory4();
            var swapChain            = new SharpDX.DXGI.SwapChain(dxgiFactory, commandQueue, swapChainDescription);
            var swapChain3           = swapChain.QueryInterface <SharpDX.DXGI.SwapChain3>();
            var frameIndex           = swapChain3.CurrentBackBufferIndex;
            var renderTargets        = new SharpDX.Direct3D12.Resource[frameCount];
            var commandAllocators    = new SharpDX.Direct3D12.CommandAllocator[frameCount];
            var rtvDescriptorSize    = d3d12Device.GetDescriptorHandleIncrementSize(SharpDX.Direct3D12.DescriptorHeapType.RenderTargetView);

            var d2d1Factory        = new SharpDX.Direct2D1.Factory();
            var d3d11Device        = SharpDX.Direct3D11.Device.CreateFromDirect3D12(d3d12Device, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport, null, null, commandQueue);
            var d3d11On12Device    = d3d11Device.QueryInterface <SharpDX.Direct3D11.Device11On12>();
            var wrappedBackBuffers = new SharpDX.Direct3D11.Resource[frameCount];
            var d2dRenderTargets   = new SharpDX.Direct2D1.RenderTarget[frameCount];

            for (int i = 0; i < frameCount; i++)
            {
                renderTargets[i]     = swapChain3.GetBackBuffer <SharpDX.Direct3D12.Resource>(i);
                commandAllocators[i] = d3d12Device.CreateCommandAllocator(SharpDX.Direct3D12.CommandListType.Direct);
                d3d12Device.CreateRenderTargetView(renderTargets[i], null, rtvHandle);
                rtvHandle += rtvDescriptorSize;

                var format = new SharpDX.Direct3D11.D3D11ResourceFlags()
                {
                    BindFlags      = (int)SharpDX.Direct3D11.BindFlags.RenderTarget,
                    CPUAccessFlags = (int)SharpDX.Direct3D11.CpuAccessFlags.None
                };
                d3d11On12Device.CreateWrappedResource(renderTargets[i], format, (int)SharpDX.Direct3D12.ResourceStates.Present, (int)SharpDX.Direct3D12.ResourceStates.RenderTarget, typeof(SharpDX.Direct3D11.Resource).GUID, out wrappedBackBuffers[i]);
                var surface = wrappedBackBuffers[i].QueryInterface <SharpDX.DXGI.Surface>();
                d2dRenderTargets[i] = new SharpDX.Direct2D1.RenderTarget(d2d1Factory, surface, new SharpDX.Direct2D1.RenderTargetProperties(new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.Unknown, SharpDX.Direct2D1.AlphaMode.Premultiplied)));
            }

            // Assets
            var fenceEvent  = new System.Threading.AutoResetEvent(false);
            var fence       = d3d12Device.CreateFence(0, SharpDX.Direct3D12.FenceFlags.None);
            var fenceValues = new int[frameCount];

            for (int i = 0; i < frameCount; i++)
            {
                fenceValues[i] = 1;
            }

            var commandList = d3d12Device.CreateCommandList(SharpDX.Direct3D12.CommandListType.Direct, commandAllocators[frameIndex], pipelineState);

            commandList.Close();

            D3D12Device          = d3d12Device;
            CommandAllocators    = commandAllocators;
            RenderTargetViewHeap = renderTargetViewHeap;
            RenderTargets        = renderTargets;
            CommandQueue         = commandQueue;
            SwapChain3           = swapChain3;
            Fence              = fence;
            FenceEvent         = fenceEvent;
            D3D11Device        = d3d11Device;
            D3D11On12Device    = d3d11On12Device;
            WrappedBackBuffers = wrappedBackBuffers;
            D2DRenderTargets   = d2dRenderTargets;
            CommandList        = commandList;
            FenceValues        = fenceValues;
            RtvDescriptorSize  = rtvDescriptorSize;
            FrameIndex         = frameIndex;
        }