Specifies whether this contains the same coordinates as the specified .
/// <summary> /// 目标点是否在线段上 (y2-y1)(x-x1) = (y-y1)(x2-x1) /// </summary> public bool Contains(Point pt) { if((pt.Equals(this.pt1)) ||(pt.Equals(this.pt2))) { return true ; } float left = (this.pt2.Y - this.pt1.Y) * (pt.X - this.pt1.X) ; float right = (pt.Y - this.pt1.Y) * (this.pt2.X - this.pt1.X) ; if(Math.Abs(left - right) < GeometryHelper.ToleranceForFloat) { return false ; } if(! GeometryHelper.IsInRegion(pt.X ,this.pt1.X ,this.pt2.X)) { return false ; } if(! GeometryHelper.IsInRegion(pt.Y ,this.pt1.Y ,this.pt2.Y)) { return false ; } return true ; }
public override bool IsInDrawObject(System.Drawing.Point point) { var maxLength = Math.Max(Math.Abs(relativeStartPoint.X - relativeEndPoint.X), Math.Abs(relativeStartPoint.Y - relativeEndPoint.Y)); if (maxLength == 0) { return(point.Equals(relativeStartPoint)); } var xIncrement = (float)(relativeEndPoint.X - relativeStartPoint.X) / (3F * (float)maxLength); var yIncrement = (float)(relativeEndPoint.Y - relativeStartPoint.Y) / (2F * (float)maxLength); var currX = (float)relativeStartPoint.X; var currY = (float)(relativeStartPoint.Y + relativeEndPoint.Y) / 2; if (checkInDrawObject(point, xIncrement, yIncrement, currX, currY)) { return(true); } currX = (float)thirdX; currY = (float)relativeEndPoint.Y; xIncrement = 2 * (float)(relativeEndPoint.X - relativeStartPoint.X) / (3F * (float)maxLength); yIncrement = (float)(relativeStartPoint.Y - relativeEndPoint.Y) / (float)maxLength; if (checkInDrawObject(point, xIncrement, yIncrement, currX, currY)) { return(true); } return(false); }
public static bool CheckIfSegmentIntersectInteriorSegment(Segment s) { foreach (var seg in SegmentsManager.InteriorSegments) { if (!s.A.X.Equals(seg.A.X) && !s.A.X.Equals(seg.B.X) && !s.B.X.Equals(seg.A.X) && !s.B.X.Equals(seg.B.X)) { VerificaIntersectia = new Intersectie(seg.A, seg.B, s.A, s.B); if (VerificaIntersectia.Intersectation()) { var pt = new Point(Convert.ToInt32(VerificaIntersectia.x), Convert.ToInt32(VerificaIntersectia.y)); if (!(pt.Equals(s.A) || pt.Equals(s.B))) return true; } } } return false; }
public void huir(MouseEventArgs e,Point puntoAntiguoRaton,int heightForm,int widthForm) { int pixlMovimiento = 0;//Cantidad de pixeles que se va a mover por cada movimiento del ratón. Point nuevoPunto = new Point(posicion.X, posicion.Y); if (Math.Abs(posicion.X - e.X) < Math.Abs(posicion.X - puntoAntiguoRaton.X) || Math.Abs(posicion.Y - e.Y) < Math.Abs(posicion.Y - puntoAntiguoRaton.Y)) /*se comprueba que el ratón se haya acercado a la persona*/ { if (!puntoAntiguoRaton.Equals(e.Location))/*se comprueba que el ratón se haya movido*/ { /* dependiendo de la distancia,se cambia lo que se mueve*/ if (distancia(posicion, e.Location) > vista) { pixlMovimiento = 0; } if (distancia(posicion, e.Location) < vista) { pixlMovimiento = velocidadAndar; } if (distancia(posicion, e.Location) < vista/2) { pixlMovimiento = velocidadCorrer; } /* Se comprueba la posición del ratón con respecto al botón para que se mueva huyendo de él*/ if (posicion.X > e.Location.X) { nuevoPunto.X = nuevoPunto.X + pixlMovimiento; } else { nuevoPunto.X = nuevoPunto.X - pixlMovimiento; } if (posicion.Y > e.Location.Y) { nuevoPunto.Y = nuevoPunto.Y + pixlMovimiento; } else { nuevoPunto.Y = nuevoPunto.Y - 1; } if (nuevoPunto.X > 10 && nuevoPunto.Y > 10 && nuevoPunto.Y < heightForm - 10 - tamanio && nuevoPunto.X < widthForm - 10 - tamanio) { posicion = nuevoPunto; boton.Location = posicion; } } } }
private void SpatialViewer_GDI_MouseUp(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Debug.WriteLine("MouseUp: {0}/{1} {2}/{3}", e.X, e.Y, e.Location.X, e.Location.Y); _isMouseDown = false; if (!_mouseDownPoint.Equals(e.Location)) { this.InvalidateWrapper(true, true); } } }
private static async Task Process(Dictionary <string, Mat> list) { foreach (var image in list.Values) { Mat screenshot = Utils.TakeScreenshot(); Point match = Utils.CompareImages(screenshot, image); screenshot.Dispose(); if (!match.Equals(Point.Empty)) { Utils.Print("Found match at: " + match, ConsoleColor.Cyan); Utils.MoveMouse(match); Utils.LeftClick(); Utils.MoveMouse(positionHolder); return; } await Task.Delay(1000); } }
/// <summary> /// On dragging, we updates the cursor and displays an insertion marker. /// </summary> /// <param name="e"></param> protected override void OnDragOver(DragEventArgs e) { base.OnDragOver(e); var draggedTab = GetDraggedTab(e); // Retrieve the point in client coordinates Point pt = new Point(e.X, e.Y); pt = PointToClient(pt); if (pt.Equals(m_lastPoint)) return; m_lastPoint = pt; // Make sure there is a TabPage being dragged. if (draggedTab == null) { e.Effect = DragDropEffects.None; return; } // Retrieve the dragged page. If same as dragged page, return var hoveredTab = GetTabPageAt(pt); if (draggedTab == hoveredTab) { e.Effect = DragDropEffects.None; m_markerIndex = -1; return; } // Get the old and new marker indices bool onLeft; int newIndex = GetMarkerIndex(draggedTab, pt, out onLeft); var oldIndex = m_markerIndex; m_markerIndex = newIndex; m_markerOnLeft = onLeft; // Updates the new tab index if (oldIndex != newIndex) { UpdateMarker(); } e.Effect = DragDropEffects.Move; }
public void LeftMouseUp(ref EditorData data, Point gridPosition) { if(gridPosition.Equals(_mInitial)) { if(!data.CtrlHeld) data.SelectedEntities.Clear(); var selected = data.Level.SelectEntity(gridPosition); if (selected != null && !data.SelectedEntities.Contains(selected)) data.SelectedEntities.Add(selected); else if (selected == null && !data.CtrlHeld) data.SelectedEntities.Clear(); } if (data.SelectedEntities.Count > 0) { data.Level.MoveEntity(data.SelectedEntities, new Size(Point.Subtract(_mInitial, new Size(gridPosition))), false); data.Level.MoveEntity(data.SelectedEntities, new Size(Point.Subtract(gridPosition, new Size(_mInitial))), true); } _mouseDown = false; }
private static bool CheckAndCreatePoint(int x, int TransitionPositionY, List<Vector> vectorlist,ref Point lastPoint, int countA, int countMiddle, int countB, bool blackFirst, bool inverse) { //Transition does fit, and one point does already exist if ((countA >= 5) && (countMiddle <= 2) && (countB >= 5)&&(!lastPoint.Equals(new Point(0,0)))) { //Create vector Point p = new Point(x, TransitionPositionY); if (!inverse) { //The vector is aligned, so that the white side is on the left (looking in the vectors direction) if (blackFirst) { Vector v = new Vector(p.X - lastPoint.X, p.Y - lastPoint.Y); vectorlist.Add(v); } else { Vector v = new Vector(lastPoint.X - p.X, lastPoint.Y - p.Y); vectorlist.Add(v); } } else { //Inverse the alingnement (because the direction would be the opposite with the vertical methods if (blackFirst) { Vector v = new Vector(lastPoint.X - p.X, lastPoint.Y - p.Y); vectorlist.Add(v); } else { Vector v = new Vector(p.X - lastPoint.X, p.Y - lastPoint.Y); vectorlist.Add(v); } } lastPoint = new Point(x, TransitionPositionY); return true; } else if ((countA >= 5) && (countMiddle <= 2) && (countB >= 5)) { //The transition does fit, but no point exists: create point lastPoint = new Point(x, TransitionPositionY); } return false; }
// Perform all startup initialization private void MainWindow_OnLoaded(object senderUnused, RoutedEventArgs eUnused) { var handle = new WindowInteropHelper(this).Handle; var initialStyle = MainWindow.GetWindowLong(handle, -20); MainWindow.SetWindowLong(handle, -20, initialStyle | 0x20 | 0x80000); var wpfDpi = PresentationSource.FromVisual(this)?.CompositionTarget?.TransformToDevice.M11; this.dpiScale = 1f / (float)wpfDpi.GetValueOrDefault(1); // Screen size and positioning init this.UpdateMonikaScreen(); this.SetupScale(); this.SetPosition(this.MonikaScreen); // Hook shutdown event SystemEvents.SessionEnding += (sender, args) => { MonikaiSettings.Default.IsColdShutdown = false; MonikaiSettings.Default.Save(); }; // Wakeup events SystemEvents.SessionSwitch += (sender, e) => { if (e.Reason == SessionSwitchReason.SessionLock) { this.screenIsLocked = true; } else if (e.Reason == SessionSwitchReason.SessionUnlock) { this.screenIsLocked = false; } }; SystemEvents.PowerModeChanged += (sender, e) => { if (e.Mode == PowerModes.Resume) { Task.Run(async() => { while (this.screenIsLocked) { await Task.Delay(500); } this.Say(new[] { new Expression("ZZZZZZzzzzzzzzz..... huh?", "q"), new Expression("Sorry, I must have fallen asleep, ahaha~", "n") }); }); } }; // Start animation var animationLogo = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(1.5))); animationLogo.AutoReverse = true; var animationFadeMonika = new DoubleAnimation(0.0, 1.0, new Duration(TimeSpan.FromSeconds(1.5))); animationFadeMonika.BeginTime = TimeSpan.FromSeconds(0.5); animationLogo.Completed += (sender, args) => { var fadeImage = new BitmapImage(); fadeImage.BeginInit(); if (MainWindow.IsNight) { fadeImage.UriSource = new Uri("pack://application:,,,/MonikAI;component/monika/1a-n.png"); } else { fadeImage.UriSource = new Uri("pack://application:,,,/MonikAI;component/monika/1a.png"); } fadeImage.EndInit(); this.backgroundPicture.Source = fadeImage; var clock = animationFadeMonika.CreateClock(); this.backgroundPicture.ApplyAnimationClock(UIElement.OpacityProperty, clock); }; // Blinking behaviour animationFadeMonika.Completed += async(sender, args) => { this.SetMonikaFace("a"); this.facePicture.Opacity = 1.0; // Start speech-thread Task.Run(async() => await this.SpeakingThread()); if (File.Exists("firstlaunch.txt") || Environment.GetCommandLineArgs().Contains("/firstlaunch")) { try { File.Delete("firstlaunch.txt"); } catch { // ignored } MonikaiSettings.Default.FirstLaunch = true; MonikaiSettings.Default.Save(); } this.updaterInitTask?.Wait(); await this.updater.PerformUpdate(this); this.UpdateMonikaScreen(); #if DEBUG MessageBox.Show("This is a testing build, please do me the favor and don't distribute it."); #endif // Startup logic if (MonikaiSettings.Default.FirstLaunch) { MessageBox.Show( "Quick note: If you want Monika to react to your web browsing, you need to install the correct extension from the website, \"monik.ai\".\r\n\r\nThat's it from me, I'll let Monika talk from now on :)\r\n\r\n- PiMaker and all the nice people helping develop this", "Welcome!"); this.settingsWindow.ShowDialog(); this.Say(new[] { new Expression("{name}, is that you?", "d"), new Expression("It's really you, huh?", "b"), new Expression("I'm so happy to see you again!", "k"), new Expression("Wait, where am I? This is not the literature club...", "p"), new Expression("This looks like... your desktop! I'm right here with you!", "j"), new Expression("Well, as close as I will get for now...", "o"), new Expression("Anyway, looks like someone was nice enough to make me a little window!", "d"), new Expression("Be sure to thank them for me, okay?", "k"), new Expression("Ah, wait a second.", "c"), new Expression( "I see... Well, if you want me to go away for now, you can use CTRL-SHIFT-F12, okay?", "b"), new Expression("But you wouldn't do that, right?", "r"), new Expression("Okay, I guess that's it for now. Don't forget, I'm watching you! Ahaha~") }); MonikaiSettings.Default.FirstLaunch = false; } else if (DateTime.Today.Month == 4 && DateTime.Today.Day == 1 && !Debugger.IsAttached) { this.Say(new[] { new Expression("Hi {name}!", "b"), new Expression("Remember the update that I just installed?", "d"), new Expression("Well, let's just say it included something *really* nice~", "k"), new Expression("Here, let me show you!", "j").AttachEvent((o, eventArgs) => { var os = MonikaiSettings.Default.ScaleModifier; MonikaiSettings.Default.ScaleModifier *= 2.5; this.Dispatcher.Invoke(this.SetupScale); MonikaiSettings.Default.ScaleModifier = os; Task.Delay(1000).Wait(); var r = new Random(); for (var i = 0; i < 12; i++) { this.Dispatcher.Invoke(() => { this.backgroundPicture.Source = r.Next(0, 2) == 0 ? this.backgroundNight : this.backgroundDay; var faceImg = new BitmapImage(); faceImg.BeginInit(); if (r.Next(0, 2) == 0) { faceImg.UriSource = new Uri("pack://application:,,,/MonikAI;component/monika/j.png"); } else { faceImg.UriSource = new Uri("pack://application:,,,/MonikAI;component/monika/j-n.png"); } faceImg.EndInit(); this.facePicture.Source = faceImg; }); Task.Delay(r.Next(100, 250)).Wait(); } }), new Expression("Just a second my love...", "d").AttachEvent((o, eventArgs) => { this.Dispatcher.Invoke(MainWindow.DoTheThing); Task.Delay(5500).Wait(); this.Dispatcher.Invoke(this.SetupScale); }), new Expression("...", "q"), new Expression("Why does this never work?!", "o"), new Expression("Oh well, back to normal I guess... Sorry, {name}.", "r") }); } else { if (MonikaiSettings.Default.IsColdShutdown) { // Sorry Monika, but if we're debugging you this one gets annoying #if !DEBUG this.Say(new[] { new Expression("Hey! Don't just turn me off without warning! That hurts...", "p") }); #endif } else { MonikaiSettings.Default.IsColdShutdown = true; MonikaiSettings.Default.Save(); } if ((DateTime.Now - MonikaiSettings.Default.LastStarted).TotalDays > 7) { this.Say(new[] { new Expression( "Don't forget, if you want me to leave just press " + MonikaiSettings.Default.HotkeyExit + "!", "i"), new Expression("But you're not going to do that, right?", "o") }); } } // Parse startup CSV var parser = new CSVParser(); var csv = parser.GetData("Startup"); var parsed = parser.ParseData(csv); var startupExpression = parsed.Select(x => x.ResponseChain) .Concat(DateTime.Today.DayOfWeek == DayOfWeek.Wednesday ? new List <List <Expression> > { new List <Expression> { new Expression("It is Wednesday, my dudes!", "k") } } : new List <List <Expression> >()).ToList().Sample(); this.Say(new[] { new Expression("Hi there, {name}~") }.Concat(startupExpression)); if ((DateTime.Now - MonikaiSettings.Default.LastStarted).TotalDays > 2.5) { this.Say(new[] { new Expression("I was waiting for you...", "m"), new Expression("Being alone on your disk is reeeally boring.", "q") }); } // No idea where the date comes from, someone mentioned it in the spreadsheet. Seems legit. if (DateTime.Now.Month == 9 && DateTime.Now.Day == 22) { // Hey {name}, guess what? 3b It's my birthday today! 2b Happy Birthday to me! k this.Say(new[] { new Expression("Hey {name}, guess what?", "b"), // What? new Expression("It's my birthday today!", "b"), // Really?! new Expression("Happy Birthday to me!", "k") // To you too, Monika! }); } MonikaiSettings.Default.LastStarted = DateTime.Now; MonikaiSettings.Default.Save(); // Start the rest server UrlServer.StartServer(); this.RegisterBehaviours(this, null); // Blinking and Behaviour logic var eyesOpen = "a"; var eyesClosed = "j"; var random = new Random(); await Task.Run(async() => { var nextBlink = DateTime.Now + TimeSpan.FromSeconds(random.Next(7, 50)); while (this.applicationRunning) { if (this.behaviours != null) { foreach (var behaviour in this.behaviours) { behaviour.Update(this); } } if (DateTime.Now >= nextBlink) { // Check if currently speaking, only blink if not in dialog if (!this.Speaking) { this.SetMonikaFace(eyesClosed); await Task.Delay(100); this.SetMonikaFace(eyesOpen); } nextBlink = DateTime.Now + TimeSpan.FromSeconds(random.Next(7, 50)); } await Task.Delay(250); } }); }; // Startup this.backgroundPicture.BeginAnimation(UIElement.OpacityProperty, animationLogo); Task.Run(async() => { try { var prev = new Point(); var rectangle = new Rectangle(); await this.Dispatcher.InvokeAsync(() => { rectangle = new Rectangle((int)this.Left, (int)this.Top, (int)this.Width, (int)this.Height); }); while (this.applicationRunning) { var point = new Point(); MainWindow.GetCursorPos(ref point); point.X = (int)(point.X * this.dpiScale); point.Y = (int)(point.Y * this.dpiScale); if (!point.Equals(prev)) { prev = point; var opacity = 1.0; const double MIN_OP = 0.125; const double FADE = 175; if (this.settingsWindow == null || !this.settingsWindow.IsPositioning) { if (rectangle.Contains(point)) { opacity = MIN_OP; } else { if (point.Y <= rectangle.Bottom) { if (point.Y >= rectangle.Y) { if (point.X < rectangle.X && rectangle.X - point.X < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (rectangle.X - point.X) / FADE); } else if (point.X > rectangle.Right && point.X - rectangle.Right < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (point.X - rectangle.Right) / FADE); } } else if (point.Y < rectangle.Y) { if (point.X >= rectangle.X && point.X <= rectangle.Right) { if (rectangle.Y - point.Y < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (rectangle.Y - point.Y) / FADE); } } else if (rectangle.X > point.X || rectangle.Right < point.X) { var distance = Math.Sqrt( Math.Pow( (point.X < rectangle.X ? rectangle.X : rectangle.Right) - point.X, 2) + Math.Pow(rectangle.Y - point.Y, 2)); if (distance < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, distance / FADE); } } } } } } this.Dispatcher.Invoke(() => { this.Opacity = opacity; }); } var hidePressed = false; var exitPressed = false; var settingsPressed = false; var buttonPressed = false; // Set position anew to correct for fullscreen apps hiding taskbar this.Dispatcher.Invoke(() => { this.SetPosition(this.MonikaScreen); rectangle = new Rectangle((int)this.Left, (int)this.Top, (int)this.Width, (int)this.Height); // Detect exit key combo hidePressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeyHide); exitPressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeyExit); settingsPressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeySettings); buttonPressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeyButton); }); if (hidePressed && (DateTime.Now - this.lastKeyComboTime).TotalSeconds > 2) { this.lastKeyComboTime = DateTime.Now; if (this.Visibility == Visibility.Visible) { this.Dispatcher.Invoke(this.Hide); //var expression = // new Expression( // "Okay, see you later {name}! (Press again for me to return)", "b"); //expression.Executed += (o, args) => { this.Dispatcher.Invoke(this.Hide); }; //this.Say(new[] {expression}); } else { this.Dispatcher.Invoke(this.Show); } } if (exitPressed) { Exit(); } if (settingsPressed) { Setting(); } if (buttonPressed) { this.Dispatcher.Invoke(() => { buttonWindow.Close(); this.buttonWindow = new ButtonWindow(this); this.buttonWindow.Show(); }); } await Task.Delay(MonikaiSettings.Default.PotatoPC ? 100 : 32); } } catch (Exception) { // ignored } }); }
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { var handle = new WindowInteropHelper(this).Handle; var initialStyle = MainWindow.GetWindowLong(handle, -20); MainWindow.SetWindowLong(handle, -20, initialStyle | 0x20 | 0x80000); Task.Run(async() => { try { var prev = new Point(); var rectangle = new Rectangle(); await this.Dispatcher.InvokeAsync(() => { rectangle = new Rectangle((int)this.Left, (int)this.Top, (int)this.Width, (int)this.Height); }); while (this.applicationRunning) { var point = new Point(); MainWindow.GetCursorPos(ref point); if (!point.Equals(prev)) { prev = point; var opacity = 1.0; const double MIN_OP = 0.125; const double FADE = 175; if (rectangle.Contains(point)) { opacity = MIN_OP; } else { if (point.Y <= rectangle.Bottom) { if (point.Y >= rectangle.Y) { if (point.X < rectangle.X && rectangle.X - point.X < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (rectangle.X - point.X) / FADE); } else if (point.X > rectangle.Right && point.X - rectangle.Right < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (point.X - rectangle.Right) / FADE); } } else if (point.Y < rectangle.Y) { if (point.X >= rectangle.X && point.X <= rectangle.Right) { if (rectangle.Y - point.Y < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (rectangle.Y - point.Y) / FADE); } } else if (rectangle.X > point.X || rectangle.Right < point.X) { var distance = Math.Sqrt( Math.Pow( (point.X < rectangle.X ? rectangle.X : rectangle.Right) - point.X, 2) + Math.Pow(rectangle.Y - point.Y, 2)); if (distance < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, distance / FADE); } } } } } this.Dispatcher.Invoke(() => { this.Opacity = opacity; }); } // Set position anew to correct for fullscreen apps hiding taskbar this.Dispatcher.Invoke(this.SetPositionBottomRight); // Detect exit key combo var keysPressed = false; this.Dispatcher.Invoke( () => keysPressed = (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) && Keyboard.IsKeyDown(Key.F12)); if (keysPressed && (DateTime.Now - this.lastKeyComboTime).TotalSeconds > 2) { this.lastKeyComboTime = DateTime.Now; if (this.Visibility == Visibility.Visible) { var expression = new Expression( "Okay, see you later " + Environment.UserName + "! (Press again for me to return)", "b"); expression.Executed += (o, args) => { this.Dispatcher.Invoke(this.Hide); }; this.Say(new[] { expression }); } else { this.Dispatcher.Invoke(this.Show); } } await Task.Delay(32); } } catch (Exception) { // ignored } }); }
private void ReDrawCards(ref ArrayList al, ref Point Location) { //填充牌型(所有充填) /* 放弃使用 选中抬高 int x = ((Card)al[0]).location.X; int w = 15 * al.Count + 71; //间距15像素*起始张数+71单张宽度 int y = ((Card)al[0]).location.Y - 20; //选中后抬高20像素 int h = 96 + 20; */ Point loc = new Point(Location.X, Location.Y); if (al.Count == 0) { this.CreateGraphics().DrawImage(mycards_under, loc); return; } int x = ((Card)al[0]).location.X; int y = ((Card)al[0]).location.Y; //int w = 15 * (52-discard)/2 + 71; int i = 0; if (Location.Equals(location)) { this.CreateGraphics().DrawImage(mycards_under, location); for (i = 9; i <= al.Count + 8; i++) {//调整cards的横坐标 ((Card)al[i - 9]).Init(-1, loc); loc.X += 15; } } for (i = 0; i < al.Count; i++) { this.CreateGraphics().DrawImage(((Card)al[i]).cardimg, ((Card)al[i]).location); } }
protected override void OnPaint(PaintEventArgs e) { var g = e.Graphics; g.Clear(Map.IsOver ? (Map.Died ? Color.LightCoral : Color.Gold) : Color.White); for (var x = 0; x < Map.Width; x++) { for (var y = 0; y < Map.Height; y++) { var p = new Point(x, y); var occupation = Map.Filled[x, y] ? Occupation.Occupied : Map.Unit.Members.Any(m => m.Equals(p)) ? Occupation.Unit : Occupation.Empty; DrawHexagon(g, x, y, penTypes[occupation], brushTypes[occupation], p.Equals(Map.Unit.Position.Point)); } } if (requestedLocation != null && !mapHistory.Playing) { IEnumerable<Directions> path = null; path = mapHistory.Solver.Finder.GetPath( Map, requestedLocation.Position); bool exist = path != null; foreach (var member in requestedLocation.Members) { DrawHexagon(e.Graphics, member.X, member.Y, Pens.Black, exist ? Brushes.Aqua : Brushes.MistyRose, false); } } foreach (var v in mapHistory.Suggestions.OraclePresense) DrawHexagon(e.Graphics, v.X, v.Y, Pens.Black, Brushes.Lime, false); if (mapHistory.Suggestions != null) { var s = mapHistory.Suggestions.GetCurrentSuggestion(); if (s!= null) { var sugg = new PositionedUnit(mapHistory.Suggestions.Unit, s.Position); foreach(var member in sugg.Members) { DrawHexagon(e.Graphics, member.X, member.Y, Pens.Black, Brushes.Yellow, false); } } } }
private void MoveExact(int x, int y) { float effectiveX = x / (POWER * 1f), effectiveY = y / (POWER * 1f); var actualX = (int)Math.Floor((float)(x + (POWER / 2)) / POWER); var actualY = (int)Math.Floor((float)(y + (POWER / 2)) / POWER); var targets = GetHitTargets(); var sourceLeft = effectiveX * _map.TileSize; var sourceTop = effectiveY * _map.TileSize; var sourceRect = new RectangleF(sourceLeft, sourceTop, _map.TileSize, _map.TileSize); var collisions = new List<Point>(); var possible = new List<Point>(); foreach (var t in targets) { int targetX = actualX + t.X, targetY = actualY + t.Y; var targetRect = new RectangleF(targetX * _map.TileSize, targetY * _map.TileSize, _map.TileSize, _map.TileSize); var movable = Movable(targetX, targetY); var intersects = sourceRect.IntersectsWith(targetRect); if (!movable && intersects) { collisions.Add(new Point(targetX, targetY)); } else { possible.Add(new Point(targetX, targetY)); } } if (collisions.Count == 0) { SetDirection(DirectionX, DirectionY); X = actualX; Y = actualY; ExactX = x; ExactY = y; } else { var candidates = new List<Tuple<int, int, Point>>(); Tuple<int, int, Point> candidate = null; var p1 = new Point(actualX + DirectionX, actualY); var p2 = new Point(actualX, actualY + DirectionY); foreach (var nextMove in possible) { if (p1.Equals(nextMove)) { candidates.Add(Tuple.Create(DirectionX, 0, p1)); } if (p2.Equals(nextMove)) { candidates.Add(Tuple.Create(0, DirectionY, p2)); } } if (candidates.Count == 1) { candidate = candidates[0]; } else if (candidates.Count == 2) { int minDistance = Int32.MaxValue; for (int i = 0; i < candidates.Count; ++i) { var targetCandidate = candidates[i]; int xs = (ExactX - candidates[i].Item3.X * POWER); int ys = (ExactY - candidates[i].Item3.Y * POWER); int distance = xs * xs + ys * ys; if (distance < minDistance) { minDistance = distance; candidate = targetCandidate; } } } if (candidate != null) { var diffX = candidate.Item3.X * POWER - ExactX; var diffY = candidate.Item3.Y * POWER - ExactY; var absX = Math.Abs(diffX); var absY = Math.Abs(diffY); int effectiveDirectionX = 0; int effectiveDirectionY = 0; if (absX == 100) { effectiveDirectionX = 0; } else { effectiveDirectionX = Math.Sign(diffX); } if (absY == 100) { effectiveDirectionY = 0; } else { effectiveDirectionY = Math.Sign(diffY); } if (effectiveDirectionX == 0 && effectiveDirectionY == 0) { effectiveDirectionX = candidate.Item1; effectiveDirectionY = candidate.Item2; } SetDirection(effectiveDirectionX, effectiveDirectionY); ExactX += DELTA * effectiveDirectionX; X = actualX; ExactY += DELTA * effectiveDirectionY; Y = actualY; } else { var diffY = (collisions[0].Y * POWER - ExactY); var diffX = (collisions[0].X * POWER - ExactX); var absX = Math.Abs(diffX); var absY = Math.Abs(diffY); int effectiveDirectionX = 0; int effectiveDirectionY = 0; if (absX >= 35 && absX < 100) { effectiveDirectionX = -Math.Sign(diffX); } if (absY >= 35 && absY < 100) { effectiveDirectionY = -Math.Sign(diffY); } SetDirection(effectiveDirectionX, effectiveDirectionY); ExactX += DELTA * effectiveDirectionX; ExactY += DELTA * effectiveDirectionY; } } }
/// <summary> /// mark obstacles and costs in the routing grid. /// </summary> private void markObstacles(RectangleF bounds, Arrow arrow, int cols, int rows) { RoutingOptions rop = flowChart.RoutingOptions; float gridSize = rop.GridSize; byte ccost = rop.CrossingCost; foreach (ChartObject obj in flowChart.Objects) { // if there is a crossing cost assigned, mark arrows in the route grid if (obj is Arrow && ccost > 0) { if (obj == arrow) continue; Arrow link = obj as Arrow; // at this time we handle only asPerpendicular links if (link.Style == ArrowStyle.Cascading) { PointF cp1 = link.ControlPoints[0]; Point gp1 = new Point( (int)((cp1.X - bounds.Left) / gridSize), (int)((cp1.Y - bounds.Top) / gridSize)); // iterate over all segments for (int i = 0; i < link.ControlPoints.Count - 1; ++i) { PointF cp2 = link.ControlPoints[i + 1]; Point gp2 = new Point( (int)((cp2.X - bounds.Left) / gridSize), (int)((cp2.Y - bounds.Top) / gridSize)); if (!gp1.Equals(gp2)) { if (gp1.X == gp2.X) { // vertical segment if (gp1.X >= 0 && gp1.X < cols) { int miny = Math.Min(gp1.Y, gp2.Y); miny = Math.Max(0, miny); int maxy = Math.Max(gp1.Y, gp2.Y); maxy = Math.Min(rows - 1, maxy); for (int y = miny; y <= maxy; ++y) if (costGrid[gp1.X, y] < ccost) costGrid[gp1.X, y] = ccost; } } else { // horizontal segment if (gp1.Y >= 0 && gp1.Y < rows) { int minx = Math.Min(gp1.X, gp2.X); minx = Math.Max(0, minx); int maxx = Math.Max(gp1.X, gp2.X); maxx = Math.Min(cols - 1, maxx); for (int x = minx; x <= maxx; ++x) if (costGrid[x, gp1.Y] < ccost) costGrid[x, gp1.Y] = ccost; } } } gp1 = gp2; } } continue; } if (!(obj is Node)) continue; Node node = obj as Node; if (!node.Obstacle) continue; if (node.MasterGroup != null && node.MasterGroup.MainObject == arrow) continue; RectangleF nodeRect = node.getRotatedBounds(); if (bounds.IntersectsWith(nodeRect)) { RectangleF intrRect = bounds; intrRect.Intersect(nodeRect); Point ptStart = new Point( (int)((intrRect.Left - bounds.Left) / gridSize), (int)((intrRect.Top - bounds.Top) / gridSize)); Point ptEnd = new Point( (int)((intrRect.Right - bounds.Left) / gridSize), (int)((intrRect.Bottom - bounds.Top) / gridSize)); if (ptStart.X < 0) ptStart.X = 0; if (ptStart.Y < 0) ptStart.Y = 0; if (ptEnd.X >= cols) ptEnd.X = cols - 1; if (ptEnd.Y >= rows) ptEnd.Y = rows - 1; // mark node interior as obstacle for (int c = ptStart.X; c <= ptEnd.X; ++c) for (int r = ptStart.Y; r <= ptEnd.Y; ++r) costGrid[c, r] = 255; // mark surrounding area with any cost assigned // going lineary down to the outside directions if (rop.NodeVicinityCost == 0) continue; for (int i = 1; i <= rop.NodeVicinitySize / gridSize; ++i) { byte cost = (byte)(rop.NodeVicinityCost / i); int minc = Math.Max(0, ptStart.X - i); int maxc = Math.Min(cols - 1, ptEnd.X + i); int minr = Math.Max(0, ptStart.Y - i); int maxr = Math.Min(rows - 1, ptEnd.Y + i); // top side int r = ptStart.Y - i; if (r >= 0) { for (int c = minc; c <= maxc; ++c) if (costGrid[c, r] < cost) costGrid[c, r] = cost; } // bottom side r = ptEnd.Y + i; if (r <= maxr) { for (int c = minc; c <= maxc; ++c) if (costGrid[c, r] < cost) costGrid[c, r] = cost; } // left side int cc = ptStart.X - i; if (cc >= 0) { for (r = minr; r <= maxr; ++r) if (costGrid[cc, r] < cost) costGrid[cc, r] = cost; } // right side cc = ptEnd.X + i; if (cc <= maxc) { for (r = minr; r <= maxr; ++r) if (costGrid[cc, r] < cost) costGrid[cc, r] = cost; } } } } }
private void Form1_MouseMove(object sender, MouseEventArgs e) { Point raton = new Point(e.Location.X, e.Location.Y); if (primero) { primero = false; RATON.X = e.X; RATON.Y = e.Y; } foreach (Persona p in listaPersonas) { if (!raton.Equals(RATON) && (Math.Abs(p.getPosicion().X - e.X) < Math.Abs(p.getPosicion().X - RATON.X) || Math.Abs(p.getPosicion().Y - e.Y) < Math.Abs(p.getPosicion().Y - RATON.Y)) ) { p.huir(e.Location, this.Size, calcDistancia(p.getPosicion(), raton)); } } RATON = raton; }
public void SetLocation(Point newPoint) { if (this.InvokeRequired) { this.Invoke(new SetLocationCallBack(SetLocation), newPoint); } else { if (newPoint.Equals(lastPoint)) return; int x = newPoint.X; int y = newPoint.Y; if (x < 0) x = 0; if (y < 0) y = 0; Screen currentScreen; if (Screen.AllScreens.Length == 1) currentScreen = Screen.PrimaryScreen; else currentScreen = Screen.FromPoint(newPoint); if (x >= currentScreen.WorkingArea.Right) x = currentScreen.WorkingArea.Right - 10; if (y >= currentScreen.WorkingArea.Bottom) y = currentScreen.WorkingArea.Bottom - 10; this.Location = new System.Drawing.Point(x, y); lastPoint = newPoint; } }
private void SaveLocation(Point loc) { if (loc.Equals(Wm.Cd.VncOverlayLoc)) return; Wm.Cd.VncOverlayLoc = loc; Wm.OnStateChange(WmStateChange.Internal); }
private void ProcessObstacles() { ModelGame mg = (ModelGame)model; // We moeten een 2e array maken om door heen te loopen // Er is kans dat we de array door lopen en ook tegelijkertijd een explosie toevoegen // We voegen dan als het ware iets toe en lezen tegelijk, dit mag niet List<GameObject> safeListArray = new List<GameObject>(mg.GameObjects); SlowingObstacle slowedDownObstacle = null; // Loop door alle obstacles objecten en roep methode aan foreach (GameObject gameObject in safeListArray) { if (gameObject is MovingExplodingObstacle) { MovingExplodingObstacle gameObstacle = (MovingExplodingObstacle)gameObject; //Opslaan van huidige locatie in variable om vervolgens te vergelijken Point currentLocation = new Point(gameObstacle.Location.X, gameObstacle.Location.Y); gameObstacle.ChasePlayer(mg.player, "x"); gameObstacle.ProcessCollision(safeListArray, "x"); gameObstacle.ChasePlayer(mg.player, "y"); gameObstacle.ProcessCollision(safeListArray, "y"); if (gameObstacle.IsSmart && currentLocation.Equals(gameObstacle.Location) && !gameObstacle.SmartMovingEnabled) { gameObstacle.SmartmovingTime = DateTime.Now.AddMilliseconds(2500); gameObstacle.SmartMovingEnabled = true; } if (gameObstacle.IsSmart && gameObstacle.SmartMovingEnabled) { //Controleert als het object nog steeds slim moet zijn if (gameObstacle.SmartmovingTime >= DateTime.Now) { //Probeert weg te komen van stilstaant object gameObstacle.TryToEscape(); } else { gameObstacle.SmartMovingEnabled = false; gameObstacle.SmartmovingDirection = ""; // Reset direction voor smart movement gameObstacle.DirectionTime = default(DateTime); } } if (gameObstacle.CollidesWith(mg.player)) { score = 0; mg.player.Location = new Point(0, 0); UpdatePlayerPosition(); mg.InitializeField(); mg.GameObjects.Add(new Explosion(gameObstacle.Location, 10, 10)); mg.player.ObjectImage = Resources.Player; } } if (gameObject is SlowingObstacle) { SlowingObstacle gameObstacle = (SlowingObstacle)gameObject; //Opslaan van huidige locatie in variable om vervolgens te vergelijken Point currentLocation = gameObstacle.Location; gameObstacle.ChasePlayer(mg.player, "x"); gameObstacle.ProcessCollision(safeListArray, "x"); gameObstacle.ChasePlayer(mg.player, "y"); gameObstacle.ProcessCollision(safeListArray, "y"); if (gameObstacle.IsSmart && currentLocation.Equals(gameObstacle.Location) && !gameObstacle.SmartMovingEnabled) { gameObstacle.SmartmovingTime = DateTime.Now.AddMilliseconds(2500); gameObstacle.SmartMovingEnabled = true; } if (gameObstacle.IsSmart && gameObstacle.SmartMovingEnabled) { //Controleert als het object nog steeds slim moet zijn if (gameObstacle.SmartmovingTime >= DateTime.Now) { //Probeert weg te komen van stilstaant object gameObstacle.TryToEscape(); } else { gameObstacle.SmartMovingEnabled = false; gameObstacle.SmartmovingDirection = ""; // Reset direction voor smart movement gameObstacle.DirectionTime = default(DateTime); } } if (mg.player.CollidesWith(gameObstacle)) { slowedDownObstacle = gameObstacle; if(gameObstacle.SlowingSpeed < slowedDownObstacle.SlowingSpeed) { slowedDownObstacle.SlowingSpeed = gameObstacle.SlowingSpeed; } } if (mg.player.Speed == mg.player.OriginalSpeed / 2) UpdatePlayerSpeed("Slow"); else if (mg.player.Speed == mg.player.OriginalSpeed) UpdatePlayerSpeed("Normal"); else if (mg.player.Speed == mg.player.OriginalSpeed * 2) UpdatePlayerSpeed("Fast"); } if (gameObject is ExplodingObstacle) { ExplodingObstacle gameObstacle = (ExplodingObstacle)gameObject; if (mg.player.CollidesWith(gameObstacle)) { score = 0; mg.player.Location = new Point(0, 0); UpdatePlayerPosition(); mg.InitializeField(); mg.GameObjects.Add(new Explosion(gameObstacle.Location, 10, 10)); mg.player.ObjectImage = Resources.Player; } } if (gameObject is StaticObstacle) { StaticObstacle gameObstacle = (StaticObstacle)gameObject; if (mg.player.CollidesWith(gameObstacle)) { if (pressedUp) { mg.player.Location = new Point(mg.player.Location.X, mg.player.Location.Y + mg.player.Speed); } if (pressedDown) { mg.player.Location = new Point(mg.player.Location.X, mg.player.Location.Y - mg.player.Speed); } if (pressedLeft) { mg.player.Location = new Point(mg.player.Location.X + mg.player.Speed, mg.player.Location.Y); } if (pressedRight) { mg.player.Location = new Point(mg.player.Location.X - mg.player.Speed, mg.player.Location.Y); } } } if (gameObject is Checkpoint) { //End Game Checkpoint gameObstacle = (Checkpoint)gameObject; if (mg.player.CollidesWith(gameObstacle) && !gameObstacle.Start) { mg.player.Location = new Point(0, 0); mg.InitializeField(); timer.Stop(); if (editor) { gameWindow.setController(ScreenStates.editor); } else { gameWindow.setController(ScreenStates.highscoreInput); } TimerStop(); } } // Check of we de explosie kunnen verwijderen if (gameObject is Explosion) { Explosion explosion = (Explosion)gameObject; DateTime nowDateTime = DateTime.Now; DateTime explosionDateTime = explosion.TimeStamp; TimeSpan difference = nowDateTime - explosionDateTime; double animationTimerTen = (difference.TotalMilliseconds / 100); int animationTimer = Convert.ToInt32(animationTimerTen); // Explosie animatie switch (animationTimer) { case 1: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#FF0000"); gameObject.FadeSmall(); if (!mute) { player.Play(); } break; case 2: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#FC1212"); gameObject.FadeSmall(); break; case 3: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#F92525"); gameObject.FadeSmall(); break; case 4: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#F63737"); gameObject.FadeSmall(); break; case 5: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#F44A4A"); gameObject.FadeSmall(); break; case 6: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#F15C5C"); gameObject.FadeSmall(); break; case 7: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#EE6F6F"); gameObject.FadeSmall(); break; case 8: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#EB8181"); gameObject.FadeSmall(); break; case 9: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#E99494"); gameObject.FadeSmall(); break; case 10: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#E6A6A6"); gameObject.FadeSmall(); break; case 11: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#E3B9B9"); gameObject.FadeSmall(); break; case 12: mg.graphicsPanel.BackColor = ColorTranslator.FromHtml("#E0CBCB"); gameObject.FadeSmall(); break; } // Verschil is 3 seconden, dus het bestaat al voor 3 seconden, verwijderen maar! if (difference.TotalSeconds > 1.2) { mg.GameObjects.Remove(gameObject); mg.graphicsPanel.BackColor = System.Drawing.SystemColors.ControlLight; } } } if(slowedDownObstacle != null) { mg.player.Speed = slowedDownObstacle.SlowingSpeed; } }
protected override void OnMouseMove(MouseEventArgs e) { this.mouse_state.setLastLocation(e.Location); if (this.resize_active) { int delta = this.mouse_state.getDeltaX(); if (this.resize_side == CellResizeEventArgs.ResizeSide.Left) { Point new_location = new Point(this.Location.X + delta, this.Location.Y); if (!new_location.Equals(this.Location)) { this.Location = new_location; this.mouse_state.setLastLocation(new Point(e.X - delta, e.Y)); } //this.Width -= delta; if (this.IsPrevColElastic) this.addWidth(-delta); } else { //this.Width += delta; this.addWidth(delta); } OnCellResize(new CellResizeEventArgs(e, this.resize_side)); //vyvola udalost } base.OnMouseMove(e); }
/// <summary> /// Calculates the position of the point where it should lie if contraining conditions are met. /// </summary> /// <param name="currentPoint">Point to be constrained</param> /// <param name="referencePoint">Reference point for constrainment. Typically this is the mouse down point</param> /// <param name="direction">Direction to force the constraint.</param> public Point ConstrainPaint(Point currentPoint, Point referencePoint, ref ConstrainDirection direction) { // If the Control key is not pressed, then nothing to do. if ((Control.ModifierKeys == Keys.None) || ((Control.ModifierKeys | _uniformConstrainKeys) != _uniformConstrainKeys)) { direction = ConstrainDirection.NotSet; return(currentPoint); } if (currentPoint.Equals(referencePoint)) { return(currentPoint); } if (direction == ConstrainDirection.NotSet) { // determine a constraining direction based on the current point and the reference point int X = Math.Abs(currentPoint.X - referencePoint.X); int Y = Math.Abs(currentPoint.Y - referencePoint.Y); int D = Math.Max(X, Y); Point[] Snaps = new Point[4]; float[] Distance = new float[4]; float MinDistance = float.MaxValue; float ThisDistance = 0f; int Index = -1; for (int i = 0; i < Snaps.Length; i++) { Snaps[i] = referencePoint; } // Horizontal Snaps[0].Offset(D, 0); Snaps[1].Offset(-D, 0); // Vertical Snaps[2].Offset(0, D); Snaps[3].Offset(0, D); for (int i = 0; i < Snaps.Length; i++) { ThisDistance = ComputeDistance(currentPoint, Snaps[i]); MinDistance = Math.Min(MinDistance, ThisDistance); if (MinDistance == ThisDistance) { Index = i; } } if (Index < 3) { direction = ConstrainDirection.Horizontal; } else { direction = ConstrainDirection.Vertical; } } if (direction == ConstrainDirection.Horizontal) { return(new Point(currentPoint.X, referencePoint.Y)); } else if (direction == ConstrainDirection.Vertical) { return(new Point(referencePoint.X, currentPoint.Y)); } else { return(currentPoint); } }
public bool Equality(Point left, Point right) { return right.Equals(left); }
private void check_food() { int food_num = 0; Point tmp = new Point(); if (food_status == 1) { for (int i = 0; i < row - 1; i++) { for (int j = 0; j < col - 1; j++) { if (all[i, j] == 2) { food_num++; tmp.X = i; tmp.Y = j; } } } if (food_num != 1) { //MessageBox.Show("food to much , error"); } if (!tmp.Equals(food_cur)) { //MessageBox.Show("food not to match , error"); } return; } //MessageBox.Show("no food , error"); }
public void TestMinMax2() { Matrix<Single> matrix = new Matrix<Single> (10, 10); matrix.SetValue (5); matrix [5, 5] = 10; matrix [3, 3] = 0; double minVal = 5; double maxVal = 5; Point minLoc = new Point(); Point maxLoc = new Point(); matrix.MinMax (out minVal, out maxVal, out minLoc, out maxLoc); EmguAssert.IsTrue(minVal == 0); EmguAssert.IsTrue(maxVal == 10); EmguAssert.IsTrue(minLoc.Equals(new Point(3, 3))); EmguAssert.IsTrue(maxLoc.Equals(new Point(5, 5))); }
private void wavefront(Point start, Point goal, int val) { if (start.x < 0 || start.x > 7 || start.y < 0 || start.y > 3) { return; } int cell = getCell(start); if (cell < 0 || (cell > 0 && cell < val)) { return; } setCell(start, val); //Console.Out.WriteLine("x: " + start.x + " y: " + start.y + " val: " + getCell(start)); if (start.Equals(goal)) { return; } wavefront(new Point(start.x - 1, start.y), goal, val + 1); wavefront(new Point(start.x + 1, start.y), goal, val + 1); wavefront(new Point(start.x, start.y - 1), goal, val + 1); wavefront(new Point(start.x, start.y + 1), goal, val + 1); wavefront(new Point(start.x - 1, start.y-1), goal, val + 1); wavefront(new Point(start.x + 1, start.y-1), goal, val + 1); wavefront(new Point(start.x-1, start.y - 1), goal, val + 1); wavefront(new Point(start.x+1, start.y + 1), goal, val + 1); }
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { var handle = new WindowInteropHelper(this).Handle; var initialStyle = MainWindow.GetWindowLong(handle, -20); MainWindow.SetWindowLong(handle, -20, initialStyle | 0x20 | 0x80000); Task.Run(async() => { try { var prev = new Point(); var rectangle = new Rectangle(); await this.Dispatcher.InvokeAsync(() => { rectangle = new Rectangle((int)this.Left, (int)this.Top, (int)this.Width, (int)this.Height); }); while (this.applicationRunning) { var point = new Point(); MainWindow.GetCursorPos(ref point); if (!point.Equals(prev)) { prev = point; var opacity = 1.0; const double MIN_OP = 0.125; const double FADE = 175; if (this.settingsWindow == null || !this.settingsWindow.IsPositioning) { if (rectangle.Contains(point)) { opacity = MIN_OP; } else { if (point.Y <= rectangle.Bottom) { if (point.Y >= rectangle.Y) { if (point.X < rectangle.X && rectangle.X - point.X < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (rectangle.X - point.X) / FADE); } else if (point.X > rectangle.Right && point.X - rectangle.Right < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (point.X - rectangle.Right) / FADE); } } else if (point.Y < rectangle.Y) { if (point.X >= rectangle.X && point.X <= rectangle.Right) { if (rectangle.Y - point.Y < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, (rectangle.Y - point.Y) / FADE); } } else if (rectangle.X > point.X || rectangle.Right < point.X) { var distance = Math.Sqrt( Math.Pow( (point.X < rectangle.X ? rectangle.X : rectangle.Right) - point.X, 2) + Math.Pow(rectangle.Y - point.Y, 2)); if (distance < FADE) { opacity = MainWindow.Lerp(1.0, MIN_OP, distance / FADE); } } } } } } this.Dispatcher.Invoke(() => { this.Opacity = opacity; }); } var hidePressed = false; var exitPressed = false; var settingsPressed = false; // Set position anew to correct for fullscreen apps hiding taskbar this.Dispatcher.Invoke(() => { this.SetPosition(this.MonikaScreen); rectangle = new Rectangle((int)this.Left, (int)this.Top, (int)this.Width, (int)this.Height); // Detect exit key combo hidePressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeyHide); exitPressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeyExit); settingsPressed = this.AreKeysPressed(MonikaiSettings.Default.HotkeySettings); }); if (hidePressed && (DateTime.Now - this.lastKeyComboTime).TotalSeconds > 2) { this.lastKeyComboTime = DateTime.Now; if (this.Visibility == Visibility.Visible) { this.Dispatcher.Invoke(this.Hide); //var expression = // new Expression( // "Okay, see you later {name}! (Press again for me to return)", "b"); //expression.Executed += (o, args) => { this.Dispatcher.Invoke(this.Hide); }; //this.Say(new[] {expression}); } else { this.Dispatcher.Invoke(this.Show); } } if (exitPressed) { var expression = new Expression( "Goodbye for now! Come back soon please~", "b"); MonikaiSettings.Default.IsColdShutdown = false; MonikaiSettings.Default.Save(); expression.Executed += (o, args) => { this.Dispatcher.Invoke(() => { Environment.Exit(0); }); }; this.Say(new[] { expression }); } if (settingsPressed) { this.Dispatcher.Invoke(() => { if (this.settingsWindow == null || !this.settingsWindow.IsVisible) { this.settingsWindow = new SettingsWindow(this); this.settingsWindow.Show(); } }); } await Task.Delay(MonikaiSettings.Default.PotatoPC ? 100 : 32); } } catch (Exception) { // ignored } }); }
public static bool Test() { bool ok = true; string s = string.Empty; // DecodePoint Point p1 = new Point(5, 104); s = DecodePointInverse(p1); Point p2 = DecodePoint(s); if (!p1.Equals(p2)) ok = false; // DecodeSize Size s1 = new Size(1254, 67); s = DecodeSizeInverse(s1); Size s2 = DecodeSize(s); if (!s1.Equals(s2)) ok = false; // DecodeFont Font f1 = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Bold | FontStyle.Italic, GraphicsUnit.Point); s = DecodeFontInverse(f1); Font f2 = DecodeFont(s); if (!f1.Equals(f2)) ok = false; // DecodeDateTime DateTime t1 = DateTime.Today; s = DecodeDateTimeInverse(t1); DateTime t2 = DecodeDateTime(s); if (!t1.Equals(t2)) ok = false; // DecodeAppearance Appearance a1 = Appearance.Button; s = DecodeAppearanceInverse(a1); Appearance a2 = DecodeAppearance(s); if (!t1.Equals(t2)) ok = false; // DecodeScrollBars ScrollBars sb1 = ScrollBars.Both; s = DecodeScrollBarsInverse(sb1); ScrollBars sb2 = DecodeScrollBars(s); if (!sb1.Equals(sb2)) ok = false; // DecodeSelectionMode SelectionMode sm1 = SelectionMode.MultiSimple; s = DecodeSelectionModeInverse(sm1); SelectionMode sm2 = DecodeSelectionMode(s); if (!sm1.Equals(sm2)) ok = false; // DecodeView View v1 = View.LargeIcon; s = DecodeViewInverse(v1); View v2 = DecodeView(s); if (!v1.Equals(v2)) ok = false; // DecodeOrientation Orientation o1 = Orientation.Vertical; s = DecodeOrientationInverse(o1); Orientation o2 = DecodeOrientation(s); if (!o1.Equals(o2)) ok = false; // DecodeTickStyle TickStyle ts1 = TickStyle.BottomRight; s = DecodeTickStyleInverse(ts1); TickStyle ts2 = DecodeTickStyle(s); if (!ts1.Equals(ts2)) ok = false; // DecodeTabAlignment TabAlignment ta1 = TabAlignment.Right; s = DecodeTabAlignmentInverse(ta1); TabAlignment ta2 = DecodeTabAlignment(s); if (!ta1.Equals(ta2)) ok = false; // DecodeListViewItem (single) ListViewItem lv1 = new ListViewItem("John Doe"); s = DecodeListViewItemInverse(lv1); ListViewItem lv2 = DecodeListViewItem(s); /* not comparable (only by reference) if (!lv1.Equals(lv2)) ok = false; */ // DecodeListViewItem (subitems) lv1 = new ListViewItem(); lv1.SubItems.Add("John Doe"); lv1.SubItems.Add("Mountain View"); lv1.SubItems.Add("43"); s = DecodeListViewItemInverse(lv1); lv2 = DecodeListViewItem(s); /* not comparable (only by reference) if (!lv1.Equals(lv2)) ok = false; */ // DecodeColor s = DecodeColorInverse(Color.BlanchedAlmond); Color c = DecodeColor(s); if (!c.Equals(Color.BlanchedAlmond)) ok = false; return ok; }
/// <summary> /// Helper method for the FindAutoCropRectangle /// </summary> /// <param name="buffer"></param> /// <param name="colorPoint"></param> /// <returns></returns> private static Rectangle FindAutoCropRectangle(BitmapBuffer buffer, Point colorPoint, int cropDifference) { Rectangle cropRectangle = Rectangle.Empty; Color referenceColor = buffer.GetColorAtWithoutAlpha(colorPoint.X,colorPoint.Y); Point min = new Point(int.MaxValue, int.MaxValue); Point max = new Point(int.MinValue, int.MinValue); if (cropDifference > 0) { for(int y = 0; y < buffer.Height; y++) { for(int x = 0; x < buffer.Width; x++) { Color currentColor = buffer.GetColorAt(x, y); int diffR = Math.Abs(currentColor.R - referenceColor.R); int diffG = Math.Abs(currentColor.G - referenceColor.G); int diffB = Math.Abs(currentColor.B - referenceColor.B); if (((diffR + diffG + diffB) / 3) > cropDifference) { if (x < min.X) min.X = x; if (y < min.Y) min.Y = y; if (x > max.X) max.X = x; if (y > max.Y) max.Y = y; } } } } else { for(int y = 0; y < buffer.Height; y++) { for(int x = 0; x < buffer.Width; x++) { Color currentColor = buffer.GetColorAtWithoutAlpha(x, y); if (referenceColor.Equals(currentColor)) { if (x < min.X) min.X = x; if (y < min.Y) min.Y = y; if (x > max.X) max.X = x; if (y > max.Y) max.Y = y; } } } } if (!(Point.Empty.Equals(min) && max.Equals(new Point(buffer.Width-1, buffer.Height-1)))) { if (!(min.X == int.MaxValue || min.Y == int.MaxValue || max.X == int.MinValue || min.X == int.MinValue)) { cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X + 1, max.Y - min.Y + 1); } } return cropRectangle; }
public override void ProcessMouseUp(Point upPoint, GeoCoord mouseGeoLocation, bool controlDown, bool shiftDown, bool altDown) { //LibSys.StatusBar.Trace("LayerWaypoints:ProcessMouseUp()"); if(movePointMode) { movePointMode = false; if(wptToMove != null) { if(!upPoint.Equals(m_downPoint)) { wptToMove.Location = mouseGeoLocation; WaypointsCache.isDirty = true; wptToMove = null; CameraManager.This.SpoilPicture(upPoint); CameraManager.This.ProcessCameraMove(); } else { Point screenPoint = m_pictureManager.PointToScreen(upPoint); Project.ShowPopup(m_pictureManager.PictureBox, " you can move this waypoint by dragging mouse where you want new waypoint location to be. ", screenPoint); wptToMove = null; } } } if(moveLegMode) { moveLegMode = false; if(!upPoint.Equals(m_downPoint)) { CameraManager.This.SpoilPicture(upPoint); legToMove.split(mouseGeoLocation); legToMove = null; CameraManager.This.ProcessCameraMove(); } else { Point screenPoint = m_pictureManager.PointToScreen(upPoint); Project.ShowPopup(m_pictureManager.PictureBox, " you can split this leg by dragging mouse where you want new waypoint location to be. ", screenPoint); legToMove = null; } } }
protected void MyDrawLine(PaintEventArgs e, Pen pen, Point ptFrom, Point ptTo) { if (ptFrom.Equals(ptTo)) { e.Graphics.DrawEllipse(pen, ptFrom.X, ptFrom.Y, 1, 1); } else { e.Graphics.DrawLine(pen, ptFrom, ptTo); } }
//On dif height private void dif_height(Point inp, Point outp, int ot) { Point a = new Point(outp.X, inp.Y); Point b = new Point(inp.X - ot, inp.Y); if (!testX(a, b) || !testY(outp,a)) { Point b0 = b; Point a0 = new Point(outp.X, outp.Y - ot); Point a1 = a0; //And here for (int i = 0; i < field_matrix.GetLength(0); i++) { if (testX(a, b)) break; a.Y +=(int)Math.Pow(-1, i) * (i + 1) * sc; b.Y +=(int)Math.Pow(-1, i) * (i + 1) * sc; } for (int i = 0; i < field_matrix.GetLength(0); i++) { if (testY(a0, a)) break; a0.X += (int)Math.Pow(-1, i) * (i + 1) * sc; a.X += (int)Math.Pow(-1, i) * (i + 1) * sc; } for (int i = 0; i < field_matrix.GetLength(0); i++) { if (testY(b0, b)) break; b0.X += (int)Math.Pow(-1, i) * (i + 1) * sc; b.X += (int)Math.Pow(-1, i) * (i + 1) * sc; } if (!points.ContainsKey(outp)) points.Add(outp, a1); if (!points.ContainsKey(a1) && !a1.Equals(a)) points.Add(a1, a0); if (!points.ContainsKey(a0) && !a0.Equals(a)) points.Add(a0, a); if (!points.ContainsKey(a)) points.Add(a, b); if (!points.ContainsKey(b)) points.Add(b, b0); if (!points.ContainsKey(b0) && !b0.Equals(b)) points.Add(b0, inp); } else { points.Add(outp, a); points.Add(a, inp); } int ar = 5; if (inp.X < outp.X) ar = -ar; points.Add(new Point(inp.X - ar, inp.Y - ar), inp); points.Add(new Point(inp.X - ar, inp.Y + ar), inp); }
private Stack<Point> getPath(Point start, Point goal) { Stack<Point> path = new Stack<Point>(); wavefront(start, goal, 1); Point current = new Point(goal.x, goal.y); while (!current.Equals(start)) { path.Push(current); int val = getCell(current); Point left = new Point(current.x - 1, current.y); Point right = new Point(current.x + 1, current.y); Point up = new Point(current.x, current.y + 1); Point down = new Point(current.x, current.y - 1); Point leftup = new Point(current.x-1, current.y + 1); Point rightup = new Point(current.x+1, current.y + 1); Point leftdown = new Point(current.x-1, current.y - 1); Point rightdown = new Point(current.x+1, current.y - 1); int leftVal = getCell(left); int rightVal = getCell(right); int upVal = getCell(up); int downVal = getCell(down); int leftUpVal = getCell(leftup); int rightUpVal = getCell(rightup); int leftDownVal = getCell(leftdown); int rightDownVal = getCell(rightdown); int[] adjVals = new int[] { leftVal, leftDownVal, downVal, leftUpVal, rightUpVal, rightVal, rightDownVal, upVal }; Point[] adjPoints = new Point[] { left, leftdown, down, leftup, rightup, right, rightdown, up }; for (int i = 0; i < 8; i++) { if (adjVals[i] < val) { current = adjPoints[i]; Console.WriteLine(adjPoints[i].ToString()); break; } } } return path; }
//On one height private void one_height(Point inp, Point outp, int ot) { Point a = new Point(outp.X + ot, outp.Y); Point b = new Point(inp.X - ot, inp.Y); if (!testX(a, b)) { Point a0 = new Point(outp.X + ot, outp.Y); Point b0 = new Point(inp.X - ot, inp.Y); //Сюда тот цикл со сменой знака for (int i = 0; i < field_matrix.GetLength(0); i++) { if (testX(a, b)) break; a.Y += (int)Math.Pow(-1, i) * (i + 1) * sc; b.Y += (int)Math.Pow(-1, i) * (i + 1) * sc; } for (int i = 0; i < field_matrix.GetLength(0); i++) { if (testY(a0, a)) break; a0.X += (int)Math.Pow(-1, i) * (i + 1) * sc; a.X += (int)Math.Pow(-1, i) * (i + 1) * sc; } for (int i = 0; i < field_matrix.GetLength(0); i++) { if (testY(b0, b)) break; b0.X += (int)Math.Pow(-1, i) * (i + 1) * sc; b.X += (int)Math.Pow(-1, i) * (i + 1) * sc; } if (!points.ContainsKey(outp)) points.Add(outp, a0); if (!points.ContainsKey(a0) && !a0.Equals(a)) points.Add(a0, a); if (!points.ContainsKey(a)) points.Add(a, b); if (!points.ContainsKey(b)) points.Add(b, b0); if (!points.ContainsKey(b0) && !b0.Equals(b)) points.Add(b0, inp); } else { if (!points.ContainsKey(outp)) points.Add(outp, inp); } int ar = 5; points.Add(new Point(inp.X - ar, inp.Y - ar), inp); points.Add(new Point(inp.X - ar, inp.Y + ar), inp); }
private void CheckPieces(Point source, Point destination) { if (source.Equals(destination) == true) { throw new InvalidMoveException(ErrorIdenticalPiece); } if (this.IsOuterPiece(source) == false || this.IsOuterPiece(destination) == false) { throw new InvalidMoveException(ErrorInternalPiece); } if (this.CanCurrentPlayerUseSource(source) == false) { throw new InvalidMoveException( string.Format(ErrorInvalidSourcePiece, this.currentPlayer.ToString(), source.ToString())); } if (source.X != destination.X && source.Y != destination.Y) { throw new InvalidMoveException( string.Format(ErrorInvalidDestinationPosition, this.currentPlayer.ToString(), destination.ToString())); } var endPoint = this.GetEndPoint(source, destination); if (endPoint != 0 && endPoint != (Dimension - 1)) { throw new InvalidMoveException( string.Format(ErrorInvalidDestinationPosition, this.currentPlayer.ToString(), destination.ToString())); } }
/// <summary> /// Calculates the distances to the enemy of every point around the target and returns the points ordered in a list. /// </summary> /// <param name="player"></param> /// <param name="playerTeam"></param> /// <param name="targetPoint"></param> /// <param name="range">The range around the target point</param> /// <param name="amountOfPlayers">The amount of players which are allowed to stand around the calculated point </param> /// <param name="rangeRectangle"></param> /// <returns></returns> public List<Point> SearchRunPoints(Player player, Team playerTeam, Point targetPoint, int range, int amountOfPlayers, Rectangle rangeRectangle) { Pathfinding pathfinding = new Pathfinding(); Point rootPoint = targetPoint; List<Point> neighbors = new List<Point>(); List<double> distancesToTarget = new List<double>(); double rootDistanceToTarget = Pathfinding.DistanceBetweenPoints(player.Location, targetPoint); Point? bestNeighbor = null; int bestSurroundingEnemies = -1; for (int v = -2; v <= 2; v++) { for (int h = -2; h <= 2; h++) { Point neighbor = new Point(rootPoint.X + h, rootPoint.Y + v); int surroundingEnemies = SurroundingPlayers(GetEnemyTeam(playerTeam), range, neighbor, 1).Count; double tmpDistanceToTarget = Pathfinding.DistanceBetweenPoints(neighbor, targetPoint); if (pathfinding.IsWithinField(neighbor) && !neighbor.Equals(player.Location) && (!Pathfinding.CurrentBlockedRoom.Room.Contains(neighbor) || Pathfinding.CurrentBlockedRoom.AllowedTeam.Equals(playerTeam))) { if (tmpDistanceToTarget < rootDistanceToTarget && (bestSurroundingEnemies == -1 || surroundingEnemies < bestSurroundingEnemies)) { bestNeighbor = neighbor; bestSurroundingEnemies = surroundingEnemies; } if (rangeRectangle.Contains(neighbor) && pathfinding.StandsPlayerOnPosition(neighbor, 1) == null && surroundingEnemies <= amountOfPlayers) { if (neighbors.Count == 0) { neighbors.Add(neighbor); distancesToTarget.Add(tmpDistanceToTarget); } else { for (int i = 0; i <= distancesToTarget.Count; i++) { if (i == distancesToTarget.Count || tmpDistanceToTarget < distancesToTarget[i]) { neighbors.Insert(i, neighbor); distancesToTarget.Insert(i, tmpDistanceToTarget); break; } } } } } } } if (neighbors.Count == 0) { if (bestNeighbor.HasValue) { neighbors.Add(bestNeighbor.Value); } else { neighbors.Add(targetPoint); } } return neighbors; }
public override bool OnMouseMove(Glyph g, MouseButtons button, Point mouseLoc) { if (!this.pushedBehavior) { return false; } bool flag = Control.ModifierKeys == Keys.Alt; if (flag && (this.dragManager != null)) { this.dragManager.EraseSnapLines(); } if (flag || !mouseLoc.Equals(this.lastMouseLoc)) { if (this.lastMouseAbs != null) { System.Design.NativeMethods.POINT pt = new System.Design.NativeMethods.POINT(mouseLoc.X, mouseLoc.Y); System.Design.UnsafeNativeMethods.ClientToScreen(new HandleRef(this, this.behaviorService.AdornerWindowControl.Handle), pt); if ((pt.x == this.lastMouseAbs.x) && (pt.y == this.lastMouseAbs.y)) { return true; } } if (!this.dragging) { if ((Math.Abs((int) (this.initialPoint.X - mouseLoc.X)) <= (DesignerUtils.MinDragSize.Width / 2)) && (Math.Abs((int) (this.initialPoint.Y - mouseLoc.Y)) <= (DesignerUtils.MinDragSize.Height / 2))) { return false; } this.InitiateResize(); this.dragging = true; } if ((this.resizeComponents == null) || (this.resizeComponents.Length == 0)) { return false; } PropertyDescriptor descriptor = null; PropertyDescriptor descriptor2 = null; PropertyDescriptor descriptor3 = null; PropertyDescriptor descriptor4 = null; if (this.initialResize) { descriptor = TypeDescriptor.GetProperties(this.resizeComponents[0].resizeControl)["Width"]; descriptor2 = TypeDescriptor.GetProperties(this.resizeComponents[0].resizeControl)["Height"]; descriptor3 = TypeDescriptor.GetProperties(this.resizeComponents[0].resizeControl)["Top"]; descriptor4 = TypeDescriptor.GetProperties(this.resizeComponents[0].resizeControl)["Left"]; if ((descriptor != null) && !typeof(int).IsAssignableFrom(descriptor.PropertyType)) { descriptor = null; } if ((descriptor2 != null) && !typeof(int).IsAssignableFrom(descriptor2.PropertyType)) { descriptor2 = null; } if ((descriptor3 != null) && !typeof(int).IsAssignableFrom(descriptor3.PropertyType)) { descriptor3 = null; } if ((descriptor4 != null) && !typeof(int).IsAssignableFrom(descriptor4.PropertyType)) { descriptor4 = null; } } Control resizeControl = this.resizeComponents[0].resizeControl as Control; this.lastMouseLoc = mouseLoc; this.lastMouseAbs = new System.Design.NativeMethods.POINT(mouseLoc.X, mouseLoc.Y); System.Design.UnsafeNativeMethods.ClientToScreen(new HandleRef(this, this.behaviorService.AdornerWindowControl.Handle), this.lastMouseAbs); int num = Math.Max(resizeControl.MinimumSize.Height, 10); int num2 = Math.Max(resizeControl.MinimumSize.Width, 10); if (this.dragManager != null) { bool flag2 = true; bool shouldSnapHorizontally = true; if ((((this.targetResizeRules & SelectionRules.BottomSizeable) != SelectionRules.None) || ((this.targetResizeRules & SelectionRules.TopSizeable) != SelectionRules.None)) && (resizeControl.Height == num)) { flag2 = false; } else if ((((this.targetResizeRules & SelectionRules.RightSizeable) != SelectionRules.None) || ((this.targetResizeRules & SelectionRules.LeftSizeable) != SelectionRules.None)) && (resizeControl.Width == num2)) { flag2 = false; } PropertyDescriptor descriptor5 = TypeDescriptor.GetProperties(resizeControl)["IntegralHeight"]; if (descriptor5 != null) { object obj2 = descriptor5.GetValue(resizeControl); if ((obj2 is bool) && ((bool) obj2)) { shouldSnapHorizontally = false; } } if (!flag && flag2) { this.lastSnapOffset = this.dragManager.OnMouseMove(resizeControl, this.GenerateSnapLines(this.targetResizeRules, mouseLoc), ref this.didSnap, shouldSnapHorizontally); } else { this.dragManager.OnMouseMove(new Rectangle(-100, -100, 0, 0)); } mouseLoc.X += this.lastSnapOffset.X; mouseLoc.Y += this.lastSnapOffset.Y; } Rectangle rectangle = new Rectangle(this.resizeComponents[0].resizeBounds.X, this.resizeComponents[0].resizeBounds.Y, this.resizeComponents[0].resizeBounds.Width, this.resizeComponents[0].resizeBounds.Height); if (this.didSnap && (resizeControl.Parent != null)) { rectangle.Location = this.behaviorService.MapAdornerWindowPoint(resizeControl.Parent.Handle, rectangle.Location); if (resizeControl.Parent.IsMirrored) { rectangle.Offset(-rectangle.Width, 0); } } Rectangle empty = Rectangle.Empty; Rectangle dragRect = Rectangle.Empty; bool flag4 = true; Color backColor = (resizeControl.Parent != null) ? resizeControl.Parent.BackColor : Color.Empty; for (int i = 0; i < this.resizeComponents.Length; i++) { Control c = this.resizeComponents[i].resizeControl as Control; Rectangle bounds = c.Bounds; Rectangle rc = bounds; Rectangle resizeBounds = this.resizeComponents[i].resizeBounds; Rectangle rect = this.BehaviorService.ControlRectInAdornerWindow(c); bool flag5 = true; System.Design.UnsafeNativeMethods.SendMessage(c.Handle, 11, false, 0); try { bool flag6 = false; if ((c.Parent != null) && c.Parent.IsMirrored) { flag6 = true; } BoundsSpecified none = BoundsSpecified.None; SelectionRules resizeRules = this.resizeComponents[i].resizeRules; if (((this.targetResizeRules & SelectionRules.BottomSizeable) != SelectionRules.None) && ((resizeRules & SelectionRules.BottomSizeable) != SelectionRules.None)) { int num4; if (this.didSnap) { num4 = mouseLoc.Y - rectangle.Bottom; } else { num4 = AdjustPixelsForIntegralHeight(c, mouseLoc.Y - this.initialPoint.Y); } bounds.Height = Math.Max(num, resizeBounds.Height + num4); none |= BoundsSpecified.Height; } if (((this.targetResizeRules & SelectionRules.TopSizeable) != SelectionRules.None) && ((resizeRules & SelectionRules.TopSizeable) != SelectionRules.None)) { int num5; if (this.didSnap) { num5 = rectangle.Y - mouseLoc.Y; } else { num5 = AdjustPixelsForIntegralHeight(c, this.initialPoint.Y - mouseLoc.Y); } none |= BoundsSpecified.Height; bounds.Height = Math.Max(num, resizeBounds.Height + num5); if ((bounds.Height != num) || ((bounds.Height == num) && (rc.Height != num))) { none |= BoundsSpecified.Y; bounds.Y = Math.Min((int) (resizeBounds.Bottom - num), (int) (resizeBounds.Y - num5)); } } if (((((this.targetResizeRules & SelectionRules.RightSizeable) != SelectionRules.None) && ((resizeRules & SelectionRules.RightSizeable) != SelectionRules.None)) && !flag6) || ((((this.targetResizeRules & SelectionRules.LeftSizeable) != SelectionRules.None) && ((resizeRules & SelectionRules.LeftSizeable) != SelectionRules.None)) && flag6)) { none |= BoundsSpecified.Width; int x = this.initialPoint.X; if (this.didSnap) { x = !flag6 ? rectangle.Right : rectangle.Left; } bounds.Width = Math.Max(num2, resizeBounds.Width + (!flag6 ? (mouseLoc.X - x) : (x - mouseLoc.X))); } if (((((this.targetResizeRules & SelectionRules.RightSizeable) != SelectionRules.None) && ((resizeRules & SelectionRules.RightSizeable) != SelectionRules.None)) && flag6) || ((((this.targetResizeRules & SelectionRules.LeftSizeable) != SelectionRules.None) && ((resizeRules & SelectionRules.LeftSizeable) != SelectionRules.None)) && !flag6)) { none |= BoundsSpecified.Width; int num7 = this.initialPoint.X; if (this.didSnap) { num7 = !flag6 ? rectangle.Left : rectangle.Right; } int num8 = !flag6 ? (num7 - mouseLoc.X) : (mouseLoc.X - num7); bounds.Width = Math.Max(num2, resizeBounds.Width + num8); if ((bounds.Width != num2) || ((bounds.Width == num2) && (rc.Width != num2))) { none |= BoundsSpecified.X; bounds.X = Math.Min((int) (resizeBounds.Right - num2), (int) (resizeBounds.X - num8)); } } if (!this.parentGridSize.IsEmpty) { bounds = this.AdjustToGrid(bounds, this.targetResizeRules); } if ((((none & BoundsSpecified.Width) == BoundsSpecified.Width) && this.dragging) && (this.initialResize && (descriptor != null))) { descriptor.SetValue(this.resizeComponents[i].resizeControl, bounds.Width); } if ((((none & BoundsSpecified.Height) == BoundsSpecified.Height) && this.dragging) && (this.initialResize && (descriptor2 != null))) { descriptor2.SetValue(this.resizeComponents[i].resizeControl, bounds.Height); } if ((((none & BoundsSpecified.X) == BoundsSpecified.X) && this.dragging) && (this.initialResize && (descriptor4 != null))) { descriptor4.SetValue(this.resizeComponents[i].resizeControl, bounds.X); } if ((((none & BoundsSpecified.Y) == BoundsSpecified.Y) && this.dragging) && (this.initialResize && (descriptor3 != null))) { descriptor3.SetValue(this.resizeComponents[i].resizeControl, bounds.Y); } if (this.dragging) { c.SetBounds(bounds.X, bounds.Y, bounds.Width, bounds.Height, none); empty = this.BehaviorService.ControlRectInAdornerWindow(c); if (c.Equals(resizeControl)) { dragRect = empty; } if (c.Bounds == rc) { flag5 = false; } if (c.Bounds != bounds) { flag4 = false; } } if ((c == this.primaryControl) && (this.statusCommandUI != null)) { this.statusCommandUI.SetStatusInformation(c); } } finally { System.Design.UnsafeNativeMethods.SendMessage(c.Handle, 11, true, 0); if (flag5) { Control parent = c.Parent; if (parent != null) { c.Invalidate(true); parent.Invalidate(rc, true); parent.Update(); } else { c.Refresh(); } } if (!empty.IsEmpty) { using (Region region = new Region(empty)) { region.Exclude(Rectangle.Inflate(empty, -2, -2)); if (flag5) { using (Region region2 = new Region(rect)) { region2.Exclude(Rectangle.Inflate(rect, -2, -2)); this.BehaviorService.Invalidate(region2); } } if (!this.captureLost) { using (Graphics graphics = this.BehaviorService.AdornerWindowGraphics) { if ((this.lastResizeRegion != null) && !this.lastResizeRegion.Equals(region, graphics)) { this.lastResizeRegion.Exclude(region); this.BehaviorService.Invalidate(this.lastResizeRegion); this.lastResizeRegion.Dispose(); this.lastResizeRegion = null; } DesignerUtils.DrawResizeBorder(graphics, region, backColor); } if (this.lastResizeRegion == null) { this.lastResizeRegion = region.Clone(); } } } } } } if ((flag4 && !flag) && (this.dragManager != null)) { this.dragManager.RenderSnapLinesInternal(dragRect); } this.initialResize = false; } return true; }
private void AnimateFrame(Rectangle box, Graphics g, ref int marqueeX) { if (box == null || g == null || box.Width <= 1) { return; } Pen penb = new Pen(new SolidBrush(blend)); g.FillRectangle(new SolidBrush(color1), box); for (int i = box.Right + marqueeX; i > box.Left; i -= ((box.Height * 2) + StripeSpacing - 1)) { Point theoreticalRightTop = new Point(i, box.Top); Point theoreticalRightBottom = new Point(i - box.Height, box.Bottom); Point theoreticalLeftTop = new Point(i - box.Height, box.Top); Point theoreticalLeftBottom = new Point(i - (box.Height * 2), box.Bottom); Point leftTop, leftBottom, rightTop, rightBottom; using (GraphicsPath gp = new GraphicsPath()) { if (theoreticalLeftTop.X <= box.Left) { // left triangle int diff = i - box.Height; rightTop = new Point(i, box.Top); rightBottom = new Point(box.Left, box.Bottom + diff); leftTop = new Point(box.Left, box.Top); leftBottom = leftTop; if (rightBottom.Equals(rightTop)) { continue; } gp.AddLine(rightTop, rightBottom); gp.AddLine(rightBottom, leftTop); gp.AddLine(leftTop, new Point(i, box.Top)); } else if (theoreticalLeftBottom.X <= box.Left) { // left pentagon int diff = i - (box.Height * 2); rightTop = new Point(i, box.Top); rightBottom = new Point(i - box.Height, box.Bottom); leftTop = new Point(i - box.Height, box.Top); leftBottom = new Point(box.Left, box.Bottom + diff); gp.AddLine(rightTop, rightBottom); gp.AddLine(rightBottom, new Point(box.Left, box.Bottom)); gp.AddLine(new Point(box.Left, box.Bottom), leftBottom); gp.AddLine(leftBottom, leftTop); gp.AddLine(leftTop, rightTop); } else if (theoreticalRightBottom.X >= box.Right) { // right triangle int diff = marqueeX - box.Height; leftTop = new Point(box.Right, box.Top + diff); //= something funky leftBottom = theoreticalLeftBottom; rightBottom = new Point(box.Right, box.Bottom); rightTop = rightBottom; if (leftBottom.Equals(leftTop)) { continue; } gp.AddLine(leftTop, rightBottom); gp.AddLine(rightBottom, leftBottom); gp.AddLine(leftBottom, leftTop); } else if (theoreticalRightTop.X >= box.Right) { // right pentagon int diff = i - box.Right; Point topRight = new Point(box.Right, box.Top); rightTop = new Point(box.Right, box.Top + diff); rightBottom = new Point(i - box.Height, box.Bottom); leftTop = new Point(i - box.Height, box.Top); leftBottom = new Point(i - (box.Height * 2), box.Bottom); gp.AddLine(leftTop, topRight); gp.AddLine(topRight, rightTop); gp.AddLine(rightTop, rightBottom); gp.AddLine(rightBottom, leftBottom); gp.AddLine(leftBottom, leftTop); } else { // mid-range rectangle rightTop = new Point(i, box.Top); rightBottom = new Point(i - box.Height, box.Bottom); leftTop = new Point(i - box.Height, box.Top); leftBottom = new Point(i - (box.Height * 2), box.Bottom); gp.AddLine(rightTop, rightBottom); gp.AddLine(rightBottom, leftBottom); gp.AddLine(leftBottom, leftTop); gp.AddLine(leftTop, rightTop); } g.FillPath(new SolidBrush(color2), gp); } if (!leftTop.Equals(leftBottom)) { g.DrawLine(penb, leftTop, leftBottom); } if (!rightTop.Equals(rightBottom)) { g.DrawLine(penb, rightTop, rightBottom); } } g.DrawLine(penb, new Point(box.Left, box.Bottom), new Point(box.Right, box.Bottom)); if (++marqueeX > (box.Height * 2) + StripeSpacing) { marqueeX = 1; } }