private async void UpdateVisibility(bool keepFocus) { if (_updating) { return; } _updating = true; await Task.Delay(1); if (_child != null) { var val = _visible && (_parent.Focused || _child.IsActive) ? Visibility.Visible : Visibility.Hidden; if (val != _child.Visibility) { _child.Visibility = val; if (val == Visibility.Visible) { _child.Topmost = false; _child.Topmost = true; } if (keepFocus) { await Task.Delay(1); _parent.Focus(); _parent.Activate(); } } } _updating = false; }
static void Main(string[] args) { System.Console.WriteLine("Victorem for by_Owl 17.07.2016"); System.Console.WriteLine("Загрузка ресурсов ..."); double start = System.Environment.TickCount; if (!SharpDX.Direct3D11.Device.IsSupportedFeatureLevel(SharpDX.Direct3D.FeatureLevel.Level_11_0)) { MessageBox.Show("Для запуска этой игры нужен DirectX 11 ОБЯЗАТЕЛЬНО!"); return; } #if DEBUG SharpDX.Configuration.EnableObjectTracking = true; #endif using (var _renderForm = new RenderForm("SharpDX game by Winbringer") { AllowUserResizing = false, IsFullscreen = false, StartPosition = FormStartPosition.CenterScreen, ClientSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height), FormBorderStyle = FormBorderStyle.None, Icon = new Icon("LogoVW.ico") }) { _renderForm.Shown += (sender, e) => { _renderForm.Activate(); }; _renderForm.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Escape) { _renderForm.Close(); } }; using (Game game = new Game(_renderForm)) { System.Console.WriteLine("Для начала игры нажмите \"Enter\""); System.Console.WriteLine("Для выхода из игры нажмите \"Esc\""); System.Console.WriteLine("Для паузы нажмите латинскую \"P\""); System.Console.WriteLine("\"U\" - Возврат снаряда "); System.Console.WriteLine("\" W A S D \" - Движение камеры "); System.Console.WriteLine("\"<- | -> \" - Стрелки на клавиатуре, поворот камеры "); System.Console.WriteLine("\"Z X\" - Изменение высоты камеры "); System.Console.WriteLine("\" 1 2 3 4 5 6\" - Цифры на клавиатуре, управление направлением, углом стрельбы и скоростью полета планеты"); System.Console.WriteLine("\"Пробел\" - Клавиша пробела запускает снаряд в цель"); System.Console.ReadLine(); game.Run(); } } double end = (System.Environment.TickCount - start) / 1000; System.Console.WriteLine("Всего проведено в игре секунд : " + end.ToString()); System.Console.WriteLine("Для завершения нажмите ввод"); System.Console.ReadLine(); }
static unsafe void Main(string[] args) { Application.EnableVisualStyles(); _screenRect = Screen.PrimaryScreen.Bounds; _form = new RenderForm("AZUSA E-mote Sample - NekoSpirit"); _form.AutoScaleMode = AutoScaleMode.None; //_form.FormBorderStyle = FormBorderStyle.None; _form.ClientSize = new Size(Width, Height); _form.Resize += FormOnResize; FormOnResize(_form, null); //form.TopMost = true; _form.StartPosition = FormStartPosition.Manual; _form.Location = new Point(_screenRect.Width - _form.Width, _screenRect.Height - _form.Height); //form.AllowTransparency = true; _e = new Emote(_form.Handle, Width, Height, false); _e.EmoteInit(); _e.Device.TextureFilter = GrayTextureFilter; if (File.Exists(args[0])) { _player = _e.CreatePlayer("Chara1", args[0]); } else { _player = _e.CreatePlayer("Chara1", "emote_test.pure.psb"); } _e.Device.UseTextureFilter = false; //turn on texture filter! //e.Device.SetMaskRegionClipping(true); //Set this to true will increase CPU usage but decrease GPU usage. //_player2 = _e.CreatePlayer("Chara2", "chocola-pure.psb"); //I don't know how to use this method. I guess this method may combine two models (only if they are complementary). //virtual void CreatePlayer (emote_uint32_t emoteObjectNum, const emote_uint8_t **emoteObjectImage, const emote_uint32_t *emoteObjectSize, class IEmotePlayer **player)=0 //_player2 = e.CreatePlayer("Chocola", new[] {"dx_e-mote3.0ショコラ制服b_鈴あり.psb", "dx_e-mote3.0バニラ私服b_鈴あり.psb"}); _player.Show(); //_player2.Show(); var faceTable = new Dictionary <string, float> { { "face_eye_UD", -30f }, { "face_eye_LR", 0.0f }, { "face_eye_open", 5 }, { "face_eyebrow", 20f }, { "face_mouth", 20 }, { "face_talk", 0.5f }, { "face_tears", 0.0f }, { "face_cheek", 0.0f } }; _device = new Device(new IntPtr(_e.D3Device)); _player.SetScale(0.4f, 0, 0); _player.SetCoord(300, 50, 0, 0); _player.StartWind(0f, 1f, 0.8f, 0.5f, 0.8f); _player.SetSmoothing(true); //for (uint i = 0; i < _player.CountVariables(); i++) //{ // for (uint j = 0; j < _player.CountVariableFrameAt(i); j++) // { // Console.WriteLine($"{_player.GetVariableFrameLabelAt(i, j)}:{_player.GetVariableFrameValueAt(i,j)}"); // } //} //_player2.SetScale(0.4f, 0, 0); //_player2.SetCoord(-100, 50, 0, 0); //_player2.SetSmoothing(true); //_player2.SetVariables(faceTable, 2000f, 1f); //-Why are you so angry? -Why am I monochrome? //_player.PlayTimeline("変な動き", TimelinePlayFlags.TIMELINE_PLAY_PARALLEL); //_player2.PlayTimeline("差分用_waiting_loop", TimelinePlayFlags.TIMELINE_PLAY_PARALLEL); //ctrlform.TopMost = true; Thread th = new Thread(() => { //var ctrlform2 = new FormConsole(_player2, "Chara2"); //ctrlform2.Closed += // (sender, eventArgs) => // { // _e.DeletePlayer(_player2); //Try to close this form, the memory will be released // }; //ctrlform2.Show(); var ctrlform = new FormConsole(_player, "Chara1"); //ctrlform.Show(); Application.Run(ctrlform); }); th.Start(); //Control _form.MouseClick += form_MouseClick; _form.MouseDown += form_MouseDown; _form.MouseMove += form_MouseMove; _form.MouseUp += form_MouseUp; _form.MouseWheel += (sender, eventArgs) => _player.OffsetScale(1 + ConvertDelta(eventArgs.Delta)); _form.Load += (sender, eventArgs) => { _form.Activate(); }; RenderLoop.Run(_form, Render); }
public void Run() { var form = new RenderForm("2d and 3d combined...it's like magic"); form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.Escape) { form.Close(); } }; // DirectX DXGI 1.1 factory var factory1 = new Factory1(); // The 1st graphics adapter var adapter1 = factory1.GetAdapter1(0); // --------------------------------------------------------------------------------------------- // Setup direct 3d version 11. It's context will be used to combine the two elements // --------------------------------------------------------------------------------------------- var description = new SwapChainDescription { BufferCount = 1, ModeDescription = new ModeDescription(0, 0, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput, Flags = SwapChainFlags.AllowModeSwitch }; Device11 device11; SwapChain swapChain; Device11.CreateWithSwapChain(adapter1, DeviceCreationFlags.None, description, out device11, out swapChain); // create a view of our render target, which is the backbuffer of the swap chain we just created RenderTargetView renderTargetView; using (var resource = Resource.FromSwapChain <Texture2D>(swapChain, 0)) renderTargetView = new RenderTargetView(device11, resource); // setting a viewport is required if you want to actually see anything var context = device11.ImmediateContext; var viewport = new Viewport(0.0f, 0.0f, form.ClientSize.Width, form.ClientSize.Height); context.OutputMerger.SetTargets(renderTargetView); context.Rasterizer.SetViewports(viewport); // // Create the DirectX11 texture2D. This texture will be shared with the DirectX10 device. // // The DirectX10 device will be used to render text onto this texture. // DirectX11 will then draw this texture (blended) onto the screen. // The KeyedMutex flag is required in order to share this resource between the two devices. var textureD3D11 = new Texture2D(device11, new Texture2DDescription { Width = form.ClientSize.Width, Height = form.ClientSize.Height, MipLevels = 1, ArraySize = 1, Format = Format.B8G8R8A8_UNorm, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.SharedKeyedmutex }); // --------------------------------------------------------------------------------------------- // Setup a direct 3d version 10.1 adapter // --------------------------------------------------------------------------------------------- var device10 = new Device10(adapter1, SharpDX.Direct3D10.DeviceCreationFlags.BgraSupport, FeatureLevel.Level_10_0); // --------------------------------------------------------------------------------------------- // Setup Direct 2d // --------------------------------------------------------------------------------------------- // Direct2D Factory var factory2D = new SharpDX.Direct2D1.Factory(FactoryType.SingleThreaded, DebugLevel.Information); // Here we bind the texture we've created on our direct3d11 device through the direct3d10 // to the direct 2d render target.... var sharedResource = textureD3D11.QueryInterface <SharpDX.DXGI.Resource>(); var textureD3D10 = device10.OpenSharedResource <SharpDX.Direct3D10.Texture2D>(sharedResource.SharedHandle); var surface = textureD3D10.AsSurface(); var rtp = new RenderTargetProperties { MinLevel = SharpDX.Direct2D1.FeatureLevel.Level_10, Type = RenderTargetType.Hardware, PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied) }; var renderTarget2D = new RenderTarget(factory2D, surface, rtp); var solidColorBrush = new SolidColorBrush(renderTarget2D, Colors.Red); // --------------------------------------------------------------------------------------------------- // Setup the rendering data // --------------------------------------------------------------------------------------------------- // Load Effect. This includes both the vertex and pixel shaders. // Also can include more than one technique. ShaderBytecode shaderByteCode = ShaderBytecode.CompileFromFile( "effectDx11.fx", "fx_5_0", ShaderFlags.EnableStrictness); var effect = new Effect(device11, shaderByteCode); // create triangle vertex data, making sure to rewind the stream afterward var verticesTriangle = new DataStream(VertexPositionColor.SizeInBytes * 3, true, true); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.0f, 0.5f, 0.5f), new Color4(1.0f, 0.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(0.5f, -0.5f, 0.5f), new Color4(0.0f, 1.0f, 0.0f, 1.0f))); verticesTriangle.Write(new VertexPositionColor(new Vector3(-0.5f, -0.5f, 0.5f), new Color4(0.0f, 0.0f, 1.0f, 1.0f))); verticesTriangle.Position = 0; // create the triangle vertex layout and buffer var layoutColor = new InputLayout(device11, effect.GetTechniqueByName("Color").GetPassByIndex(0).Description.Signature, VertexPositionColor.inputElements); var vertexBufferColor = new Buffer(device11, verticesTriangle, (int)verticesTriangle.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesTriangle.Close(); // create overlay vertex data, making sure to rewind the stream afterward // Top Left of screen is -1, +1 // Bottom Right of screen is +1, -1 var verticesText = new DataStream(VertexPositionTexture.SizeInBytes * 4, true, true); verticesText.Write(new VertexPositionTexture(new Vector3(-1, 1, 0), new Vector2(0, 0f))); verticesText.Write(new VertexPositionTexture(new Vector3(1, 1, 0), new Vector2(1, 0))); verticesText.Write(new VertexPositionTexture(new Vector3(-1, -1, 0), new Vector2(0, 1))); verticesText.Write(new VertexPositionTexture(new Vector3(1, -1, 0), new Vector2(1, 1))); verticesText.Position = 0; // create the overlay vertex layout and buffer var layoutOverlay = new InputLayout(device11, effect.GetTechniqueByName("Overlay").GetPassByIndex(0).Description.Signature, VertexPositionTexture.inputElements); var vertexBufferOverlay = new Buffer(device11, verticesText, (int)verticesText.Length, ResourceUsage.Default, BindFlags.VertexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); verticesText.Close(); // Think of the shared textureD3D10 as an overlay. // The overlay needs to show the 2d content but let the underlying triangle (or whatever) // show thru, which is accomplished by blending. var bsd = new BlendStateDescription(); bsd.RenderTarget[0].IsBlendEnabled = true; bsd.RenderTarget[0].SourceBlend = BlendOption.SourceColor; bsd.RenderTarget[0].DestinationBlend = BlendOption.BlendFactor; bsd.RenderTarget[0].BlendOperation = BlendOperation.Add; bsd.RenderTarget[0].SourceAlphaBlend = BlendOption.One; bsd.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero; bsd.RenderTarget[0].AlphaBlendOperation = BlendOperation.Add; bsd.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All; var blendStateTransparent = new BlendState(device11, bsd); // --------------------------------------------------------------------------------------------------- // Create and tesselate an ellipse // --------------------------------------------------------------------------------------------------- var center = new DrawingPointF(form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f); var ellipse = new EllipseGeometry(factory2D, new Ellipse(center, form.ClientSize.Width / 2.0f, form.ClientSize.Height / 2.0f)); // Populate a PathGeometry from Ellipse tessellation var tesselatedGeometry = new PathGeometry(factory2D); _geometrySink = tesselatedGeometry.Open(); // Force RoundLineJoin otherwise the tesselated looks buggy at line joins _geometrySink.SetSegmentFlags(PathSegment.ForceRoundLineJoin); // Tesselate the ellipse to our TessellationSink ellipse.Tessellate(1, this); _geometrySink.Close(); // --------------------------------------------------------------------------------------------------- // Acquire the mutexes. These are needed to assure the device in use has exclusive access to the surface // --------------------------------------------------------------------------------------------------- var device10Mutex = textureD3D10.QueryInterface <KeyedMutex>(); var device11Mutex = textureD3D11.QueryInterface <KeyedMutex>(); // --------------------------------------------------------------------------------------------------- // Main rendering loop // --------------------------------------------------------------------------------------------------- bool first = true; RenderLoop .Run(form, () => { if (first) { form.Activate(); first = false; } // clear the render target to black context.ClearRenderTargetView(renderTargetView, Colors.DarkSlateGray); // Draw the triangle context.InputAssembler.InputLayout = layoutColor; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferColor, VertexPositionColor.SizeInBytes, 0)); context.OutputMerger.BlendState = null; var currentTechnique = effect.GetTechniqueByName("Color"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(3, 0); } ; // Draw Ellipse on the shared Texture2D device10Mutex.Acquire(0, 100); renderTarget2D.BeginDraw(); renderTarget2D.Clear(Colors.Black); renderTarget2D.DrawGeometry(tesselatedGeometry, solidColorBrush); renderTarget2D.DrawEllipse(new Ellipse(center, 200, 200), solidColorBrush, 20, null); renderTarget2D.EndDraw(); device10Mutex.Release(0); // Draw the shared texture2D onto the screen, blending the 2d content in device11Mutex.Acquire(0, 100); var srv = new ShaderResourceView(device11, textureD3D11); effect.GetVariableByName("g_Overlay").AsShaderResource().SetResource(srv); context.InputAssembler.InputLayout = layoutOverlay; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleStrip; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertexBufferOverlay, VertexPositionTexture.SizeInBytes, 0)); context.OutputMerger.BlendState = blendStateTransparent; currentTechnique = effect.GetTechniqueByName("Overlay"); for (var pass = 0; pass < currentTechnique.Description.PassCount; ++pass) { using (var effectPass = currentTechnique.GetPassByIndex(pass)) { System.Diagnostics.Debug.Assert(effectPass.IsValid, "Invalid EffectPass"); effectPass.Apply(context); } context.Draw(4, 0); } srv.Dispose(); device11Mutex.Release(0); swapChain.Present(0, PresentFlags.None); }); // dispose everything vertexBufferColor.Dispose(); vertexBufferOverlay.Dispose(); layoutColor.Dispose(); layoutOverlay.Dispose(); effect.Dispose(); shaderByteCode.Dispose(); renderTarget2D.Dispose(); swapChain.Dispose(); device11.Dispose(); device10.Dispose(); textureD3D10.Dispose(); textureD3D11.Dispose(); factory1.Dispose(); adapter1.Dispose(); sharedResource.Dispose(); factory2D.Dispose(); surface.Dispose(); solidColorBrush.Dispose(); blendStateTransparent.Dispose(); device10Mutex.Dispose(); device11Mutex.Dispose(); }