Example #1
0
        public TileLoader(string filePath, SharpDX.Direct3D11.SubResourceTiling[] tilingInfo, bool border)
        {
            _filePath = filePath;
            _tilingInfo = tilingInfo;
            _border = border;

            var fileInfo = new FileInfo(_filePath);

            // precompute the tile offsets in the file for each cube face
            var numTilesPerFace = (fileInfo.Length / SampleSettings.TileSizeInBytes / 6);
            var tilesForSingleFaceMostDetailedMip = tilingInfo[1].StartTileIndexInOverallResource;
            _subresourcesPerFaceInResource = tilingInfo.Length / 6;

            for (var face = 0; face < 6; face++)
            {
                var tileIndexInFace = 0;
                var tilesInSubresource = tilesForSingleFaceMostDetailedMip;
                _subresourcesPerFaceInFile = 0;
                while (tileIndexInFace < numTilesPerFace)
                {
                    var offset = (face * numTilesPerFace) + tileIndexInFace;
                    _subresourceTileOffsets.Add(offset);
                    tileIndexInFace += tilesInSubresource;
                    tilesInSubresource = Math.Max(1, tilesInSubresource / 4);
                    _subresourcesPerFaceInFile++;
                }
            }
        }
Example #2
0
        public static IFormatInfo FormatInfo(SharpDX.DXGI.Format dxgiFormat)
        {
            int numColors;
            int colorBits;
            FormatElementType colorFormatType;
            int alphaBits;
            FormatElementType alphaFormatType;
            int totalBits;
            ColorAlphaFormatFlags flags;

            Utility.Helpers.FormatHelper.GetExplicitColorAlphaFormatInfo((ExplicitFormat)dxgiFormat,
                out numColors, out colorBits, out colorFormatType, out alphaBits, out alphaFormatType, out totalBits, out flags);

            return new FormatInfo
            {
                ID = (int)dxgiFormat,
                Description = dxgiFormat.ToString(),
                ExplicitFormat = (ExplicitFormat)dxgiFormat,
                NumColors = numColors,
                ColorBits = colorBits,
                ColorFormatType = colorFormatType,
                AlphaBits = alphaBits,
                AlphaFormatType = alphaFormatType,
                TotalBits = totalBits,
                Flags = flags
            };
        }
Example #3
0
        public static void Draw(RenderContext11 renderContext, PositionColoredTextured[] points, int count, Texture11 texture, SharpDX.Direct3D.PrimitiveTopology primitiveType, float opacity = 1.0f)
        {
            if (VertexBuffer == null)
            {
                VertexBuffer = new Buffer(renderContext.Device, System.Runtime.InteropServices.Marshal.SizeOf(points[0]) * 2500, ResourceUsage.Dynamic, BindFlags.VertexBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, System.Runtime.InteropServices.Marshal.SizeOf(points[0]));
                VertexBufferBinding = new VertexBufferBinding(VertexBuffer, System.Runtime.InteropServices.Marshal.SizeOf((points[0])), 0);

            }
            renderContext.devContext.InputAssembler.PrimitiveTopology = primitiveType;
            renderContext.BlendMode = BlendMode.Alpha;
            renderContext.setRasterizerState(TriangleCullMode.Off);
            SharpDX.Matrix mat = (renderContext.World * renderContext.View * renderContext.Projection).Matrix11;
            mat.Transpose();

            WarpOutputShader.MatWVP = mat;
            WarpOutputShader.Use(renderContext.devContext, texture != null, opacity);

            renderContext.SetVertexBuffer(VertexBufferBinding);

            DataBox box = renderContext.devContext.MapSubresource(VertexBuffer, 0, MapMode.WriteDiscard, MapFlags.None);
            Utilities.Write(box.DataPointer, points, 0, count);

            renderContext.devContext.UnmapSubresource(VertexBuffer, 0);
            if (texture != null)
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, texture.ResourceView);
            }
            else
            {
                renderContext.devContext.PixelShader.SetShaderResource(0, null);
            }
            renderContext.devContext.Draw(count, 0);
        }
        internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Line line)
        {
            var rect = line.GetBoundingRect(rootElement).ToSharpDX();
            //var fill = line.Fill.ToSharpDX(renderTarget, rect);
            var stroke = await line.Stroke.ToSharpDX(renderTarget, rect);

            if (stroke == null ||
                line.StrokeThickness <= 0)
            {
                return;
            }

            //var layer = new Layer(renderTarget);
            //var layerParameters = new LayerParameters();
            //layerParameters.ContentBounds = rect;
            //renderTarget.PushLayer(ref layerParameters, layer);

            renderTarget.DrawLine(
                new DrawingPointF(
                    rect.Left + (float)line.X1,
                    rect.Top + (float)line.Y1),
                new DrawingPointF(
                    rect.Left + (float)line.X2,
                    rect.Top + (float)line.Y2),
                    stroke,
                    (float)line.StrokeThickness,
                    line.GetStrokeStyle(compositionEngine.D2DFactory));

            //renderTarget.PopLayer();
        }
Example #5
0
 internal MyBackbuffer(SharpDX.Direct3D11.Resource swapChainBB)
 {
     m_resource = swapChainBB;
     m_resource.DebugName = m_debugName;
     m_rtv = new RenderTargetView(MyRender11.Device, swapChainBB);
     m_rtv.DebugName = m_debugName;
 }
Example #6
0
        public override void GetTexture(SharpDX.Size2F surfaceSize, out DrawingSurfaceSynchronizedTexture synchronizedTexture, out SharpDX.RectangleF textureSubRectangle)
        {
            if (_synchronizedTexture == null)
            {
                _synchronizedTexture = _host.CreateSynchronizedTexture(_controller.GetTexture());
            }
            
            // Set output parameters.
            _textureSubRectangle.Left = 0.0f;
            _textureSubRectangle.Top = 0.0f;
            _textureSubRectangle.Right = surfaceSize.Width;
            _textureSubRectangle.Bottom = surfaceSize.Height;


            //HOW DO YOU DO A Microsoft::WRL::ComPtr<T>   CopyTo ?????
            //m_synchronizedTexture.CopyTo(synchronizedTexture);
            synchronizedTexture = _synchronizedTexture;

            textureSubRectangle = _textureSubRectangle;     

            //something is going wrong here as the second time thru the BeginDraw consumes 
            //the call and controlnever returns back to this method, thus GetTexture 
            //(the call after begindraw) never fires again... ??????
            synchronizedTexture.BeginDraw();

            _controller.GetTexture(surfaceSize, synchronizedTexture, textureSubRectangle);

            synchronizedTexture.EndDraw();
        }
Example #7
0
        /// <summary>
        /// Initializes a new instance of <see cref="VertexBuffer"/> class.
        /// </summary>
        /// <param name="context">Instance of an effect context</param>
        /// <param name="resourceId"></param>
        /// <param name="vertexBufferProperties"></param>
        /// <param name="customVertexBufferProperties"></param>
        public VertexBuffer(EffectContext context, System.Guid resourceId, SharpDX.Direct2D1.VertexBufferProperties vertexBufferProperties, CustomVertexBufferProperties customVertexBufferProperties) : base(IntPtr.Zero)
        {
            unsafe {            
                var customVertexBufferPropertiesNative = new CustomVertexBufferProperties.__Native();
                customVertexBufferProperties.__MarshalTo(ref customVertexBufferPropertiesNative);

                var inputElementsNative = new InputElement.__Native[customVertexBufferProperties.InputElements.Length];
                try
                {
                    for (int i = 0; i < customVertexBufferProperties.InputElements.Length; i++)
                        customVertexBufferProperties.InputElements[i].__MarshalTo(ref inputElementsNative[i]);

                    fixed (void* pInputElements = inputElementsNative)
                    {
                        customVertexBufferPropertiesNative.InputElementsPointer = (IntPtr)pInputElements;
                        customVertexBufferPropertiesNative.ElementCount = customVertexBufferProperties.InputElements.Length;
                        fixed (void* pInputSignature = customVertexBufferProperties.InputSignature)
                        {
                            customVertexBufferPropertiesNative.ShaderBufferSize = customVertexBufferProperties.InputSignature.Length;
                            customVertexBufferPropertiesNative.ShaderBufferWithInputSignature = (IntPtr)pInputSignature;

                            context.CreateVertexBuffer(vertexBufferProperties, resourceId, new IntPtr(&customVertexBufferPropertiesNative), this);
                        }
                    }
                }
                finally
                {
                    for (int i = 0; i < inputElementsNative.Length; i++)
                        inputElementsNative[i].__MarshalFree();
                }
            }
        }
Example #8
0
 public override void Draw(SharpDX.Toolkit.GameTime gameTime)
 {
     Vector2 p1=new Vector2(RodeData.Node1.Position.Item1,RodeData.Node1.Position.Item2),
         p2=new Vector2(RodeData.Node2.Position.Item1,RodeData.Node2.Position.Item2);
     DrawLine(p1, p2, line, Game, Color, RodeData.RoadDisplayMode);
     base.Draw(gameTime);
 }
 protected override SharpDX.DXGI.SwapChain2 CreateSwapChain(SharpDX.DXGI.Factory2 factory, SharpDX.Direct3D11.Device1 device, SharpDX.DXGI.SwapChainDescription1 desc)
 {
     // Creates a SwapChain from a CoreWindow pointer
     using (var comWindow = new ComObject(window))
     using (var swapChain1 = new SwapChain1(factory, device, comWindow, ref desc))
         return swapChain1.QueryInterface<SwapChain2>();
 }
Example #10
0
File: MainForm.cs Project: kmpm/MoJ
        void Joy_JoystickStateChanged(object sender, SharpDX.DirectInput.JoystickState state)
        {

            if (buttonPanel != null && buttonPanel.Controls.Count > 0)
            {
                for (int i = 0; i < buttonPanel.Controls.Count; i++)
                {
                    bool[] buttons = state.Buttons;
                    var b = (JoyButton)buttonPanel.Controls[i];
                    b.State = buttons[i];
                }
            }
            if (povsPanel != null && povsPanel.Controls.Count > 0)
            {
                int[] povs = state.PointOfViewControllers;
                for (int i = 0; i < povsPanel.Controls.Count; i++)
                {
                    var p = (JoyPov)povsPanel.Controls[i];
                    p.State = povs[i];
                }
            }
            if (sliderPanel != null && sliderPanel.Controls.Count > 0)
            {
                for(int i=0; i<sliderPanel.Controls.Count; i++){
                    var c = (JoySlider)sliderPanel.Controls[i];
                    c.State = state.Sliders[i];
                }
            }
        }
Example #11
0
 public Form1(Factory factory, SharpDX.Direct3D11.Device device, Object renderLock)
 {
     InitializeComponent();
     this.factory = factory;
     this.device = device;
     this.renderLock = renderLock;
 }
        public override void Update(double secondsElapsed, ExternalUtilsCSharp.KeyUtils keyUtils, SharpDX.Vector2 cursorPoint, bool checkMouse = false)
        {
            base.Update(secondsElapsed, keyUtils, cursorPoint, checkMouse);
            Framework fw = WithOverlay.Framework;
            if (fw.LocalPlayer == null)
                return;
            if (!fw.LocalPlayer.IsValid())
                return;

            if(fw.LocalPlayer.m_iTeamNum == (int)Team.Terrorists)
            {
                this.AlliesColor = Color.Red;
                this.EnemiesColor = Color.LightBlue;
            }
            else
            {
                this.AlliesColor = Color.LightBlue;
                this.EnemiesColor = Color.Red;
            }

            this.RotationDegrees = fw.ViewAngles.Y + 90;
            this.CenterCoordinate = new SharpDX.Vector2(fw.LocalPlayer.m_vecOrigin.X, fw.LocalPlayer.m_vecOrigin.Y);

            var enemies = fw.Players.Where(x => x.Item2.IsValid() && x.Item2.m_iHealth > 0 && x.Item2.m_iTeamNum != fw.LocalPlayer.m_iTeamNum);
            this.Enemies = enemies.Select(x => new Vector2(x.Item2.m_vecOrigin.X, x.Item2.m_vecOrigin.Y)).ToArray();

            var allies = fw.Players.Where(x => x.Item2.IsValid() && x.Item2.m_iHealth > 0 && x.Item2.m_iTeamNum == fw.LocalPlayer.m_iTeamNum);
            this.Allies = allies.Select(x => new Vector2(x.Item2.m_vecOrigin.X, x.Item2.m_vecOrigin.Y)).ToArray();
        }
 protected override void OnDraw(SharpDX.Direct2D1.WindowRenderTarget device)
 {
     if (Theme.ShadowColor != Color.Transparent)
         FillRectangle(device, Theme.ShadowColor, X, Y, Width, Height);
     if (Theme.BackColor != Color.Transparent)
         FillRectangle(device, Theme.BackColor, X, Y, Width, Height);
 }
        public LinearGradientBrushImpl(
            Perspex.Media.LinearGradientBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Size destinationSize)
        {
            if (brush != null)
            {
                var gradientStops = brush.GradientStops.Select(s => new SharpDX.Direct2D1.GradientStop { Color = s.Color.ToDirect2D(), Position = (float)s.Offset }).ToArray();

                Point startPoint = new Point(0, 0);
                Point endPoint = new Point(0, 0);

                switch (brush.MappingMode)
                {
                    case Perspex.Media.BrushMappingMode.Absolute:
                        // TODO:

                        break;
                    case Perspex.Media.BrushMappingMode.RelativeToBoundingBox:
                        startPoint = new Point(brush.StartPoint.X * destinationSize.Width, brush.StartPoint.Y * destinationSize.Height);
                        endPoint = new Point(brush.EndPoint.X * destinationSize.Width, brush.EndPoint.Y * destinationSize.Height);

                        break;
                }

                PlatformBrush = new SharpDX.Direct2D1.LinearGradientBrush(
                    target,
                    new SharpDX.Direct2D1.LinearGradientBrushProperties { StartPoint = startPoint.ToSharpDX(), EndPoint = endPoint.ToSharpDX() },
                    new SharpDX.Direct2D1.BrushProperties { Opacity = (float)brush.Opacity, Transform = target.Transform },
                    new SharpDX.Direct2D1.GradientStopCollection(target, gradientStops, brush.SpreadMethod.ToDirect2D())
                );
            }
        }
        public static UnorderedAccessView CreateBufferUAV(SharpDX.Direct3D11.Device device, Buffer buffer, UnorderedAccessViewBufferFlags flags = UnorderedAccessViewBufferFlags.None)
        {
            UnorderedAccessViewDescription uavDesc = new UnorderedAccessViewDescription
            {
                Dimension = UnorderedAccessViewDimension.Buffer,
                Buffer = new UnorderedAccessViewDescription.BufferResource { FirstElement = 0 }
            };
            if ((buffer.Description.OptionFlags & ResourceOptionFlags.BufferAllowRawViews) == ResourceOptionFlags.BufferAllowRawViews)
            {
                // A raw buffer requires R32_Typeless
                uavDesc.Format = Format.R32_Typeless;
                uavDesc.Buffer.Flags = UnorderedAccessViewBufferFlags.Raw | flags;
                uavDesc.Buffer.ElementCount = buffer.Description.SizeInBytes / 4;
            }
            else if ((buffer.Description.OptionFlags & ResourceOptionFlags.BufferStructured) == ResourceOptionFlags.BufferStructured)
            {
                uavDesc.Format = Format.Unknown;
                uavDesc.Buffer.Flags = flags;
                uavDesc.Buffer.ElementCount = buffer.Description.SizeInBytes / buffer.Description.StructureByteStride;
            }
            else
            {
                throw new ArgumentException("Buffer must be raw or structured", "buffer");
            }

            return new UnorderedAccessView(device, buffer, uavDesc);
        }
Example #16
0
 private void SetButtonStateTo(MouseButton button, SharpDX.Toolkit.Input.ButtonState state)
 {
     switch (button)
     {
         case MouseButton.None:
             break;
         case MouseButton.Left:
             left = state;
             break;
         case MouseButton.Middle:
             middle = state;
             break;
         case MouseButton.Right:
             right = state;
             break;
         case MouseButton.XButton1:
             xButton1 = state;
             break;
         case MouseButton.XButton2:
             xButton2 = state;
             break;
         default:
             throw new ArgumentOutOfRangeException("button");
     }
 }
 /// <summary>	
 /// <p><strong>Applies to: </strong>desktop apps | Metro style apps</p><p> Creates a media source or a byte stream from a URL. This method is synchronous. </p>	
 /// </summary>	
 /// <param name="url"><dd> <p> Null-terminated string that contains the URL to resolve. </p> </dd></param>	
 /// <param name="flags"><dd> <p> Bitwise OR of one or more flags. See <strong>Source Resolver Flags</strong>. </p> </dd></param>	
 /// <param name="objectType"><dd> <p> Receives a member of the <strong><see cref="SharpDX.MediaFoundation.ObjectType"/></strong> enumeration, specifying the type of object that was created. </p> </dd></param>	
 /// <returns>A reference to the object's <strong><see cref="SharpDX.ComObject"/></strong> interface. The caller must release the interface.</returns>	
 /// <remarks>	
 /// <p>The <em>dwFlags</em> parameter must contain either the <strong><see cref="SharpDX.MediaFoundation.SourceResolverFlags.MediaSource"/></strong> flag or the <strong><see cref="SharpDX.MediaFoundation.SourceResolverFlags.ByteStream"/></strong> flag, but should not contain both.</p><p>For local files, you can pass the file name in the <em>pwszURL</em> parameter; the <code>file:</code> scheme is not required.</p><p><strong>Note</strong>??This method cannot be called remotely.</p>	
 /// </remarks>	
 /// <msdn-id>ms702279</msdn-id>	
 /// <unmanaged>HRESULT IMFSourceResolver::CreateObjectFromURL([In] const wchar_t* pwszURL,[In] unsigned int dwFlags,[In] IPropertyStore* pProps,[Out] MF_OBJECT_TYPE* pObjectType,[Out] IUnknown** ppObject)</unmanaged>	
 /// <unmanaged-short>IMFSourceResolver::CreateObjectFromURL</unmanaged-short>	
 public SharpDX.ComObject CreateObjectFromURL(string url,
     SourceResolverFlags flags,
     out SharpDX.MediaFoundation.ObjectType objectType
     )
 {
     return CreateObjectFromURL(url, flags, null, out objectType);
 }
Example #18
0
 /// <summary>	
 /// <p>Creates an effect from a binary effect or file.</p>	
 /// </summary>	
 /// <param name="dataRef"><dd>  <p>Blob of compiled effect data.</p> </dd></param>	
 /// <param name="dataLength"><dd>  <p>Length of the data blob.</p> </dd></param>	
 /// <param name="fXFlags"><dd>  <p>No effect flags exist. Set to zero.</p> </dd></param>	
 /// <param name="deviceRef"><dd>  <p>Pointer to the <strong><see cref="SharpDX.Direct3D11.Device"/></strong> on which to create Effect resources.</p> </dd></param>	
 /// <param name="effectOut"><dd>  <p>Address of the newly created <strong><see cref="SharpDX.Direct3D11.Effect"/></strong> interface.</p> </dd></param>	
 /// <param name="srcName">No documentation.</param>	
 /// <returns><p>The return value is one of the values listed in Direct3D 11 Return Codes.</p></returns>	
 /// <remarks>	
 /// <p><strong>Note</strong>??You must use Effects 11 source to build  your effects-type application. For more info about using Effects 11 source, see Differences Between Effects 10 and Effects 11.</p>	
 /// </remarks>	
 /// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='D3DX11CreateEffectFromMemory']/*"/>	
 /// <msdn-id>ff476273</msdn-id>	
 /// <unmanaged>HRESULT D3DX11CreateEffectFromMemory([In, Buffer] const void* pData,[In] SIZE_T DataLength,[In] unsigned int FXFlags,[In] ID3D11Device* pDevice,[Out, Fast] ID3DX11Effect** ppEffect,[In, Optional] const char* srcName)</unmanaged>	
 /// <unmanaged-short>D3DX11CreateEffectFromMemory</unmanaged-short>	
 public static void CreateEffectFromMemory(System.IntPtr dataRef,
     SharpDX.PointerSize dataLength,
     int fXFlags,
     SharpDX.Direct3D11.Device deviceRef,
     SharpDX.Direct3D11.Effect effectOut,
     string srcName)
 {
     unsafe
     {
         IntPtr effectOut_ = IntPtr.Zero;
         IntPtr srcName_ = Utilities.StringToHGlobalAnsi(srcName);
         SharpDX.Result __result__;
         if(IntPtr.Size == 4)
         {
             __result__ = D3DX11CreateEffectFromMemory_11_1_x86(dataRef, dataLength, fXFlags, deviceRef.NativePointer, out effectOut_, srcName_);
         }
         else
         {
             __result__ = D3DX11CreateEffectFromMemory_11_1_x64(dataRef, dataLength, fXFlags, deviceRef.NativePointer, out effectOut_, srcName_);
         }
         ((SharpDX.Direct3D11.Effect)effectOut).NativePointer = effectOut_;
         Marshal.FreeHGlobal(srcName_);
         __result__.CheckError();
     }
 }
 public static SharpDX.Direct3D11.VertexShader VertexShader(SharpDX.Direct3D11.Device device, string hlslFile, string entryPoint, ShaderMacro[] defines = null, string profile = "vs_5_0")
 {
     using (var bytecode = CompileFromFile(hlslFile, entryPoint, profile, defines))
     {
         return new SharpDX.Direct3D11.VertexShader(device, bytecode);
     }
 }
        private void LoadGeometry()
        {
            // constants for easy manipulation
            const float f = 0.5f;
            const float c = 0.75f;

            var vertices = new[]
                           {
                               new Vertex(new Vector3(f, f, f), new Vector3(c, 0f, 0f)),
                               new Vertex(new Vector3(f, f, -f), new Vector3(0, c, 0f)),
                               new Vertex(new Vector3(f, -f, f), new Vector3(0f, 0f, c)),
                               new Vertex(new Vector3(f, -f, -f), new Vector3(c, c, 0f)),

                               new Vertex(new Vector3(-f, f, f), new Vector3(c, 0f, c)),
                               new Vertex(new Vector3(-f, f, -f), new Vector3(0f, c, c)),
                               new Vertex(new Vector3(-f, -f, f), new Vector3(0f, 0f, 0f)),
                               new Vertex(new Vector3(-f, -f, -f), new Vector3(c, c, c))
                           };

            var indices = new short[]
                          {
                              0,2,1, 1,2,3,
                              1,3,7, 7,5,1,

                              5,7,6, 5,6,4,
                              0,6,2, 0,4,6,

                              0,1,5, 0,5,4,
                              3,7,6, 3,6,2
                          };

            _cubeGeometry = ToDisposeContent(new GeometricPrimitive<Vertex>(GraphicsDevice, vertices, indices, false));
        }
 public static MathObjects.Vector3[] Vector3SDXtoEUC(SharpDX.Vector3[] vec)
 {
     MathObjects.Vector3[] vecs = new MathObjects.Vector3[vec.Length];
     for (int i = 0; i < vecs.Length; i++)
         vecs[i] = Vector3SDXtoEUC(vec[i]);
     return vecs;
 }
Example #22
0
        private BitmapBrush CreateDirectBrush(
            ImageBrush brush,
            SharpDX.Direct2D1.RenderTarget target,
            Bitmap image, 
            Rect sourceRect, 
            Rect destinationRect)
        {
            var tileMode = brush.TileMode;
            var scale = brush.Stretch.CalculateScaling(destinationRect.Size, sourceRect.Size);
            var translate = CalculateTranslate(brush, sourceRect, destinationRect, scale);
            var transform = Matrix.CreateTranslation(-sourceRect.Position) *
                Matrix.CreateScale(scale) *
                Matrix.CreateTranslation(translate);

            var opts = new BrushProperties
            {
                Transform = transform.ToDirect2D(),
                Opacity = (float)brush.Opacity,
            };

            var bitmapOpts = new BitmapBrushProperties
            {
                ExtendModeX = GetExtendModeX(tileMode),
                ExtendModeY = GetExtendModeY(tileMode),                
            };

            return new BitmapBrush(target, image, bitmapOpts, opts);
        }
Example #23
0
        public override void Draw(SharpDX.Toolkit.GameTime gametime)
        {
            // model.Draw(game.GraphicsDevice, basicEffect.World, basicEffect.View, basicEffect.Projection);
                        foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    // effect.EnableDefaultLighting();
                    effect.LightingEnabled = true; // Turn on the lighting subsystem.

                    effect.DirectionalLight0.DiffuseColor = new Vector3(0.0008f, 0.0008f, 0.0008f); // a reddish light
                    effect.DirectionalLight0.Direction = new Vector3(10000, 5000, 5000);  // coming along the x-axis
                    effect.DirectionalLight0.SpecularColor = new Vector3(0.8f, 0.8f, 0.8f); // with green highlights
                    effect.SpecularPower = 5;

                    effect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f); // Add some overall ambient light.
                    // effect.EmissiveColor = new Vector3(1, 0, 0); // Sets some strange emmissive lighting.  This just looks weird.
                /*    if (pos.Y > 50)
                    {
                        effect.FogEnabled = true;
                        effect.FogColor = Color.WhiteSmoke.ToVector3(); // For best results, ake this color whatever your background is.
                        effect.FogStart = 9.75f;
                        effect.FogEnd = 10.25f;
                    }*/
                    effect.World = this.basicEffect.World;
                    effect.View = this.basicEffect.View;
                    effect.Projection = this.basicEffect.Projection;

                    //     effect.TextureEnabled = true;
                    //     effect.Texture = texture;
                }

                mesh.Draw(game.GraphicsDevice);
            }
        }
        internal static async Task Render(CompositionEngine compositionEngine, SharpDX.Direct2D1.RenderTarget renderTarget, FrameworkElement rootElement, Line line)
        {
            var rect = line.GetBoundingRect(rootElement).ToSharpDX();
            var stroke = await line.Stroke.ToSharpDX(renderTarget, rect);

            if (stroke == null ||
                line.StrokeThickness <= 0)
            {
                return;
            }

            var layer = line.CreateAndPushLayerIfNecessary(renderTarget, rootElement);

            renderTarget.DrawLine(
                new Vector2(
                    rect.Left + (float)line.X1,
                    rect.Top + (float)line.Y1),
                new Vector2(
                    rect.Left + (float)line.X2,
                    rect.Top + (float)line.Y2),
                    stroke,
                    (float)line.StrokeThickness,
                    line.GetStrokeStyle(compositionEngine.D2DFactory));

            if (layer != null)
            {
                renderTarget.PopLayer();
                layer.Dispose();
            }
        }
        private void ClearTargets(RenderTargetBinding[] targets, SharpDX.Direct3D11.CommonShaderStage shaderStage)
        {
            // NOTE: We make the assumption here that the caller has
            // locked the d3dContext for us to use.

            // We assume 4 targets to avoid a loop within a loop below.
            var target0 = targets[0].RenderTarget;
            var target1 = targets[1].RenderTarget;
            var target2 = targets[2].RenderTarget;
            var target3 = targets[3].RenderTarget;

            // Make one pass across all the texture slots.
            for (var i = 0; i < _textures.Length; i++)
            {
                if (_textures[i] == null)
                    continue;

                if (_textures[i] != target0 &&
                    _textures[i] != target1 &&
                    _textures[i] != target2 &&
                    _textures[i] != target3)
                    continue;

                // Immediately clear the texture from the device.
                _dirty &= ~(1 << i);
                _textures[i] = null;
                shaderStage.SetShaderResource(i, null);
            }
        }
Example #26
0
     public GraphicsCommandList CreateCommandList(
 SharpDX.Direct3D12.CommandListType type,
 SharpDX.Direct3D12.CommandAllocator commandAllocatorRef,
 SharpDX.Direct3D12.PipelineState initialStateRef)
     {
         return CreateCommandList(0, type, commandAllocatorRef, initialStateRef);
     }
        public void SetRenderTargetDX10(SharpDX.Direct3D10.Texture2D renderTarget)
        {
            if (RenderTarget != null)
            {
                RenderTarget = null;

                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, IntPtr.Zero);
                base.Unlock();
            }

            if (renderTarget == null)
                return;

            if (!IsShareable(renderTarget))
                throw new ArgumentException("Texture must be created with ResourceOptionFlags.Shared");

            Format format = DX10ImageSource.TranslateFormat(renderTarget);
            if (format == Format.Unknown)
                throw new ArgumentException("Texture format is not compatible with OpenSharedResource");

            IntPtr handle = GetSharedHandle(renderTarget);
            if (handle == IntPtr.Zero)
                throw new ArgumentNullException("Handle");

            RenderTarget = new Texture(DX10ImageSource.D3DDevice, renderTarget.Description.Width, renderTarget.Description.Height, 1, Usage.RenderTarget, format, Pool.Default, ref handle);
            using (Surface surface = RenderTarget.GetSurfaceLevel(0))
            {
                base.Lock();
                base.SetBackBuffer(D3DResourceType.IDirect3DSurface9, surface.NativePointer);
                base.Unlock();
            }
        }
Example #28
0
        public override void Draw(SharpDX.Toolkit.GameTime gametime)
        {
            //model.Draw(game.GraphicsDevice, basicEffect.World, basicEffect.View, basicEffect.Projection);
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    // effect.EnableDefaultLighting();
                    effect.LightingEnabled = true; // Turn on the lighting subsystem.

                    effect.DirectionalLight0.DiffuseColor = new Vector3(0f, 1f, 0f); // a reddish light
                    effect.DirectionalLight0.Direction = new Vector3(pos.X +100, pos.Y+500, pos.Z+ 500);  // coming along the x-axis
                    effect.DirectionalLight0.SpecularColor = new Vector3(0, 0, 0); // with green highlights

                    effect.AmbientLightColor = new Vector3(0.2f, 0.2f, 0.2f); // Add some overall ambient light.
                    // effect.EmissiveColor = new Vector3(1, 0, 0); // Sets some strange emmissive lighting.  This just looks weird.

                    effect.World = this.basicEffect.World;
                    effect.View = this.basicEffect.View;
                    effect.Projection = this.basicEffect.Projection;

                    //     effect.TextureEnabled = true;
                    //     effect.Texture = texture;
                }

                mesh.Draw(game.GraphicsDevice);
            }
        }
Example #29
0
 public override void Update(SharpDX.Toolkit.GameTime gametime)
 {
     float a = 9.8f;
     pos.Z = game.z0 - game.v0 * (float)Math.Cos(((game.yDegree / 180.0) * Math.PI)) * (float)(Math.Cos((game.degree / 180) * Math.PI)) * game.time;
     pos.X = game.x0 + game.v0 * (float)Math.Cos(((game.yDegree / 180.0) * Math.PI)) * (float)(Math.Sin((game.degree / 180) * Math.PI)) * game.time;
     pos.Y = (game.y0 + (game.v0 * (float)Math.Sin(((game.yDegree / 180.0) * Math.PI)) * game.time)) - (0.5f * a * game.time * game.time);
 }
Example #30
-1
 /// <summary>	
 /// Draw formatted text.
 /// </summary>	
 /// <remarks>	
 /// The parameters of this method are very similar to those of the {{GDI DrawText}} function. This method supports both ANSI and Unicode strings. Unless the DT_NOCLIP format is used, this method clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified. If the selected font is too large for the rectangle, this method does not attempt to substitute a smaller font. This method supports only fonts whose escapement and orientation are both zero. 	
 /// </remarks>	
 /// <param name="sprite">Reference to an ID3DX10Sprite object that contains the string you wish to draw. Can be NULL, in which case Direct3D will render the string with its own sprite object. To improve efficiency, a sprite object should be specified if ID3DX10Font::DrawText is to be called more than once in a row. </param>
 /// <param name="text">Pointer to a string to draw. If UNICODE is defined, this parameter type resolves to an LPCWSTR, otherwise, the type resolves to an LPCSTR. If the Count parameter is -1, the string must be NULL terminated. </param>
 /// <param name="rect">Pointer to a <see cref="RawRectangle"/> structure that contains the rectangle, in logical coordinates, in which the text is to be formatted. As with any RECT object, the coordinate value of the rectangle's right side must be greater than that of its left side. Likewise, the coordinate value of the bottom must be greater than that of the top. </param>
 /// <param name="drawFlags">Specify the method of formatting the text. It can be any combination of the following values:    ItemDescription  DT_BOTTOM  Justify the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.   DT_CALCRECT  Tell DrawText to automatically calculate the width and height of the rectangle based on the length of the string you tell it to draw. If there are multiple lines of text, ID3DX10Font::DrawText uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, ID3DX10Font::DrawText modifies the right side of the rectangle so that it bounds the last character in the line. In either case, ID3DX10Font::DrawText returns the height of the formatted text but does not draw the text.   DT_CENTER  Center text horizontally in the rectangle.   DT_EXPANDTABS  Expand tab characters. The default number of characters per tab is eight.   DT_LEFT  Align text to the left.   DT_NOCLIP  Draw without clipping. ID3DX10Font::DrawText is somewhat faster when DT_NOCLIP is used.   DT_RIGHT  Align text to the right.   DT_RTLREADING  Display text in right-to-left reading order for bidirectional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.   DT_SINGLELINE  Display text on a single line only. Carriage returns and line feeds do not break the line.   DT_TOP  Top-justify text.   DT_VCENTER  Center text vertically (single line only).   DT_WORDBREAK  Break words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.   ? </param>
 /// <param name="color">Color of the text. See <see cref="RawColor4"/>. </param>
 /// <returns>If the function succeeds, the return value is the height of the text in logical units. If DT_VCENTER or DT_BOTTOM is specified, the return value is the offset from pRect (top to the bottom) of the drawn text. If the function fails, the return value is zero. </returns>
 /// <unmanaged>int ID3DX10Font::DrawTextW([None] LPD3DX10SPRITE pSprite,[None] const wchar_t* pString,[None] int Count,[None] RECT* pRect,[None] int Format,[None] D3DXCOLOR Color)</unmanaged>
 public unsafe int DrawText(SharpDX.Direct3D10.Sprite sprite, string text, RawRectangle rect, FontDrawFlags drawFlags, RawColor4 color)
 {
     int value = DrawText(sprite, text, text.Length, new IntPtr(&rect), (int) drawFlags, color);
     if (value == 0)
         throw new SharpDXException("Draw failed");
     return value;
 }