private void DrawingSurface_Loaded(object sender, RoutedEventArgs e) { // Set window bounds in dips m_d3dInterop.WindowBounds = new Windows.Foundation.Size( (float)DrawingSurface.ActualWidth, (float)DrawingSurface.ActualHeight ); // Set native resolution in pixels m_d3dInterop.NativeResolution = new Windows.Foundation.Size( (float)Math.Floor(DrawingSurface.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(DrawingSurface.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f) ); // Set render resolution to the full native resolution m_d3dInterop.RenderResolution = m_d3dInterop.NativeResolution; // Hook-up native component to DrawingSurface DrawingSurface.SetContentProvider(m_d3dInterop.CreateContentProvider()); DrawingSurface.SetManipulationHandler(m_d3dInterop); Deployment.Current.Dispatcher.BeginInvoke(() => { StreamResourceInfo resourceInfo = Application.GetResourceStream(new Uri("Assets/Lena.png", UriKind.Relative)); BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(resourceInfo.Stream); m_bmp = new WriteableBitmap(bitmap); m_d3dInterop.CreateTexture(m_bmp.Pixels, m_bmp.PixelWidth, m_bmp.PixelHeight, OCVFilterType.ePreview); m_bInitialized = true; }); }
private void DrawingSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { var position = e.GetPosition(DrawingSurface); if (AddRadioButton.IsChecked == true) { // Создать, нарисовать и добавить новый квадрат var visual = new DrawingVisual(); DrawSquare(visual, position, false); DrawingSurface.AddVisual(visual); } else if (DeleteRadioButton.IsChecked == true) { var visual = DrawingSurface.GetVisual(position); if (visual != null) { DrawingSurface.DeleteVisual(visual); } } else if (SelectMoveRadioButton.IsChecked == true) { var visual = DrawingSurface.GetVisual(position); if (visual != null) { /* Найти верхний левый угол квадрата. Это делается просмотром текущих границ * и удаления половины границы (толщины пера). Альтернативное решение может * предусматривать хранение верхней левой точки каждого визуального элемента * в коллекции DrawingCanvas и предоставление этой точки при проверке попадания. */ var topLeftCorner = new Point( visual.ContentBounds.TopLeft.X + _drawingPen.Thickness / 2, visual.ContentBounds.TopLeft.Y + _drawingPen.Thickness / 2); DrawSquare(visual, topLeftCorner, true); _clickOffset = topLeftCorner - position; _isDragging = true; if (_selectedVisual != null && !Equals(_selectedVisual, visual)) { // Выбор изменился. Очистить предыдущий выбор. ClearSelection(); } _selectedVisual = visual; } } else if (SelectMultipleRadioButton.IsChecked == true) { _selectionSquare = new DrawingVisual(); DrawingSurface.AddVisual(_selectionSquare); _selectionSquareTopLeft = position; _isMultiSelecting = true; // Обеспечить получение события MouseLeftButtonUp, даже // если пользователь вышел за пределы Canvas. В противном // случае могут быть нарисованы два квадрата сразу. DrawingSurface.CaptureMouse(); } }
public void ResetAI() { int i = 0; for (i = 0; i < MAX_RACING_CARS; i += 1) { RobotsPB[i].Reset(); } for (i = 0; i < MAX_RACING_CARS; i += 1) { RobotsRB[i].Reset(); } for (i = 0; i < MAX_PATH_NODES; i += 1) { Paths[i].Reset(); } if (AIRegionsDS) { AIRegionsDS.Release(); AIRegionsDS = null; } if (AIRegions) { AIRegions.Delete(); AIRegions = null; } ActiveAIType = eAINone; }
/// <summary> /// This call configure the graphic library for the new device instance. /// </summary> public override void InvalidateDevice() { base.InvalidateDevice(); // - Wait the GPU (we must operate only when GPU is idle) GraphicDevice.Handle.WaitIdle(); // - Dispose render pass DefaultRenderPass.Dispose(); // - Dispose the pipeline Pipeline.Dispose(); // - Dipose current swapchain Swapchain.Dispose(); // - Dispose current VK surface DrawingSurface.Dispose(); // - Dispose vertex and index managers VertexManager.Dispose(); IndexManager.Dispose(); // - Release all VK shaders ShaderManager.Dispose(); for (int i = 0; i < MaxFrameInFlight; ++i) { if (CommandBuffers[i] != null) { foreach (var buffer in CommandBuffers[i]) { buffer.Reset(); } Commands[i].FreeCommandBuffers(CommandBuffers[i]); } } foreach (Fence fence in InFlightFences) { fence.Destroy(); } foreach (Semaphore sem in ImageAvailableSemaphores) { sem.Destroy(); } foreach (Semaphore sem in RenderFinishedSemaphores) { sem.Destroy(); } // - Dispose device GraphicDevice.Dispose(); // - Initialize device Initialize(); // - Reconfigure the renderer ConfigureRendering(); }
//void _exportListButton_Click(object sender, EventArgs e) //{ // var editor = (Editors.SceneEditor)MainScreen.Instance.ActiveEditor; // if (editor.Hotspots.Count == 0) // return; // Windows.SelectFilePopup popup = new Windows.SelectFilePopup(); // popup.Center(); // popup.Closed += (s, e2) => // { // if (popup.DialogResult) // { // List<Hotspot> clonedSpots = new List<Hotspot>(editor.Hotspots.Count); // foreach (var spot in editor.Hotspots) // { // Hotspot newSpot = new Hotspot(); // newSpot.Title = spot.Title; // spot.DebugAppearance.CopyAppearanceTo(newSpot.DebugAppearance); // newSpot.Settings = new Dictionary<string, string>(spot.Settings); // clonedSpots.Add(newSpot); // } // popup.SelectedLoader.Save(clonedSpots, popup.SelectedFile); // } // }; // popup.FileLoaderTypes = new FileLoaders.IFileLoader[] { new FileLoaders.Hotspots() }; // popup.SkipFileExistCheck = true; // popup.SelectButtonText = "Save"; // popup.Show(true); //} //private void ImportListButton_Click(object sender, EventArgs e) //{ // Windows.SelectFilePopup popup = new Windows.SelectFilePopup(); // popup.Center(); // popup.Closed += (s, e2) => // { // if (popup.DialogResult) // { // var editor = (Editors.SceneEditor)MainScreen.Instance.ActiveEditor; // Dictionary<string, Hotspot> titleKeys = new Dictionary<string, Hotspot>(); // List<Hotspot> loadedSpots = (List<Hotspot>)popup.SelectedLoader.Load(popup.SelectedFile); // var titleCount = loadedSpots.Select(h => h.Title).Intersect(editor.Hotspots.Select(h => h.Title)).Count(); // if (titleCount != 0) // { // titleKeys = editor.Hotspots.ToDictionary((h) => h.Title, (h) => h); // Window.Prompt(new ColoredString($"{titleCount} will be overwritten, continue?"), "Yes", "No", (result) => // { // if (result) // RunImportLogic(loadedSpots, titleKeys); // }); // } // else // RunImportLogic(loadedSpots, titleKeys); // } // }; // popup.FileLoaderTypes = new FileLoaders.IFileLoader[] { new FileLoaders.Hotspots() }; // popup.Show(true); //} //void RunImportLogic(List<Hotspot> importedSpots, Dictionary<string, Hotspot> titleKeys) //{ // var editor = (Editors.SceneEditor)MainScreen.Instance.ActiveEditor; // foreach (var spot in importedSpots) // { // if (titleKeys.ContainsKey(spot.Title)) // { // var oldSpot = titleKeys[spot.Title]; // spot.DebugAppearance.CopyAppearanceTo(oldSpot.DebugAppearance); // spot.Settings = oldSpot.Settings; // } // else // editor.Hotspots.Add(spot); // } // RebuildListBox(); //} #endregion void RebuildProperties(Zone zone) { if (zone.Settings.Count == 0) { propertySurface.IsVisible = false; } else { propertySurface.IsVisible = true; } if (propertySurface.IsVisible) { var drawing = new DrawingSurface(Consoles.ToolPane.PanelWidthControls, (zone.Settings.Count * 2) + 1); previousProperties = new Dictionary <string, string>(); int y = 1; drawing.Print(0, 0, "Zone Settings", Settings.Green); foreach (var setting in zone.Settings) { drawing.Print(0, y, setting.Key.Length > Consoles.ToolPane.PanelWidthControls ? setting.Key.Substring(0, Consoles.ToolPane.PanelWidthControls) : setting.Key, Settings.Yellow); drawing.Print(1, y + 1, setting.Value.Length > Consoles.ToolPane.PanelWidthControls - 1 ? setting.Value.Substring(0, Consoles.ToolPane.PanelWidthControls - 1) : setting.Value, Settings.Grey); previousProperties[setting.Key] = setting.Value; y += 2; } propertySurface.TextSurface = drawing.TextSurface; } }
public MainPage() { InitializeComponent(); DrawingSurface.SetBackgroundContentProvider(_sdInterop.CreateContentProvider()); DrawingSurface.SetBackgroundManipulationHandler(_sdInterop); }
private void DrawingSurface_Loaded(object sender, RoutedEventArgs e) { if (m_d3dInterop == null) { m_d3dInterop = new Direct3DInterop(); // Set window bounds in dips m_d3dInterop.WindowBounds = new Windows.Foundation.Size((float)DrawingSurface.ActualWidth, (float)DrawingSurface.ActualHeight); // Set native resolution in pixels m_d3dInterop.NativeResolution = new Windows.Foundation.Size((float)Math.Floor(DrawingSurface.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(DrawingSurface.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f)); // Set render resolution to the full native resolution m_d3dInterop.RenderResolution = m_d3dInterop.NativeResolution; // Hook-up native component to DrawingSurface DrawingSurface.SetContentProvider(m_d3dInterop.CreateContentProvider(m_username, false)); DrawingSurface.SetManipulationHandler(m_d3dInterop); m_d3dInterop.setWinRtCallback(new WinRtCallback(ProcessCallback)); string preGameUpdate = "{\"" + EVENT_TYPE + "\":" + PRE_GAME + ",\"" + PHASE + "\":" + CONNECTING + "}"; Deployment.Current.Dispatcher.BeginInvoke(() => { m_d3dInterop.onChatReceived(preGameUpdate); WarpClient.GetInstance().AddConnectionRequestListener(m_connectionRequestListener); WarpClient.GetInstance().AddNotificationListener(m_notifyListener); WarpClient.GetInstance().Connect(m_username, AppWarpConstants.APPWARP_AUTH_DATA); }); } }
// Generic way to hook a LineGraphInterop up with a DrawingSurface private LineGraphInterop initializeLineGraph(DrawingSurface canvas) { // Create the LineGraphInterop, the C++/CX component that will draw out to the canvas LineGraphInterop graph = new LineGraphInterop(); // Set window bounds graph.WindowBounds = new Windows.Foundation.Size( (float)canvas.ActualWidth, (float)canvas.ActualHeight ); // Set native/rendering resolution! graph.NativeResolution = new Windows.Foundation.Size( (float)Math.Floor(canvas.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(canvas.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f) ); graph.RenderResolution = graph.NativeResolution; // Notify the canvas who we're hooking up to them canvas.SetContentProvider(graph.CreateContentProvider()); canvas.SetManipulationHandler(graph); // Give back the graph object! return(graph); }
public void late_repeatedly_execute_always() { if (IsGamePaused()) { return; } if (!Cars[0].IsInit) { return; } if (DisplayDebugInfo) { String s1 = StringFormatAGS("Accel: %.2f; Power: %.2f; Brake: %.2f; Drive force: %.2f; Impact: %.2f[", Cars[0].Accelerator, Cars[0].EnginePower, Cars[0].brakePower, Cars[0].driveWheelForce, Cars[0].infoImpact.length()); String s2 = StringFormatAGS("Pos: %.2f, %.2f; Dir: (%.2f) %.2f, %.2f; Velocity: (%.2f) %.2f, %.2f[", Cars[0].position.x, Cars[0].position.y, Cars[0].direction.angle(), Cars[0].direction.x, Cars[0].direction.y, Cars[0].velocity.length(), Cars[0].velocity.x, Cars[0].velocity.y); String s3 = StringFormatAGS("Grip: %.2f; AirRes: %.2f; SlideFrict: %.2f; RollFrict: %.2f; CustomTerRes: %.2f; Antiroll: %.2f, Antislide: %.2f[", Cars[0].driveWheelGrip, Track.AirResistance, Cars[0].envSlideFriction, Cars[0].envRollFriction, Cars[0].envResistance, Cars[0].infoRollAntiforce, Cars[0].infoSlideAntiforce); String s4 = StringFormatAGS("Steer angle: %.2f, Angular velocity: %.2f, Turning accel: (%.2f) %.2f, %.2f", Cars[0].steeringWheelAngle, Cars[0].angularVelocity, Cars[0].turningAccel.length(), Cars[0].turningAccel.x, Cars[0].turningAccel.y); lblCarPos.Text = s1.Append(s2); lblCarPos.Text = lblCarPos.Text.Append(s3); lblCarPos.Text = lblCarPos.Text.Append(s4); } if (DisplayDebugOverlay) { int xoff = -GetViewportX(); int yoff = -GetViewportY(); DrawingSurface ds = debugOver.GetDrawingSurface(); ds.Clear(COLOR_TRANSPARENT); int i = 0; for (i = 0; i < MAX_RACING_CARS; i += 1) { if (!Cars[i].IsInit) { continue; } ds.DrawingColor = Game.GetColorFromRGB(255, 0, 255); float dirx = Cars[i].direction.x * 100.0f; float diry = Cars[i].direction.y * 100.0f; ds.DrawLine(Cars[i].c.x + xoff, Cars[i].c.y + yoff, Cars[i].c.x + FloatToInt(dirx, eRoundNearest) + xoff, Cars[i].c.y + FloatToInt(diry, eRoundNearest) + yoff); ds.DrawingColor = Game.GetColorFromRGB(0, 255, 255); dirx = Cars[i].velocity.x * 0.4f; diry = Cars[i].velocity.y * 0.4f; ds.DrawLine(Cars[i].c.x + xoff, Cars[i].c.y + yoff, Cars[i].c.x + FloatToInt(dirx, eRoundNearest) + xoff, Cars[i].c.y + FloatToInt(diry, eRoundNearest) + yoff); ds.DrawingColor = Game.GetColorFromRGB(255, 0, 0); ds.DrawLine(FloatToInt(Cars[i].collPoint[0].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[0].y, eRoundNearest) + yoff, FloatToInt(Cars[i].collPoint[1].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[1].y, eRoundNearest) + yoff); ds.DrawLine(FloatToInt(Cars[i].collPoint[1].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[1].y, eRoundNearest) + yoff, FloatToInt(Cars[i].collPoint[2].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[2].y, eRoundNearest) + yoff); ds.DrawLine(FloatToInt(Cars[i].collPoint[2].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[2].y, eRoundNearest) + yoff, FloatToInt(Cars[i].collPoint[3].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[3].y, eRoundNearest) + yoff); ds.DrawLine(FloatToInt(Cars[i].collPoint[3].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[3].y, eRoundNearest) + yoff, FloatToInt(Cars[i].collPoint[0].x, eRoundNearest) + xoff, FloatToInt(Cars[i].collPoint[0].y, eRoundNearest) + yoff); } ds.Release(); } if (DisplayDebugAI) { UpdateDebugAI(); } else if (DisplayDebugRace) { UpdateDebugRace(); } LastViewportX = GetViewportX(); LastViewportY = GetViewportY(); }
public void RegisterTemplateVars() { if (this.template == null) { return; } this.template.Register("production.status", () => this.status); this.template.Register("production.blocks", (DrawingSurface ds, string text, DrawingSurface.Options options) => { bool first = true; foreach (KeyValuePair <ProductionBlock, string> blk in this.blockStatus) { if (!first) { ds.Newline(); } string status = blk.Key.Status(); string blockName = $"{blk.Key.block.CustomName}: {status} {(blk.Key.IsIdle() ? blk.Key.IdleTime() : "")}"; Color?colour = DrawingSurface.StringToColour(this.statusDotColour.Get(status)); ds.TextCircle(colour, outline: false).Text(blockName); foreach (string str in blk.Value.Split(this.splitNewline, StringSplitOptions.RemoveEmptyEntries)) { ds.Newline().Text(str); } first = false; } }); }
private void DrawingSurface_Loaded(object sender, RoutedEventArgs e) { if (m_d3dInterop == null) { m_d3dInterop = new Direct3DInterop(); // Set window bounds in dips m_d3dInterop.WindowBounds = new Windows.Foundation.Size( (float)DrawingSurface.ActualWidth, (float)DrawingSurface.ActualHeight ); // Set native resolution in pixels m_d3dInterop.NativeResolution = new Windows.Foundation.Size( (float)Math.Floor(DrawingSurface.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(DrawingSurface.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f) ); // Set render resolution to the full native resolution m_d3dInterop.RenderResolution = m_d3dInterop.NativeResolution; // Hook-up native component to DrawingSurfaceBackgroundGrid DrawingSurface.SetContentProvider(m_d3dInterop.CreateContentProvider()); DrawingSurface.SetManipulationHandler(m_d3dInterop); m_d3dInterop.SetCocos2dEventDelegate(OnCocos2dEvent); EditBoxDelegate editBoxDelegate = new EditBoxDelegate(); EditBoxImpl editBoxImpl = new EditBoxImpl(); editBoxImpl.setMainPage(this); editBoxImpl.setD3dInterop(m_d3dInterop); editBoxDelegate.SetCallback(editBoxImpl); } }
public Scene(DrawingSurface drawingSurface) { _drawingSurface = drawingSurface; // Register for size changed to update the aspect ratio _drawingSurface.SizeChanged += _drawingSurface_SizeChanged; // Get a content manager to access content pipeline contentManager = new ContentManager(null) { RootDirectory = "Content" }; // Initializing variables LightPosition = new Vector3(1, 1, -1); BuildScene03(); //mg = new MeshGeometry(this, TongJi.Geometry3D.SurfaceExamples.ExtrudeWithCaps()); //Camera = new FreeCamera(new Vector3(0, 0, 1.5f * maxHeight), 1, 1, GraphicsDevice); //Camera = new FreeFlyCamera(new Vector3(0, 0, 0), Vector3.UnitX + Vector3.UnitY, Vector3.UnitZ, GraphicsDevice); //Camera = new OneAxisLevelFlyCamera(new Vector3(0, 0, 0), Vector3.UnitX + Vector3.UnitY, GraphicsDevice); //Camera = new TwoAxesLevelFlyCamera(new Vector3(0, 0, 0), Vector3.UnitX + Vector3.UnitY, GraphicsDevice); //Camera = new LevelCamera(new Vector3(0, 0, 1.5f * maxHeight), new Vector3(num * 1.5f * size / 2, num * 1.5f * size / 2, 0), 1, 1000, GraphicsDevice); //Camera = new FixAxisCamera(new Vector3(0, 0, 1.5f * maxHeight), new Vector3(num * 1.5f * size / 2, num * 1.5f * size / 2, maxHeight), new Vector3(num * 1.5f * size / 2, num * 1.5f * size / 2, 0), 0, 1, 1000, GraphicsDevice); //Camera = new ArcBallCamera(new Vector3(0, 0, 1.5f * maxHeight), new Vector3(num * 1.5f * size / 2, num * 1.5f * size / 2, 0), -MathHelper.Pi * 100, MathHelper.Pi * 100, 1, 1000, GraphicsDevice); //Camera = new ArcBallCamera1(Vector3.Zero, 0, 0, -MathHelper.Pi * 100, MathHelper.Pi * 100, 5, 1, 10, GraphicsDevice); Current = this; }
protected View(ILog log, int width, int height, Font font) : base(width, height, font) { Log = log; visualControls = new List <IVisualControl>(); DefaultForeground = Color.White; DefaultBackground = Color.Black; ThemeColors = new Colors { Appearance_ControlNormal = new Cell(Color.White, Color.Black), Appearance_ControlDisabled = new Cell(Color.White, Color.Black) }; var surface = new DrawingSurface(Width, Height) { Position = new Point(0, 0), OnDraw = s => DrawView(s.Surface), CanFocus = false, UseMouse = false, UseKeyboard = false }; Add(surface); }
public void CreateFromSprite(DynamicSprite sprite, int gl_width, int height, int gl_first, int gl_last, int[] offs, int[] widths) { this.Delete(); int sprw = sprite.Width; int sprh = sprite.Height; int in_row = sprw / gl_width; int total = in_row * (sprh / height); total = Maths.Min(total, gl_last - gl_first + 1); if (total <= 0) { return; } this.Glyphs = new DynamicSprite[total]; this.FirstGlyph = gl_first; this.LastGlyph = gl_last; this.GlyphWidth = gl_width; this.Height = height; int i = 0; if (offs != null) { this.Offs = offs; } else { this.Offs = new int[total]; for (i = 0; i < total; i += 1) { this.Offs[i] = 0; } } if (widths != null) { this.Widths = widths; } else { this.Widths = new int[total]; for (i = 0; i < total; i += 1) { this.Widths[i] = gl_width; } } int x = 0; int y = 0; int gl = gl_first; DrawingSurface ds = sprite.GetDrawingSurface(); for (y = 0; y < sprh && gl <= gl_last; y = y + height) { for (x = 0; x < sprw && gl <= gl_last; x = x + gl_width) { DynamicSprite spr = DynamicSprite.CreateFromDrawingSurface(ds, x + this.Offs[gl], y, this.Widths[gl], height); this.Glyphs[gl] = spr; gl += 1; } } ds.Release(); }
private void DrawingSurface_Loaded(object sender, System.Windows.RoutedEventArgs e) { if (_sdInterop == null) { _sdInterop = new SharpDXInterop(); // Set window bounds in dips _sdInterop.WindowBounds = new Windows.Foundation.Size( (float)DrawingSurface.ActualWidth, (float)DrawingSurface.ActualHeight ); // Set native resolution in pixels _sdInterop.NativeResolution = new Windows.Foundation.Size( (float)Math.Floor(DrawingSurface.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(DrawingSurface.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f) ); // Set render resolution to the full native resolution _sdInterop.RenderResolution = _sdInterop.NativeResolution; // Hook-up native component to DrawingSurface DrawingSurface.SetContentProvider(_sdInterop.CreateContentProvider()); DrawingSurface.SetManipulationHandler(_sdInterop); } }
private void SaveAs_Click(object sender, RoutedEventArgs e) { // Configure open file dialog box var dlg = new Microsoft.Win32.SaveFileDialog { InitialDirectory = DrawingSurface.HomeFolder, FileName = Path.GetFileName(DrawingSurface.FileName), DefaultExt = DrawingSurface.EditorMode == EditorMode.AsScheme ? ".scm" : ".shp", Filter = DrawingSurface.EditorMode == EditorMode.AsScheme ? "Мнемосхемы (.scm)|*.scm" : "Фигуры (.shp)|*.shp" }; // Show open file dialog box var result = dlg.ShowDialog(); // Process open file dialog box results if (result != true) { return; } // Save document DrawingSurface.SaveContent(dlg.FileName); SaveContentButton.IsEnabled = false; Title = (DrawingSurface.EditorMode == EditorMode.AsScheme ? "Редактор мнемосхем - " : "Редактор фигур - ") + Path.GetFileName(DrawingSurface.FileName); }
/// <summary> /// Attaches the the painter to the given target panel. /// </summary> /// <param name="targetPanel">The target panel.</param> /// <exception cref="System.InvalidOperationException">Unable to attach to new SwapChainBackgroundPanel: Renderer is already attached to another one!</exception> public void Attach(DrawingSurface targetPanel) { if (m_targetPanel != null) { throw new InvalidOperationException("Unable to attach to new SwapChainBackgroundPanel: Renderer is already attached to another one!"); } // Set default values m_lastRefreshTargetSize = new Size2(0, 0); m_targetPanel = targetPanel; // Attach to SizeChanged event (refresh view resources only after a specific time) m_observerSizeChanged = Observable.FromEventPattern <SizeChangedEventArgs>(m_targetPanel, "SizeChanged") .Throttle(TimeSpan.FromSeconds(0.5)) .ObserveOn(SynchronizationContext.Current) .Subscribe((eArgs) => OnTargetPanelThrottledSizeChanged(eArgs.Sender, eArgs.EventArgs)); m_targetPanel.SizeChanged += OnTargetPanelSizeChanged; m_targetPanel.Loaded += OnTargetPanelLoaded; m_targetPanel.Unloaded += OnTargetPanelUnloaded; // Hook-up native component to DrawingSurface m_drawingInterop = new WP8DrawingSurfaceInterop(this); m_targetPanel.SetContentProvider(m_drawingInterop); //m_targetPanel.SetManipulationHandler(m_drawingInterop); // Define unloading behavior if (VisualTreeHelper.GetParent(m_targetPanel) != null) { m_renderLoop.RegisterRenderLoop(); } //// Register simple mouse movement //InitializeMouseMovement(); }
public override void Draw(GameObject obj, DrawingSurface ds, bool shadow = true) { if (InvisibleInGame || Shp == null) { return; } Size onBridgeOffset = Size.Empty; if (OwnerCollection != null && OwnerCollection.Type == CollectionType.Infantry) { int randomDir = -1; if (_config.ExtraOptions.FirstOrDefault() != null && _config.ExtraOptions.FirstOrDefault().EnableRandomInfantryFacing) { randomDir = Rand.Next(256); } Props.FrameDecider = FrameDeciders.InfantryFrameDecider(Ready_Start, Ready_Count, Ready_CountNext, randomDir); if (obj is OwnableObject && (obj as OwnableObject).OnBridge) { onBridgeOffset = new Size(0, -4 * _config.TileHeight / 2); } } Props.Offset += onBridgeOffset; if (Props.HasShadow && shadow && !Props.Cloakable) { _renderer.DrawShadow(obj, Shp, Props, ds); } _renderer.Draw(Shp, obj, this, Props, ds, Props.Cloakable ? 50 : 0); Props.Offset -= onBridgeOffset; }
public void Create(float perc) { this.Remove(); float sys_w = IntToFloat(system.ViewportWidth); float sys_h = IntToFloat(system.ViewportHeight); this.Width2 = (sys_w * perc / 100.0f) / 2.0f; float w = sys_w * perc / 100.0f; float h = sys_h * perc / 100.0f; this.Width2 = w / 2.0f; this.Height2 = h / 2.0f; float x = CameraData.CameraX - this.Width2; float y = CameraData.CameraY - this.Height2; this.Rect = DynamicSprite.Create(FloatToInt(w), FloatToInt(h), false); DrawingSurface ds = this.Rect.GetDrawingSurface(); ds.Clear(); ds.DrawingColor = Game.GetColorFromRGB(0, 50, 200); ds.DrawFrame(0, 0, ds.Width - 1, ds.Height - 1); ds.DrawString(2, 2, eFontNotalot35Regular12, StringFormatAGS("Zoom: %0.1f%%", perc)); ds.Release(); this.O = Overlay.CreateGraphical(FloatToInt(x, eRoundNearest) - GetViewportX(), FloatToInt(y, eRoundNearest) - GetViewportY(), this.Rect.Graphic, true); }
// Generic way to hook a LineGraphInterop up with a DrawingSurface private LineGraphInterop initializeLineGraph(DrawingSurface canvas) { // Create the LineGraphInterop, the C++/CX component that will draw out to the canvas LineGraphInterop graph = new LineGraphInterop(); // Set window bounds graph.WindowBounds = new Windows.Foundation.Size( (float)canvas.ActualWidth, (float)canvas.ActualHeight ); // Set native/rendering resolution! graph.NativeResolution = new Windows.Foundation.Size( (float)Math.Floor(canvas.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(canvas.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f) ); graph.RenderResolution = graph.NativeResolution; // Notify the canvas who we're hooking up to them canvas.SetContentProvider(graph.CreateContentProvider()); canvas.SetManipulationHandler(graph); // Give back the graph object! return graph; }
// Fields // Methods public void ExtensionMethod_DrawFrame(DrawingSurface thisItem, int x1, int y1, int x2, int y2) { thisItem.DrawLine(x1, y1, x2, y1); thisItem.DrawLine(x2, y1, x2, y2); thisItem.DrawLine(x2, y2, x1, y2); thisItem.DrawLine(x1, y2, x1, y1); }
public void UpdateDebugAIRegions(DrawingSurface ds) { ds.DrawingColor = Game.GetColorFromRGB(255, 255, 255); int i = 0; for (i = 0; i < MAX_RACING_CARS; i += 1) { int veh = RobotsRB[i].vehicleIndex; if (veh < 0) { continue; } VectorF pos = Cars[veh].position; if (pos == null) { continue; } VectorF dir = VectorF.create(50, 0); dir.rotate(RobotsRB[i].targetAngle); dir.add(pos); int x1 = FloatToInt(pos.x, eRoundNearest) - GetViewportX(); int y1 = FloatToInt(pos.y, eRoundNearest) - GetViewportY(); int x2 = FloatToInt(dir.x, eRoundNearest) - GetViewportX(); int y2 = FloatToInt(dir.y, eRoundNearest) - GetViewportY(); ds.DrawLine(x1, y1, x2, y2); } }
public override void Draw(GameObject obj, DrawingSurface ds, bool shadow = true) { if (!obj.Drawable.Props.Cloakable) { ShpRenderer.DrawAlpha(obj, Shp, Props, ds); } }
// Can only be run on the UI thread void createDestinationTarget() { // Don't run if not on the UI thread if (!Container.Dispatcher.HasThreadAccess) { return; } // Don't run if no video is loaded if (Player.PlaybackSession.NaturalVideoWidth == 0) { return; } double containerRatio = Container.ActualWidth / Container.ActualHeight, videoRatio = (double)Player.PlaybackSession.NaturalVideoWidth / Player.PlaybackSession.NaturalVideoHeight; double dW, dH; if (containerRatio < videoRatio) { dH = Container.ActualHeight; dW = dH * videoRatio; } else { dW = Container.ActualWidth; dH = dW / videoRatio; } // Multiply the width and height of the UI container by the device's scale factor var display = DisplayInformation.GetForCurrentView(); int width = (int)MyMath.Round(dW * display.RawPixelsPerViewPixel), height = (int)MyMath.Round(dH * display.RawPixelsPerViewPixel); if (width < 1 || height < 1) { return; } lock (ResourceLock) { if (destinationTarget == null || destinationTarget.Description.Width != width || destinationTarget.Description.Height != height) { destinationTarget?.Dispose(); destinationTarget = new CanvasRenderTarget(CanvasDevice, width, height, 96); if (DrawingSurface == null) { DrawingSurface = CompositionDevice.CreateDrawingSurface2(new SizeInt32() { Width = width, Height = height }, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied); SurfaceBrush.Surface = DrawingSurface; } else { DrawingSurface.Resize(new SizeInt32() { Width = width, Height = height }); } } } }
private void InitBackground() { _backgroundSurface = new DrawingSurface(Width - 2, Height - 2); _backgroundSurface.Position = new Coord(1, 1); _backgroundSurface.Surface.Fill(Color.Blue, Color.Tan, '_'); _backgroundSurface.OnDraw = (surface) => { }; //do nothing Window.Add(_backgroundSurface); }
public void ConfigureScreen(DrawingSurface ds, DrawingSurface.Options options) { ds.surface.Font = options.custom.Get("font", ds.surface.Font); ds.surface.FontSize = options.size == 0f ? ds.surface.FontSize : options.size; ds.surface.TextPadding = options.textPadding ?? ds.surface.TextPadding; ds.surface.ScriptForegroundColor = options.colour ?? ds.surface.ScriptForegroundColor; ds.surface.ScriptBackgroundColor = options.bgColour ?? ds.surface.ScriptBackgroundColor; }
void IInternalGameModule.Prepare(DrawingSurface drawingSurface, IServiceProvider provider) { _drawingSurface = drawingSurface; GraphicsDevice = drawingSurface.GraphicsDevice; SpriteBatch = new SpriteBatch((GraphicsDevice)provider.GetService(typeof(GraphicsDevice))); Content = new ContentManager(provider, _contentDirectory); _updater = new GameUpdater(Update, drawingSurface.Invalidate); }
public CircleToolPanel() { Title = "Circle Status"; statusBox = new DrawingSurface(SadConsoleEditor.Consoles.ToolPane.PanelWidthControls, 2); RedrawBox(); Controls = new ControlBase[] { statusBox }; }
//连边更新 private void GraphEdgeUpdate() { myCurModifyEdge = null; ClearArrows(DrawingSurface); DrawingSurface.ClearVisuals(); SelectNode(NodeListBox.SelectedIndex); UpdateCustomNode(myCurModifyNode.Name); }
private void DrawImage(DrawingSurface control) { control.Surface.Fill(0, 0, control.Width, Color.Gray, Color.Black, '#'); control.Surface.Fill(0, control.Height - 1, control.Width, Color.Gray, Color.Black, '#'); control.Surface.DrawVerticalLine(0, 0, control.Height, new ColoredGlyph('#', Color.Gray, Color.Black)); control.Surface.DrawVerticalLine(control.Width - 1, 0, control.Height, new ColoredGlyph('#', Color.Gray, Color.Black)); control.Surface.DrawImage(1, 1, image, Color.White, backgroundColor.ToXna()); }
//节点更新 private void GraphNodeUpdate() { NodeListBox.Items.Clear(); ClearArrows(DrawingSurface); DrawingSurface.ClearVisuals(); ResetRibbonControls(); FillNodeList(); }
private static void SetMultiSampleAntialiasing(DrawingSurface drawingSurface, int samples) { drawingSurface.CompositionMode = new OffscreenCompositionMode { PreferredMultiSampleCount = samples, RenderTargetUsage = RenderTargetUsage.DiscardContents, PreferredDepthStencilFormat = DepthFormat.Depth24Stencil8, }; }
public override void OnApplyTemplate() { base.OnApplyTemplate(); _image = (StaticImage)GetTemplateChild("ImageContainer"); _surface = (DrawingSurface)GetTemplateChild("SurfaceContainer"); CreateIfReady(); }
public Direct3DRenderProvider() { RunOnUIThread(() => { DrawingSurface = new System.Windows.Controls.DrawingSurface(); DrawingSurface.HorizontalAlignment = HorizontalAlignment.Stretch; DrawingSurface.VerticalAlignment = VerticalAlignment.Stretch; SharpDXRenderProvider = new SharpDXRenderProvider(); SharpDXRenderProvider.Run(DrawingSurface); }); }
/// <summary> /// Initializes a new instance of the <see cref="GameContext" /> class. /// </summary> /// <param name="control">The control.</param> /// <param name="requestedWidth">Width of the requested.</param> /// <param name="requestedHeight">Height of the requested.</param> public GameContext(DrawingSurface control, int requestedWidth = 0, int requestedHeight = 0) { if (control == null) { throw new ArgumentNullException("control"); } Control = control; RequestedWidth = requestedWidth; RequestedHeight = requestedHeight; ContextType = GameContextType.WindowsPhoneXaml; }
public void BindToControl(DrawingSurface drawingSurface) { this.ThrowIfDisposed(); this.ThrowIfBound(); this.surfaceContentProvider = new DrawingSurfaceContentProvider(this); this.manipulationHandler.ManipulationHostChanged += OnManipulationHostChanged; drawingSurface.SetContentProvider(this.surfaceContentProvider); drawingSurface.SetManipulationHandler(this.manipulationHandler); this.IsBound = true; }
private void RunOrSwitchContext() { if (currentSurface != null) LayoutRoot.Children.Remove(currentSurface); currentSurface = new DrawingSurface(); LayoutRoot.Children.Add(currentSurface); if (game.IsRunning) game.Switch(currentSurface); else game.Run(currentSurface); label.Text = "Context nr. " + (index++); }
public Scene(DrawingSurface drawingSurface) { _drawingSurface = drawingSurface; // Register for size changed to update the aspect ratio _drawingSurface.SizeChanged += _drawingSurface_SizeChanged; // Get a content manager to access content pipeline contentManager = new ContentManager(null) { RootDirectory = "Content" }; // Initializing variables cube = new Cube(this, 1.0f); }
public Engine(DrawingSurface drawingSurface) { RootControl = (Control)App.Current.RootVisual; Asserter.AssertIsNotNull(RootControl, "RootControl"); Asserter.AssertIsNotNull(drawingSurface, "drawingSurface"); _drawingSurface = drawingSurface; _content = new ContentManager(_gameServices); _content.RootDirectory = "Content"; _totalGameTime = TimeSpan.Zero; _accumulatedElapsedGameTime = TimeSpan.Zero; _lastFrameElapsedGameTime = TimeSpan.Zero; _targetElapsedTime = TimeSpan.FromTicks(166667L); _drawState = new DrawState(); _updateState = new UpdateState(); _gameServices = new GameServiceContainer(); }
public Scene(DrawingSurface _drawingSurface) { // regist events drawingSurface = _drawingSurface; drawingSurface.SizeChanged += _drawingSurface_SizeChanged; drawingSurface.MouseWheel+=new System.Windows.Input.MouseWheelEventHandler(drawingSurface_MouseWheel); drawingSurface.MouseLeftButtonDown +=new MouseButtonEventHandler(drawingSurface_MouseLeftButtonDown); drawingSurface.MouseLeftButtonUp+=new MouseButtonEventHandler(drawingSurface_MouseLeftButtonUp); drawingSurface.MouseMove+=new MouseEventHandler(drawingSurface_MouseMove); drawingSurface.MouseLeave+=new MouseEventHandler(drawingSurface_MouseLeave); // init contentmanager contentManager = new ContentManager(null) { RootDirectory = "Content" }; //set up camera cameraPosition = new Vector3(0, 120, 120); cameraTarget = Vector3.Zero; // Init variables mesh = new Mesh(this); }
internal override void Initialize(GameContext gameContext) { drawingSurface = (DrawingSurface)gameContext.Control; graphicsDeviceService = (IGraphicsDeviceService)Services.GetService(typeof(IGraphicsDeviceService)); graphicsDeviceManager = (IGraphicsDeviceManager)Services.GetService(typeof(IGraphicsDeviceManager)); }
public void DrawingSurfaceLoad(DrawingSurface drawingSurface) { // Set window bounds in dips m_d3dInterop.WindowBounds = new Windows.Foundation.Size( (float)drawingSurface.ActualWidth, (float)drawingSurface.ActualHeight ); // Set native resolution in pixels m_d3dInterop.NativeResolution = new Windows.Foundation.Size( (float)Math.Floor(drawingSurface.ActualWidth * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f), (float)Math.Floor(drawingSurface.ActualHeight * Application.Current.Host.Content.ScaleFactor / 100.0f + 0.5f) ); // Set render resolution to the full native resolution m_d3dInterop.RenderResolution = m_d3dInterop.NativeResolution; // Hook-up native component to DrawingSurface drawingSurface.SetContentProvider(m_d3dInterop.CreateContentProvider()); drawingSurface.SetManipulationHandler(m_d3dInterop); }
public Game() { GamePadState.Initialize(); root = new ContentControl(); drawingSurface = new DrawingSurface(); root.Content = drawingSurface; drawingSurface.HorizontalAlignment = HorizontalAlignment.Left; drawingSurface.VerticalAlignment = VerticalAlignment.Top; _window = new SilverlightGameWindow(this) as GameWindow; updateGameTime = new GameTime(); drawGameTime = new GameTime(); startingUp = true; drawingSurface.Draw += new EventHandler<DrawEventArgs>(drawingSurface_Draw); drawingSurface.SizeChanged += new SizeChangedEventHandler(drawingSurface_SizeChanged); drawingSurface.Dispatcher.BeginInvoke(() => { _currentState = States.Startup; SetSize(); startingUp = false; }); }
/// <summary> /// Binds the corresponding event handler to the provided <see cref="DrawingSurfaceBackgroundGrid"/> /// </summary> /// <param name="drawingSurface">An instance of <see cref="DrawingSurfaceBackgroundGrid"/> whose events needs to be bound to</param> /// <exception cref="ArgumentNullException">Is thrown if <paramref name="drawingSurface"/> is null</exception> private void BindManipulationEvents(DrawingSurface drawingSurface) { if (drawingSurface == null) throw new ArgumentNullException("drawingSurface"); drawingSurface.SetManipulationHandler(this); // TODO: review if we need to unbind the handlers to avoid memory leaks drawingSurface.Unloaded += (_, __) => drawingSurface.SetManipulationHandler(null); Disposing += (_, __) => drawingSurface.SetManipulationHandler(null); }
private void LoadScene(DrawingSurface drawingSurface, out Scene scene) { scene = new Scene(_camera); if (!_isSoftwareRendered) SetMultiSampleAntialiasing(drawingSurface, 8); if (!Application.Current.IsRunningOutOfBrowser) { HtmlPage.Plugin.Focus(); } }
internal override void Switch(GameContext context) { drawingSurface.Loaded -= DrawingSurfaceOnLoaded; drawingSurface.Unloaded -= DrawingSurfaceUnloaded; drawingSurface.SetContentProvider(null); drawingSurface = (DrawingSurface)context.Control; isInitialized = false; synchronizedTexture.Dispose(); synchronizedTexture = null; drawingSurface.Loaded += DrawingSurfaceOnLoaded; drawingSurface.Unloaded += DrawingSurfaceUnloaded; drawingSurface.SetContentProvider(this); }
internal override void Initialize(GameContext gameContext) { drawingSurface = (DrawingSurface)gameContext.Control; }
public SilverlightUserControl(SilverlightApplication application) { this.application = application; surface = new DrawingSurface(); surface.SizeChanged += sizeChanged; surface.Draw += updateAndRender; this.Content = surface; }
private DrawingSurface surface; // The Xwt Drawing Surface #endregion Fields #region Constructors /// <summary> /// Default constructor /// </summary> public PlotCanvas() : base() { surface = new DrawingSurface (this); // Create Drawing surface }
/// <summary> /// Intializes DirectInput for use on Win32 platforms. /// </summary> /// <param name="window"></param> /// <param name="useKeyboard"></param> /// <param name="useMouse"></param> /// <param name="useGamepad"></param> public override void Initialize( RenderWindow window, bool useKeyboard, bool useMouse, bool useGamepad, bool ownMouse ) { this.useKeyboard = useKeyboard; this.useMouse = useMouse; this.useGamepad = useGamepad; this.ownMouse = ownMouse; this.window = window; drawingSurface = (DrawingSurface)window[ "DRAWINGSURFACE" ]; // initialize keyboard if needed if ( useKeyboard ) { for (var ui = drawingSurface as FrameworkElement; ui != null; ui = ui.Parent as FrameworkElement) { ui.KeyDown += ( s, e ) => { var key = ConvertKeyEnum( e.Key ); keys[ (int)key ] = true; modifiers |= ConvertModifierKeysEnum( e.Key ); if ( useKeyboardEvents ) OnKeyDown( new KeyEventArgs( key, modifiers ) ); //HACK: temporary if (key == KeyCodes.F9) { foreach (var cam in Root.Instance.SceneManager.Cameras) cam.PolygonMode = cam.PolygonMode == PolygonMode.Wireframe ? PolygonMode.Solid : PolygonMode.Wireframe; } }; ui.KeyUp += ( s, e ) => { var key = ConvertKeyEnum( e.Key ); keys[ (int)key ] = false; modifiers &= ~ConvertModifierKeysEnum( e.Key ); if ( useKeyboardEvents ) OnKeyUp( new KeyEventArgs( key, modifiers ) ); }; } } // initialize the mouse if needed if ( useMouse ) { drawingSurface.MouseEnter += ( s, e ) => { var p = e.GetPosition( drawingSurface ); mouseAbsX = (int)p.X; mouseAbsY = (int)p.Y; }; drawingSurface.MouseMove += ( s, e ) => { if ( mouseCaptured ) { var p = e.GetPosition( drawingSurface ); if (true) { mouseRelX = mouseAbsX - (int)p.X; mouseRelY = mouseAbsY - (int)p.Y; mouseAbsX -= mouseRelX; mouseAbsY -= mouseRelY; } else { mouseRelX = (int)p.X - mouseAbsX; mouseRelY = (int)p.Y - mouseAbsY; mouseAbsX += mouseRelX; mouseAbsY += mouseRelY; } } }; drawingSurface.MouseLeftButtonDown += ( s, e ) => { var p = e.GetPosition(drawingSurface); mouseAbsX = (int)p.X; mouseAbsY = (int)p.Y; mouseCaptured = ((UIElement)s).CaptureMouse(); modifiers |= ModifierKeys.MouseButton0; }; drawingSurface.MouseLeftButtonUp += ( s, e ) => { ((UIElement)s).ReleaseMouseCapture(); mouseCaptured = false; modifiers &= ~ModifierKeys.MouseButton0; }; drawingSurface.MouseRightButtonDown += ( s, e ) => modifiers |= ModifierKeys.MouseButton1; drawingSurface.MouseRightButtonUp += ( s, e ) => modifiers &= ~ModifierKeys.MouseButton1; } // we are initialized isInitialized = true; // mouse starts off in the center mouseAbsX = window.Width >> 1; mouseAbsY = window.Height >> 1; }