public Piece(Height height, Shape shape, Top top, Color color, int location, long pieceId, bool isSelected) { Initialize(height, shape, top, color); Location = location; PieceId = pieceId; IsSelected = isSelected; }
public static void CSharpTypesDemo() { Height joe = new Height(); joe.Inches = 71; Height bob = new Height(); bob.Inches = 59; Console.WriteLine("Original Height Values:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches); // assign joe reference to bob variable bob = joe; Console.WriteLine(); Console.WriteLine("Values After Value Assignment:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches); joe.Inches = 65; Console.WriteLine(); Console.WriteLine("Values After Changing One Instance:"); Console.WriteLine("joe = " + joe.Inches); Console.WriteLine("bob = " + bob.Inches); Console.ReadKey(); }
public Area(string selection) { jquery = jQuery.Select(selection); // create properties mMargin = new Margin(jquery); mHeight = new Height(jquery); mOuterHeight = new OuterHeight(jquery, mHeight); updateCss = true; }
public BlockchainState(Network network, Height bestHeight, IEnumerable <BlockState> blockStates) { Network = network; BestHeight = bestHeight; BlockStates = blockStates?.OrderBy(x => x).ToList() ?? new List <BlockState>(); }
public override int GetHashCode() { return(position.GetHashCode() + Width.GetHashCode() + Height.GetHashCode()); }
/// <summary> /// Gets the <see cref="GraphicsPath"/> for this element. /// </summary> public override GraphicsPath Path(ISvgRenderer renderer) { if (_path == null || IsPathDirty) { var halfStrokeWidth = new SvgUnit(base.StrokeWidth / 2); // If it is to render, don't need to consider stroke if (renderer != null) { halfStrokeWidth = 0; this.IsPathDirty = false; } // If the corners aren't to be rounded just create a rectangle if (CornerRadiusX.Value == 0.0f && CornerRadiusY.Value == 0.0f) { // Starting location which take consideration of stroke width SvgPoint strokedLocation = new SvgPoint(Location.X - halfStrokeWidth, Location.Y - halfStrokeWidth); var width = this.Width.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this) + halfStrokeWidth; var height = this.Height.ToDeviceValue(renderer, UnitRenderingType.Vertical, this) + halfStrokeWidth; var rectangle = new RectangleF(strokedLocation.ToDeviceValue(renderer, this), new SizeF(width, height)); _path = new GraphicsPath(); _path.StartFigure(); _path.AddRectangle(rectangle); _path.CloseFigure(); } else { _path = new GraphicsPath(); var arcBounds = new RectangleF(); var lineStart = new PointF(); var lineEnd = new PointF(); var width = Width.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this); var height = Height.ToDeviceValue(renderer, UnitRenderingType.Vertical, this); var rx = Math.Min(CornerRadiusX.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this) * 2, width); var ry = Math.Min(CornerRadiusY.ToDeviceValue(renderer, UnitRenderingType.Vertical, this) * 2, height); var location = Location.ToDeviceValue(renderer, this); // Start _path.StartFigure(); // Add first arc arcBounds.Location = location; arcBounds.Width = rx; arcBounds.Height = ry; _path.AddArc(arcBounds, 180, 90); // Add first line lineStart.X = Math.Min(location.X + rx, location.X + width * 0.5f); lineStart.Y = location.Y; lineEnd.X = Math.Max(location.X + width - rx, location.X + width * 0.5f); lineEnd.Y = lineStart.Y; _path.AddLine(lineStart, lineEnd); // Add second arc arcBounds.Location = new PointF(location.X + width - rx, location.Y); _path.AddArc(arcBounds, 270, 90); // Add second line lineStart.X = location.X + width; lineStart.Y = Math.Min(location.Y + ry, location.Y + height * 0.5f); lineEnd.X = lineStart.X; lineEnd.Y = Math.Max(location.Y + height - ry, location.Y + height * 0.5f); _path.AddLine(lineStart, lineEnd); // Add third arc arcBounds.Location = new PointF(location.X + width - rx, location.Y + height - ry); _path.AddArc(arcBounds, 0, 90); // Add third line lineStart.X = Math.Max(location.X + width - rx, location.X + width * 0.5f); lineStart.Y = location.Y + height; lineEnd.X = Math.Min(location.X + rx, location.X + width * 0.5f); lineEnd.Y = lineStart.Y; _path.AddLine(lineStart, lineEnd); // Add third arc arcBounds.Location = new PointF(location.X, location.Y + height - ry); _path.AddArc(arcBounds, 90, 90); // Add fourth line lineStart.X = location.X; lineStart.Y = Math.Max(location.Y + height - ry, location.Y + height * 0.5f); lineEnd.X = lineStart.X; lineEnd.Y = Math.Min(location.Y + ry, location.Y + height * 0.5f); _path.AddLine(lineStart, lineEnd); // Close _path.CloseFigure(); } } return(_path); }
protected bool Equals(Dimensions other) { return(Width.Equals(other.Width) && Height.Equals(other.Height)); }
public override string ToString() { return($"Value = {Value.ToString()} Height={Height.ToString()}"); }
List<WoWPoint> ProcessPoints(List<WoWPoint> points, Height ht) { List<WoWPoint> newPoints = new List<WoWPoint>(); newPoints.Add(points[0]); for (int i = 1; i < points.Count; i++) { List<WoWPoint> tempPoints = CreatePathSegment(points[i - 1], points[i], ht); /* TODO - RENABLE THIS if (Gui.smoothCheck.Checked) { tempPoints = SmoothOut3dSegment(tempPoints); } * */ newPoints.AddRange(tempPoints); } return newPoints; }
public void SetTerrainHeight(float heightMod){ if (heightMod > 0) { currentHight = Height.High; } else { currentHight = Height.Low; } Vector3 heightVector = new Vector3(0,heightMod,0); transform.position += heightVector; InstanceType(); }
/// <summary> /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object. /// </summary> protected override void Render(ISvgRenderer renderer) { if (!(Visible && Displayable && Width.Value > 0f && Height.Value > 0f && Href != null)) { return; } var img = GetImage(Href); var bmp = img as Image; var svg = img as SvgFragment; if (bmp == null && svg == null) { return; } try { if (PushTransforms(renderer)) { RectangleF srcRect; if (bmp != null) { srcRect = new RectangleF(0f, 0f, bmp.Width, bmp.Height); } else { srcRect = new RectangleF(new PointF(0f, 0f), svg.GetDimensions()); } var destClip = new RectangleF(Location.ToDeviceValue(renderer, this), new SizeF(Width.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this), Height.ToDeviceValue(renderer, UnitRenderingType.Vertical, this))); var destRect = destClip; renderer.SetClip(new Region(destClip), CombineMode.Intersect); SetClip(renderer); var aspectRatio = AspectRatio; if (aspectRatio.Align != SvgPreserveAspectRatio.none) { var fScaleX = destClip.Width / srcRect.Width; var fScaleY = destClip.Height / srcRect.Height; var xOffset = 0f; var yOffset = 0f; if (aspectRatio.Slice) { fScaleX = Math.Max(fScaleX, fScaleY); fScaleY = Math.Max(fScaleX, fScaleY); } else { fScaleX = Math.Min(fScaleX, fScaleY); fScaleY = Math.Min(fScaleX, fScaleY); } switch (aspectRatio.Align) { case SvgPreserveAspectRatio.xMinYMin: break; case SvgPreserveAspectRatio.xMidYMin: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; break; case SvgPreserveAspectRatio.xMaxYMin: xOffset = (destClip.Width - srcRect.Width * fScaleX); break; case SvgPreserveAspectRatio.xMinYMid: yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMidYMid: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMaxYMid: xOffset = (destClip.Width - srcRect.Width * fScaleX); yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMinYMax: yOffset = (destClip.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatio.xMidYMax: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; yOffset = (destClip.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatio.xMaxYMax: xOffset = (destClip.Width - srcRect.Width * fScaleX); yOffset = (destClip.Height - srcRect.Height * fScaleY); break; } destRect = new RectangleF(destClip.X + xOffset, destClip.Y + yOffset, srcRect.Width * fScaleX, srcRect.Height * fScaleY); } if (bmp != null) { var opacity = FixOpacityValue(Opacity); if (opacity == 1f) { renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel); } else { renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel, opacity); } } else { renderer.TranslateTransform(destRect.X, destRect.Y, MatrixOrder.Prepend); renderer.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height, MatrixOrder.Prepend); try { renderer.SetBoundable(new GenericBoundable(srcRect)); svg.RenderElement(renderer); } finally { renderer.PopBoundable(); } } ResetClip(renderer); } } finally { PopTransforms(renderer); if (bmp != null) { bmp.Dispose(); } } // TODO: cache images... will need a shared context for this }
/// <summary> /// Converts the <see cref='System.Drawing.RectangleF.Location'/> and <see cref='System.Drawing.RectangleF.Size'/> of this <see cref='System.Drawing.RectangleF'/> to a /// human-readable string. /// </summary> public override string ToString() { return("{X=" + X.ToString() + ",Y=" + Y.ToString() + ",Width=" + Width.ToString() + ",Height=" + Height.ToString() + "}"); }
public override string RenderHtml() { if (Wrap) { var wrapper = new TagBuilder(_fieldWrapper); if (string.IsNullOrEmpty(this._cssClass)) { wrapper.Attributes["class"] = _fieldWrapperClass; } else { wrapper.Attributes["class"] = this._cssClass; } System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"(\r\n|\r|\n)+"); string newText = regex.Replace(Html.Replace(" ", " "), "<br />"); Html = MvcHtmlString.Create(newText).ToString(); // wrapper.Attributes["ID"] = "labelmvcdynamicfield_" + Name.ToLower(); wrapper.Attributes["ID"] = "mvcdynamicfield_" + Name.ToLower() + "_fieldWrapper"; StringBuilder StyleValues = new StringBuilder(); StyleValues.Append(GetContolStyle(_fontstyle.ToString(), _top.ToString(), _left.ToString(), Width.ToString(), Height.ToString(), IsHidden)); //StyleValues.Append(";word-wrap:break-word;"); wrapper.Attributes.Add(new KeyValuePair <string, string>("style", StyleValues.ToString())); wrapper.InnerHtml = Html; return(wrapper.ToString()); } return(Html); }
public override int GetHashCode() => Width.GetHashCode() ^ Height.GetHashCode();
public bool Equals(DisplayInfo other) => Width.Equals(other.Width) && Height.Equals(other.Height) && Density.Equals(other.Density) && Orientation.Equals(other.Orientation) && Rotation.Equals(other.Rotation);
/// <summary> /// The method called upon a hitbox update. /// </summary> protected virtual void OnRectangleUpdate() { if (Texture != null) { _boundingRect = new Rectangle(TopLeft.X.Round(), TopLeft.Y.Round(), Width.Round(), Height.Round()); _nonscaleCenter = new Vector2(Texture.Width / 2f, Texture.Height / 2f); } else { _boundingRect = new Rectangle(TopLeft.X.Round(), TopLeft.Y.Round(), 0, 0); _nonscaleCenter = Vector2.Zero; } }
public HeaderElement(string header) { this.header = header; Width.Set(0f, 1f); Height.Set(30f, 0f); }
// methods public override void allocate() { // initialize/declare arrays and steps // If we want to change one of the parameters: n, m, l, TB, // then it needs to call this (plus Intiials) functions again. hx = 2 * L / (N - 1); // step for x ht = T / (M - 1); // step for t x = new double[N]; // arrange x's t = new double[M]; // arrange t's velocities = new Velocity[M]; heights = new Height[M]; Parallel.Invoke( () => { if (x != null) for (int i = 0; i < N; i++) x[i] = -L + i * hx; }, () => { if (t != null && velocities != null && heights != null) for (int j = 0; j < M; j++) { t[j] = j * ht; velocities[j] = new Velocity(); heights[j] = new Height(); } } ); u = new double[M, N]; v = new double[M, N]; }
protected bool Equals(ModelObject other) { return(string.Equals(Name, other.Name) && Height.Equals(other.Height) && Width.Equals(other.Width)); }
List<WoWPoint> CreatePathSegment(WoWPoint from, WoWPoint to, Height ht) { List<WoWPoint> segment = new List<WoWPoint>(); WoWPoint point = from; float step = 50; float noMeshStep = 5; for (float i = from.Distance(to) - step; i > 0; ) { point = WoWMathHelper.CalculatePointFrom(from, to, i); try { float z = ht == Height.High ? Navigator.FindHeights(point.X, point.Y).Max() : Navigator.FindHeights(point.X, point.Y).Min(); i -= step; /* TODO - REENABLE THISif (Gui.smoothCheck.Checked && z > point.Z) { point.Z = z; } * */ segment.Add(point); } catch { i -= noMeshStep; } } segment.Add(to); return segment; }
public ICoinsView AtBlockHeight(Height height) => new CoinsView(Coins.Where(x => x.Height == height));
WoWPoint TryGetHeight(WoWPoint point, Height ht) { float PIx2 = (float)Math.PI * 2f; int step = 20; for (int d = 5; d <= 50; d += 5) { for (int i = 0; i < 20; i++) { WoWPoint newPoint = point.RayCast((i * PIx2) / step, d); try { newPoint.Z = ht == Height.High ? Navigator.FindHeights(newPoint.X, newPoint.Y).Max() : Navigator.FindHeights(newPoint.X, newPoint.Y).Min(); return newPoint; } catch { } } } return point; }
public bool Equals(SizeF other) { return(Width.Equals(other.Width) && Height.Equals(other.Height)); }
public override void OnInitialize() { Width.Set((int)Main.fontMouseText.MeasureString(Text).X * 1.2f, 0); Height.Set((int)Main.fontMouseText.MeasureString(Text).Y * 1.2f, 0); }
public override string ToString() { return("{Width=" + Width.ToString(CultureInfo.CurrentCulture) + ", Height=" + Height.ToString(CultureInfo.CurrentCulture) + "}"); }
public void Synchronize() { Interlocked.Exchange(ref _running, 1); Task.Run(async() => { try { var blockCount = await RpcClient.GetBlockCountAsync(); var isIIB = true; // Initial Index Building phase while (IsRunning) { try { // If stop was requested return. if (IsRunning == false) { return; } Height height = StartingHeight; uint256 prevHash = null; using (await IndexLock.LockAsync()) { if (Index.Count != 0) { var lastIndex = Index.Last(); height = lastIndex.BlockHeight + 1; prevHash = lastIndex.BlockHash; } } if (blockCount - height <= 100) { isIIB = false; } Block block = null; try { block = await RpcClient.GetBlockAsync(height); } catch (RPCException) // if the block didn't come yet { await Task.Delay(1000); continue; } if (blockCount - height <= 2) { OnNewBlock(block); } if (prevHash != null) { // In case of reorg: if (prevHash != block.Header.HashPrevBlock && !isIIB) // There is no reorg in IIB { Logger.LogInfo <IndexBuilderService>($"REORG Invalid Block: {prevHash}"); // 1. Rollback index using (await IndexLock.LockAsync()) { Index.RemoveLast(); } // 2. Serialize Index. (Remove last line.) var lines = File.ReadAllLines(IndexFilePath); File.WriteAllLines(IndexFilePath, lines.Take(lines.Length - 1).ToArray()); // 3. Rollback Bech32UtxoSet if (Bech32UtxoSetHistory.Count != 0) { Bech32UtxoSetHistory.Last().Rollback(Bech32UtxoSet); // The Bech32UtxoSet MUST be recovered to its previous state. Bech32UtxoSetHistory.RemoveLast(); // 4. Serialize Bech32UtxoSet. await File.WriteAllLinesAsync(Bech32UtxoSetFilePath, Bech32UtxoSet .Select(entry => entry.Key.Hash + ":" + entry.Key.N + ":" + ByteHelpers.ToHex(entry.Value.ToCompressedBytes()))); } // 5. Skip the current block. continue; } } if (!isIIB) { if (Bech32UtxoSetHistory.Count >= 100) { Bech32UtxoSetHistory.RemoveFirst(); } Bech32UtxoSetHistory.Add(new ActionHistoryHelper()); } var scripts = new HashSet <Script>(); foreach (var tx in block.Transactions) { // If stop was requested return. // Because this tx iteration can take even minutes // It doesn't need to be accessed with a thread safe fasion with Interlocked through IsRunning, this may have some performance benefit if (_running != 1) { return; } for (int i = 0; i < tx.Outputs.Count; i++) { var output = tx.Outputs[i]; if (!output.ScriptPubKey.IsPayToScriptHash && output.ScriptPubKey.IsWitness) { var outpoint = new OutPoint(tx.GetHash(), i); Bech32UtxoSet.Add(outpoint, output.ScriptPubKey); if (!isIIB) { Bech32UtxoSetHistory.Last().StoreAction(ActionHistoryHelper.Operation.Add, outpoint, output.ScriptPubKey); } scripts.Add(output.ScriptPubKey); } } foreach (var input in tx.Inputs) { var found = Bech32UtxoSet.SingleOrDefault(x => x.Key == input.PrevOut); if (found.Key != default) { Script val = Bech32UtxoSet[input.PrevOut]; Bech32UtxoSet.Remove(input.PrevOut); if (!isIIB) { Bech32UtxoSetHistory.Last().StoreAction(ActionHistoryHelper.Operation.Remove, input.PrevOut, val); } scripts.Add(found.Value); } } } // https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki // The parameter k MUST be set to the first 16 bytes of the hash of the block for which the filter // is constructed.This ensures the key is deterministic while still varying from block to block. var key = block.GetHash().ToBytes().Take(16).ToArray(); GolombRiceFilter filter = null; if (scripts.Count != 0) { filter = GolombRiceFilter.Build(key, scripts.Select(x => x.ToCompressedBytes())); } var filterModel = new FilterModel { BlockHash = block.GetHash(), BlockHeight = height, Filter = filter }; await File.AppendAllLinesAsync(IndexFilePath, new[] { filterModel.ToLine() }); using (await IndexLock.LockAsync()) { Index.Add(filterModel); } if (File.Exists(Bech32UtxoSetFilePath)) { File.Delete(Bech32UtxoSetFilePath); } await File.WriteAllLinesAsync(Bech32UtxoSetFilePath, Bech32UtxoSet .Select(entry => entry.Key.Hash + ":" + entry.Key.N + ":" + ByteHelpers.ToHex(entry.Value.ToCompressedBytes()))); // If not close to the tip, just log debug. // Use height.Value instead of simply height, because it cannot be negative height. if (blockCount - height.Value <= 3 || height % 100 == 0) { Logger.LogInfo <IndexBuilderService>($"Created filter for block: {height}."); } else { Logger.LogDebug <IndexBuilderService>($"Created filter for block: {height}."); } } catch (Exception ex) { Logger.LogDebug <IndexBuilderService>(ex); } } } finally { if (IsStopping) { Interlocked.Exchange(ref _running, 3); } } }); }
/// <summary> /// Initializes the control properties. /// </summary> protected override void SetupControl() { if (StopProcessing) { // Do not process } else { if (string.IsNullOrEmpty(Domain)) { Domain = SiteContext.CurrentSite.DomainName; } // Use HTML 5 output instead of XHTML if (UseHTML5) { StringBuilder sb = new StringBuilder(); sb.Append("<div class=\"fb-activity\" data-width=\"", Width, "\" data-height=\"", Height, "\" data-site=\"", Domain, "\" data-header=\"", ShowHeader, "\" data-recommendations=\"", ShowRecommendations, "\" data-colorscheme=\"", ColorScheme, "\""); if (!string.IsNullOrEmpty(Font)) { sb.Append(" data-font=\"", Font, "\""); } if (!string.IsNullOrEmpty(RefParameter)) { sb.Append(" data-ref=\"", RefParameter, "\""); } sb.Append("></div>"); string fbApiKey = FacebookConnectHelper.GetFacebookApiKey(SiteContext.CurrentSiteName); if (String.IsNullOrEmpty(fbApiKey)) { ShowError(lblErrorMessage, "socialnetworking.facebook.apikeynotset"); } // Register Facebook javascript SDK ScriptHelper.RegisterFacebookJavascriptSDK(Page, LocalizationContext.PreferredCultureCode, fbApiKey); ltlActivityFeed.Text = sb.ToString(); } else { // Iframe code string query = null; string src = "http://www.facebook.com/plugins/activity.php"; if (!string.IsNullOrEmpty(Font)) { query = URLHelper.AddUrlParameter(query, "font", Font); } if (!string.IsNullOrEmpty(RefParameter)) { query = URLHelper.AddUrlParameter(query, "ref", RefParameter); } query = URLHelper.AddUrlParameter(query, "site", Domain); query = URLHelper.AddUrlParameter(query, "header", ShowHeader.ToString()); query = URLHelper.AddUrlParameter(query, "width", Width.ToString()); query = URLHelper.AddUrlParameter(query, "recommendations", ShowRecommendations.ToString()); query = URLHelper.AddUrlParameter(query, "colorscheme", ColorScheme); query = URLHelper.AddUrlParameter(query, "height", Height.ToString()); src = HTMLHelper.EncodeForHtmlAttribute(URLHelper.AppendQuery(src, query)); ltlActivityFeed.Text = "<iframe src=\"" + src + "\""; ltlActivityFeed.Text += " scrolling=\"no\" frameborder=\"0\" style=\"border:none; overflow:hidden; width:" + Width + "px; height:" + Height + "px;\"></iframe>"; } } }
public int GetConfirmationCount(Height bestHeight) => Height == Height.Mempool ? 0 : bestHeight.Value - Height.Value + 1;
public UIWorldListItem(WorldFileData data) { BorderColor = new Color(89, 116, 213) * 0.7f; _dividerTexture = TextureManager.Load("Images/UI/Divider"); _innerPanelTexture = TextureManager.Load("Images/UI/InnerPanelBackground"); _buttonCloudActiveTexture = TextureManager.Load("Images/UI/ButtonCloudActive"); _buttonCloudInactiveTexture = TextureManager.Load("Images/UI/ButtonCloudInactive"); _buttonFavoriteActiveTexture = TextureManager.Load("Images/UI/ButtonFavoriteActive"); _buttonFavoriteInactiveTexture = TextureManager.Load("Images/UI/ButtonFavoriteInactive"); _buttonPlayTexture = TextureManager.Load("Images/UI/ButtonPlay"); _buttonDeleteTexture = TextureManager.Load("Images/UI/ButtonDelete"); Height.Set(96f, 0f); Width.Set(0f, 1f); SetPadding(6f); _data = data; _worldIcon = new UIImage(GetIcon()); _worldIcon.Left.Set(4f, 0f); _worldIcon.OnDoubleClick += PlayGame; Append(_worldIcon); UIImageButton uIImageButton = new UIImageButton(_buttonPlayTexture); uIImageButton.VAlign = 1f; uIImageButton.Left.Set(4f, 0f); uIImageButton.OnClick += PlayGame; base.OnDoubleClick += PlayGame; uIImageButton.OnMouseOver += PlayMouseOver; uIImageButton.OnMouseOut += ButtonMouseOut; Append(uIImageButton); UIImageButton uIImageButton2 = new UIImageButton(_data.IsFavorite ? _buttonFavoriteActiveTexture : _buttonFavoriteInactiveTexture); uIImageButton2.VAlign = 1f; uIImageButton2.Left.Set(28f, 0f); uIImageButton2.OnClick += FavoriteButtonClick; uIImageButton2.OnMouseOver += FavoriteMouseOver; uIImageButton2.OnMouseOut += ButtonMouseOut; uIImageButton2.SetVisibility(1f, _data.IsFavorite ? 0.8f : 0.4f); Append(uIImageButton2); if (SocialAPI.Cloud != null) { UIImageButton uIImageButton3 = new UIImageButton(_data.IsCloudSave ? _buttonCloudActiveTexture : _buttonCloudInactiveTexture); uIImageButton3.VAlign = 1f; uIImageButton3.Left.Set(52f, 0f); uIImageButton3.OnClick += CloudButtonClick; uIImageButton3.OnMouseOver += CloudMouseOver; uIImageButton3.OnMouseOut += ButtonMouseOut; Append(uIImageButton3); } UIImageButton uIImageButton4 = new UIImageButton(_buttonDeleteTexture); uIImageButton4.VAlign = 1f; uIImageButton4.HAlign = 1f; uIImageButton4.OnClick += DeleteButtonClick; uIImageButton4.OnMouseOver += DeleteMouseOver; uIImageButton4.OnMouseOut += DeleteMouseOut; _deleteButton = uIImageButton4; if (!_data.IsFavorite) { Append(uIImageButton4); } _buttonLabel = new UIText(""); _buttonLabel.VAlign = 1f; _buttonLabel.Left.Set(80f, 0f); _buttonLabel.Top.Set(-3f, 0f); Append(_buttonLabel); _deleteButtonLabel = new UIText(""); _deleteButtonLabel.VAlign = 1f; _deleteButtonLabel.HAlign = 1f; _deleteButtonLabel.Left.Set(-30f, 0f); _deleteButtonLabel.Top.Set(-3f, 0f); Append(_deleteButtonLabel); }
public override string ToString() { return("Texture: " + Width.ToString() + "x" + Height.ToString() + ": " + Name); }
public override void OnInitialize() { Width.Set(64, 0f); Height.Set(64, 0f); }
public override void Save(XmlDocument doc, XmlNode node, MpeParser parser, MpeControl reference) { if (reference == null) { // Update reference.xml file if (node.Name != "controls") { throw new MpeParserException("Invalid root node <" + node.Name + "> provided."); } // Update the skin node XmlNode skin = node.SelectSingleNode("skin"); if (skin == null) { throw new MpeParserException( "Invalid reference.xml file. The <skin> element must be the first child in the document."); } skin.RemoveAll(); parser.SetValue(doc, skin, "width", Width.ToString()); parser.SetValue(doc, skin, "height", Height.ToString()); // Update the image control node that defines the window background XmlNode image = skin.NextSibling; if (image == null || image.Name.Equals("control") == false) { throw new MpeParserException( "Invalid reference.xml file. A <control> element of type image must follow the <skin> element."); } XmlNode test = image.SelectSingleNode("type"); if (test == null || test.InnerXml.Equals("image") == false) { throw new MpeParserException( "Invalid reference.xml file. A <control> element of type image must follow the <skin> element."); } image.RemoveAll(); backImage.Save(doc, image, parser, null); } else { // Update screen.xml file if (node == null || node.Name.Equals("window") == false) { throw new MpeParserException("Invalid root node <" + node.Name + "> provided. Looking for a <window> element."); } node.RemoveAll(); if (screenType != MpeScreenType.Window) { parser.SetValue(doc, node, "type", screenType.ToString().ToLower()); } parser.SetValue(doc, node, "id", Id.ToString()); parser.SetValue(doc, node, "defaultcontrol", DefaultControl.ToString()); parser.SetValue(doc, node, "allowoverlay", AllowOverlay ? "yes" : "no"); parser.SetValue(doc, node, "autohidetopbar", AutohideTopbar ? "yes" : "no"); XmlElement controls = doc.CreateElement("controls"); node.AppendChild(controls); if (ScreenType == MpeScreenType.Dialog) { MpeGroup dg = DialogGroup; //if (dg.TextureBack != null) { XmlElement image = doc.CreateElement("control"); dg.TextureBackImage.Save(doc, image, parser, parser.GetControl(MpeControlType.Image)); controls.AppendChild(image); //} for (int i = dg.Controls.Count - 1; i >= 0; i--) { if (dg.Controls[i] is MpeControl) { MpeControl control = (MpeControl)dg.Controls[i]; try { XmlElement element = doc.CreateElement("control"); MpeControl referenceControl = parser.GetControl(control.Type); control.Save(doc, element, parser, referenceControl); controls.AppendChild(element); } catch (Exception e) { MpeLog.Debug(e); MpeLog.Error(e); throw new MpeParserException(e.Message); } } } } else { if (TextureBack != null) { XmlElement image = doc.CreateElement("control"); backImage.Save(doc, image, parser, parser.GetControl(MpeControlType.Image)); controls.AppendChild(image); } for (int i = Controls.Count - 1; i >= 0; i--) { if (Controls[i] is MpeControl) { MpeControl control = (MpeControl)Controls[i]; try { XmlElement element = doc.CreateElement("control"); MpeControl referenceControl = parser.GetControl(control.Type); control.Save(doc, element, parser, referenceControl); controls.AppendChild(element); } catch (Exception e) { MpeLog.Debug(e); MpeLog.Error(e); throw new MpeParserException(e.Message); } } } } } }
private async void LoadImage() { if (_currentTask != null) { _currentTask.Cancel(); } TaskParameter imageLoader = null; var ffSource = await FFImageSourceBinding.GetImageSourceBinding(Source); if (ffSource == null) { if (internalImage != null) { await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { internalImage.Source = null; }); } } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Url) { imageLoader = ImageService.LoadUrl(ffSource.Path, TimeSpan.FromDays(CacheDuration)); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.CompiledResource) { imageLoader = ImageService.LoadCompiledResource(ffSource.Path); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.ApplicationBundle) { imageLoader = ImageService.LoadFileFromApplicationBundle(ffSource.Path); } else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Filepath) { imageLoader = ImageService.LoadFile(ffSource.Path); } if (imageLoader != null) { // LoadingPlaceholder if (LoadingPlaceholder != null) { var placeholderSource = await FFImageSourceBinding.GetImageSourceBinding(LoadingPlaceholder); if (placeholderSource != null) { imageLoader.LoadingPlaceholder(placeholderSource.Path, placeholderSource.ImageSource); } } // ErrorPlaceholder if (ErrorPlaceholder != null) { var placeholderSource = await FFImageSourceBinding.GetImageSourceBinding(ErrorPlaceholder); if (placeholderSource != null) { imageLoader.ErrorPlaceholder(placeholderSource.Path, placeholderSource.ImageSource); } } // Downsample if (DownsampleToViewSize && (Width > 0 || Height > 0)) { if (Height > Width) { imageLoader.DownSample(height: Height.PointsToPixels()); } else { imageLoader.DownSample(width: Width.PointsToPixels()); } } else if (DownsampleToViewSize && (MinWidth > 0 || MinHeight > 0)) { if (MinHeight > MinWidth) { imageLoader.DownSample(height: MinHeight.PointsToPixels()); } else { imageLoader.DownSample(width: MinWidth.PointsToPixels()); } } else if ((int)DownsampleHeight != 0 || (int)DownsampleWidth != 0) { if (DownsampleHeight > DownsampleWidth) { imageLoader.DownSample(height: DownsampleUseDipUnits ? DownsampleHeight.PointsToPixels() : (int)DownsampleHeight); } else { imageLoader.DownSample(width: DownsampleUseDipUnits ? DownsampleWidth.PointsToPixels() : (int)DownsampleWidth); } } // Downsample mode imageLoader.DownSampleMode(DownsampleMode); // RetryCount if (RetryCount > 0) { imageLoader.Retry(RetryCount, RetryDelay); } // FadeAnimation imageLoader.FadeAnimation(FadeAnimationEnabled); // TransformPlaceholders imageLoader.TransformPlaceholders(TransformPlaceholders); // Transformations if (Transformations != null && Transformations.Count != 0) { imageLoader.Transform(Transformations); } _currentTask = imageLoader.Into(internalImage); } }
public override int GetHashCode() { int hash = 1; if (CameraDev.Length != 0) { hash ^= CameraDev.GetHashCode(); } if (FrameId.Length != 0) { hash ^= FrameId.GetHashCode(); } if (PixelFormat.Length != 0) { hash ^= PixelFormat.GetHashCode(); } if (IoMethod != 0) { hash ^= IoMethod.GetHashCode(); } if (Width != 0) { hash ^= Width.GetHashCode(); } if (Height != 0) { hash ^= Height.GetHashCode(); } if (FrameRate != 0) { hash ^= FrameRate.GetHashCode(); } if (Monochrome != false) { hash ^= Monochrome.GetHashCode(); } if (Brightness != 0) { hash ^= Brightness.GetHashCode(); } if (Contrast != 0) { hash ^= Contrast.GetHashCode(); } if (Saturation != 0) { hash ^= Saturation.GetHashCode(); } if (Sharpness != 0) { hash ^= Sharpness.GetHashCode(); } if (Gain != 0) { hash ^= Gain.GetHashCode(); } if (AutoFocus != false) { hash ^= AutoFocus.GetHashCode(); } if (Focus != 0) { hash ^= Focus.GetHashCode(); } if (AutoExposure != false) { hash ^= AutoExposure.GetHashCode(); } if (Exposure != 0) { hash ^= Exposure.GetHashCode(); } if (AutoWhiteBalance != false) { hash ^= AutoWhiteBalance.GetHashCode(); } if (WhiteBalance != 0) { hash ^= WhiteBalance.GetHashCode(); } if (BytesPerPixel != 0) { hash ^= BytesPerPixel.GetHashCode(); } if (TriggerInternal != 0) { hash ^= TriggerInternal.GetHashCode(); } if (TriggerFps != 0) { hash ^= TriggerFps.GetHashCode(); } if (ChannelName.Length != 0) { hash ^= ChannelName.GetHashCode(); } if (DeviceWaitMs != 0) { hash ^= DeviceWaitMs.GetHashCode(); } if (SpinRate != 0) { hash ^= SpinRate.GetHashCode(); } if (OutputType != 0) { hash ^= OutputType.GetHashCode(); } if (compressConf_ != null) { hash ^= CompressConf.GetHashCode(); } return(hash); }
/// <summary> /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object. /// </summary> protected override void Render(ISvgRenderer renderer) { if (!Visible || !Displayable) { return; } if (Width.Value > 0.0f && Height.Value > 0.0f && this.Href != null) { var img = GetImage(this.Href); if (img != null) { RectangleF srcRect; var bmp = img as Image; var svg = img as SvgFragment; if (bmp != null) { srcRect = new RectangleF(0, 0, bmp.Width, bmp.Height); } else if (svg != null) { srcRect = new RectangleF(new PointF(0, 0), svg.GetDimensions()); } else { return; } var destClip = new RectangleF(this.Location.ToDeviceValue(renderer, this), new SizeF(Width.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this), Height.ToDeviceValue(renderer, UnitRenderingType.Vertical, this))); RectangleF destRect = destClip; this.PushTransforms(renderer); renderer.SetClip(new Region(destClip), CombineMode.Intersect); this.SetClip(renderer); if (AspectRatio != null && AspectRatio.Align != SvgPreserveAspectRatio.none) { var fScaleX = destClip.Width / srcRect.Width; var fScaleY = destClip.Height / srcRect.Height; var xOffset = 0.0f; var yOffset = 0.0f; if (AspectRatio.Slice) { fScaleX = Math.Max(fScaleX, fScaleY); fScaleY = Math.Max(fScaleX, fScaleY); } else { fScaleX = Math.Min(fScaleX, fScaleY); fScaleY = Math.Min(fScaleX, fScaleY); } switch (AspectRatio.Align) { case SvgPreserveAspectRatio.xMinYMin: break; case SvgPreserveAspectRatio.xMidYMin: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; break; case SvgPreserveAspectRatio.xMaxYMin: xOffset = (destClip.Width - srcRect.Width * fScaleX); break; case SvgPreserveAspectRatio.xMinYMid: yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMidYMid: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMaxYMid: xOffset = (destClip.Width - srcRect.Width * fScaleX); yOffset = (destClip.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatio.xMinYMax: yOffset = (destClip.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatio.xMidYMax: xOffset = (destClip.Width - srcRect.Width * fScaleX) / 2; yOffset = (destClip.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatio.xMaxYMax: xOffset = (destClip.Width - srcRect.Width * fScaleX); yOffset = (destClip.Height - srcRect.Height * fScaleY); break; } destRect = new RectangleF(destClip.X + xOffset, destClip.Y + yOffset, srcRect.Width * fScaleX, srcRect.Height * fScaleY); } if (bmp != null) { renderer.DrawImage(bmp, destRect, srcRect, GraphicsUnit.Pixel); bmp.Dispose(); } else if (svg != null) { var currOffset = new PointF(renderer.Transform.OffsetX, renderer.Transform.OffsetY); renderer.TranslateTransform(-currOffset.X, -currOffset.Y); renderer.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height); renderer.TranslateTransform(currOffset.X + destRect.X, currOffset.Y + destRect.Y); renderer.SetBoundable(new GenericBoundable(srcRect)); svg.RenderElement(renderer); renderer.PopBoundable(); } this.ResetClip(renderer); this.PopTransforms(renderer); } // TODO: cache images... will need a shared context for this // TODO: support preserveAspectRatio, etc } }
/// <summary> /// Unpacks the message from a MessagePack object /// This method should not be called directly, use deserialize instead. /// </summary> /// <param name="unpacker">The unpacker</param> public void UnpackFromMessage(Unpacker unpacker) { string dcs, dac, dad, dbd, dbb, day, dau, dag, dai, daj, dak, dcg; int dbc; if (!unpacker.IsMapHeader) throw SerializationExceptions.NewIsNotMapHeader(); if (UnpackHelpers.GetItemsCount(unpacker) != MapCount) throw SerializationExceptions.NewUnexpectedArrayLength(MapCount, UnpackHelpers.GetItemsCount(unpacker)); for (var i = 0; i < MapCount; i++) { string key; if (!unpacker.ReadString(out key)) throw SerializationExceptions.NewUnexpectedEndOfStream(); switch (key) { case "DCS": { if (!unpacker.ReadString(out dcs)) throw SerializationExceptions.NewMissingProperty("dcs"); Dcs = dcs; break; } case "DAC": { if (!unpacker.ReadString(out dac)) throw SerializationExceptions.NewMissingProperty("dac"); Dac = dac; break; } case "DAD": { if (!unpacker.ReadString(out dad)) throw SerializationExceptions.NewMissingProperty("dad"); Dad = dad; break; } case "DBD": { if (!unpacker.ReadString(out dbd)) throw SerializationExceptions.NewMissingProperty("dbd"); Dbd = DateTime.Parse(dbd); break; } case "DBB": { if (!unpacker.ReadString(out dbb)) throw SerializationExceptions.NewMissingProperty("dbb"); Dbb = DateTime.Parse(dbb); break; } case "DBC": { if (!unpacker.ReadInt32(out dbc)) throw SerializationExceptions.NewMissingProperty("dbc"); Dbc = (Sex) dbc; break; } case "DAY": { if (!unpacker.ReadString(out day)) throw SerializationExceptions.NewMissingProperty("day"); Day = GetEyeColor(day); break; } case "DAU": { if (!unpacker.ReadString(out dau)) throw SerializationExceptions.NewMissingProperty("dau"); Dau = new Height {AnsiFormat = dau}; break; } case "DAG": { if (!unpacker.ReadString(out dag)) throw SerializationExceptions.NewMissingProperty("dag"); Dag = dag; break; } case "DAI": { if (!unpacker.ReadString(out dai)) throw SerializationExceptions.NewMissingProperty("dai"); Dai = dai; break; } case "DAJ": { if (!unpacker.ReadString(out daj)) throw SerializationExceptions.NewMissingProperty("daj"); Daj = daj; break; } case "DAK": { if (!unpacker.ReadString(out dak)) throw SerializationExceptions.NewMissingProperty("dak"); Dak = new PostalCode {AnsiFormat = dak}; break; } case "DCG": { if (!unpacker.ReadString(out dcg)) throw SerializationExceptions.NewMissingProperty("dcg"); Dcg = dcg; break; } case "ZAA": { if (!unpacker.Read()) throw SerializationExceptions.NewMissingProperty("zaa"); var ms = new MemoryStream(unpacker.LastReadData.AsBinary()); Image = Image.FromStream(ms); break; } case "ZAB": { if (!unpacker.Read()) throw SerializationExceptions.NewMissingProperty("zab"); Fingerprint = new Fingerprint {AsIsoTemplate = unpacker.LastReadData.AsBinary()}; break; } } } }
/// <summary> /// Revises the height. /// </summary> /// <param name="height">The height.</param> public virtual void ReviseHeight( Height height ) { Check.IsNotNull ( height, "height is required." ); Height = height; }
WoWPoint mapToWorldCoords(float x, float y, uint mapId, Height ht) { WoWPoint worldPoint = new WoWPoint(); WoWDb.DbTable worldMapArea = StyxWoW.Db[ClientDb.WorldMapArea]; WoWDb.Row worldMapAreaFields = worldMapArea.GetRow(mapId); float ay = worldMapAreaFields.GetField<float>(4); float by = worldMapAreaFields.GetField<float>(5); float ax = worldMapAreaFields.GetField<float>(6); float bx = worldMapAreaFields.GetField<float>(7); worldPoint.X = ax + (y * (bx - ax)); worldPoint.Y = ay + (x * (by - ay)); try { worldPoint.Z = ht == Height.High ? Navigator.FindHeights(worldPoint.X, worldPoint.Y).Max() : Navigator.FindHeights(worldPoint.X, worldPoint.Y).Min(); } catch { return TryGetHeight(worldPoint, ht); } return worldPoint; }
public static string GetRange(Height height) { return Ranges[(byte)height - 1]; }
List<WoWPoint> RouteToWoWPoint(List<string> rawPoints, uint mapId, Height ht, int status) { List<WoWPoint> points = new List<WoWPoint>(); for (int n = 2; n < rawPoints.Count; n++) { float x, y; uint coord; uint.TryParse(rawPoints[n], out coord); //local ex, ey = floor(point / 10000) / 10000, (point % 10000) / 10000 x = (float)Math.Floor((float)coord / 10000f) / 10000f; y = ((float)coord % 10000f) / 10000f; points.Add(mapToWorldCoords(x, y, mapId, ht)); int retCnt = RawImport.Count; /* TODO - REENABLE THIS int process1 = (status * 100) / retCnt; int process2 = ((status + 1) * 100) / retCnt; int process3 = (n * (process2 - process1) / rawPoints.Count) + process1; Gui.UpdateProgressBar(process3); * * */ } return points; }
public Piece(Height height, Shape shape, Top top, Color color) { Initialize(height, shape, top, color); }
public async Task SendTestsAsync() { (string password, IRPCClient rpc, Network network, _, ServiceConfiguration serviceConfiguration, BitcoinStore bitcoinStore, Backend.Global global) = await Common.InitializeTestEnvironmentAsync(RegTestFixture, 1); bitcoinStore.IndexStore.NewFilter += Common.Wallet_NewFilterProcessed; // Create the services. // 1. Create connection service. var nodes = new NodesGroup(global.Config.Network, requirements: Constants.NodeRequirements); nodes.ConnectedNodes.Add(await RegTestFixture.BackendRegTestNode.CreateNewP2pNodeAsync()); // 2. Create mempool service. Node node = await RegTestFixture.BackendRegTestNode.CreateNewP2pNodeAsync(); node.Behaviors.Add(bitcoinStore.CreateUntrustedP2pBehavior()); // 3. Create wasabi synchronizer service. var wasabiClientFactory = new WasabiClientFactory(torEndPoint: null, backendUriGetter: () => new Uri(RegTestFixture.BackendEndPoint)); var synchronizer = new WasabiSynchronizer(rpc.Network, bitcoinStore, wasabiClientFactory); // 4. Create key manager service. var keyManager = KeyManager.CreateNew(out _, password); // 5. Create wallet service. var workDir = Helpers.Common.GetWorkDir(); CachedBlockProvider blockProvider = new CachedBlockProvider( new P2pBlockProvider(nodes, null, synchronizer, serviceConfiguration, network), bitcoinStore.BlockRepository); var walletManager = new WalletManager(network, new WalletDirectories(workDir)); walletManager.RegisterServices(bitcoinStore, synchronizer, nodes, serviceConfiguration, synchronizer, blockProvider); // Get some money, make it confirm. var key = keyManager.GetNextReceiveKey("foo label", out _); var key2 = keyManager.GetNextReceiveKey("foo label", out _); var txId = await rpc.SendToAddressAsync(key.GetP2wpkhAddress(network), Money.Coins(1m)); Assert.NotNull(txId); await rpc.GenerateAsync(1); var txId2 = await rpc.SendToAddressAsync(key2.GetP2wpkhAddress(network), Money.Coins(1m)); Assert.NotNull(txId2); await rpc.GenerateAsync(1); try { Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0); nodes.Connect(); // Start connection service. node.VersionHandshake(); // Start mempool service. synchronizer.Start(requestInterval: TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(5), 10000); // Start wasabi synchronizer service. // Wait until the filter our previous transaction is present. var blockCount = await rpc.GetBlockCountAsync(); await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), blockCount); var wallet = await walletManager.AddAndStartWalletAsync(keyManager); var broadcaster = new TransactionBroadcaster(network, bitcoinStore, synchronizer, nodes, walletManager, rpc); var waitCount = 0; while (wallet.Coins.Sum(x => x.Amount) == Money.Zero) { await Task.Delay(1000); waitCount++; if (waitCount >= 21) { Logger.LogInfo("Funding transaction to the wallet did not arrive."); return; // Very rarely this test fails. I have no clue why. Probably because all these RegTests are interconnected, anyway let's not bother the CI with it. } } var scp = new Key().ScriptPubKey; var res2 = wallet.BuildTransaction(password, new PaymentIntent(scp, Money.Coins(0.05m), label: "foo"), FeeStrategy.CreateFromConfirmationTarget(5), allowUnconfirmed: false); Assert.NotNull(res2.Transaction); Assert.Single(res2.OuterWalletOutputs); Assert.Equal(scp, res2.OuterWalletOutputs.Single().ScriptPubKey); Assert.Single(res2.InnerWalletOutputs); Assert.True(res2.Fee > Money.Satoshis(2 * 100)); // since there is a sanity check of 2sat/vb in the server Assert.InRange(res2.FeePercentOfSent, 0, 1); Assert.Single(res2.SpentCoins); var spentCoin = Assert.Single(res2.SpentCoins); Assert.Contains(new[] { key.P2wpkhScript, key2.P2wpkhScript }, x => x == spentCoin.ScriptPubKey); Assert.Equal(Money.Coins(1m), res2.SpentCoins.Single().Amount); Assert.False(res2.SpendsUnconfirmed); await broadcaster.SendTransactionAsync(res2.Transaction); Assert.Contains(res2.InnerWalletOutputs.Single(), wallet.Coins); #region Basic Script receive = keyManager.GetNextReceiveKey("Basic", out _).P2wpkhScript; Money amountToSend = wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) / 2; var res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true); foreach (SmartCoin coin in res.SpentCoins) { Assert.False(coin.CoinJoinInProgress); Assert.True(coin.Confirmed); Assert.Null(coin.SpenderTransaction); Assert.False(coin.IsSpent()); } Assert.Equal(2, res.InnerWalletOutputs.Count()); Assert.Empty(res.OuterWalletOutputs); var activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); var changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive); Assert.Equal(receive, activeOutput.ScriptPubKey); Assert.Equal(amountToSend, activeOutput.Amount); if (res.SpentCoins.Sum(x => x.Amount) - activeOutput.Amount == res.Fee) // this happens when change is too small { Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == activeOutput.Amount); Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}"); } Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"TxId: {res.Transaction.GetHash()}"); var foundReceive = false; Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2); foreach (var output in res.Transaction.Transaction.Outputs) { if (output.ScriptPubKey == receive) { foundReceive = true; Assert.Equal(amountToSend, output.Value); } } Assert.True(foundReceive); await broadcaster.SendTransactionAsync(res.Transaction); #endregion Basic #region SubtractFeeFromAmount receive = keyManager.GetNextReceiveKey("SubtractFeeFromAmount", out _).P2wpkhScript; amountToSend = wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) / 3; res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, subtractFee: true, label: "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Equal(2, res.InnerWalletOutputs.Count()); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive); Assert.Equal(receive, activeOutput.ScriptPubKey); Assert.Equal(amountToSend - res.Fee, activeOutput.Amount); Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount); Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"TxId: {res.Transaction.GetHash()}"); foundReceive = false; Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2); foreach (var output in res.Transaction.Transaction.Outputs) { if (output.ScriptPubKey == receive) { foundReceive = true; Assert.Equal(amountToSend - res.Fee, output.Value); } } Assert.True(foundReceive); #endregion SubtractFeeFromAmount #region LowFee res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Equal(2, res.InnerWalletOutputs.Count()); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive); Assert.Equal(receive, activeOutput.ScriptPubKey); Assert.Equal(amountToSend, activeOutput.Amount); Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount); Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"TxId: {res.Transaction.GetHash()}"); foundReceive = false; Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2); foreach (var output in res.Transaction.Transaction.Outputs) { if (output.ScriptPubKey == receive) { foundReceive = true; Assert.Equal(amountToSend, output.Value); } } Assert.True(foundReceive); #endregion LowFee #region MediumFee res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.OneDayConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Equal(2, res.InnerWalletOutputs.Count()); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive); Assert.Equal(receive, activeOutput.ScriptPubKey); Assert.Equal(amountToSend, activeOutput.Amount); Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount); Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"TxId: {res.Transaction.GetHash()}"); foundReceive = false; Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2); foreach (var output in res.Transaction.Transaction.Outputs) { if (output.ScriptPubKey == receive) { foundReceive = true; Assert.Equal(amountToSend, output.Value); } } Assert.True(foundReceive); #endregion MediumFee #region HighFee res = wallet.BuildTransaction(password, new PaymentIntent(receive, amountToSend, label: "foo"), FeeStrategy.TwentyMinutesConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Equal(2, res.InnerWalletOutputs.Count()); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); changeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey != receive); Assert.Equal(receive, activeOutput.ScriptPubKey); Assert.Equal(amountToSend, activeOutput.Amount); Assert.Contains(res.Transaction.Transaction.Outputs, x => x.Value == changeOutput.Amount); Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"Change Output: {changeOutput.Amount.ToString(false, true)} {changeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"TxId: {res.Transaction.GetHash()}"); foundReceive = false; Assert.InRange(res.Transaction.Transaction.Outputs.Count, 1, 2); foreach (var output in res.Transaction.Transaction.Outputs) { if (output.ScriptPubKey == receive) { foundReceive = true; Assert.Equal(amountToSend, output.Value); } } Assert.True(foundReceive); Assert.InRange(res.Fee, Money.Zero, res.Fee); Assert.InRange(res.Fee, res.Fee, res.Fee); await broadcaster.SendTransactionAsync(res.Transaction); #endregion HighFee #region MaxAmount receive = keyManager.GetNextReceiveKey("MaxAmount", out _).P2wpkhScript; res = wallet.BuildTransaction(password, new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Single(res.InnerWalletOutputs); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(); Assert.Equal(receive, activeOutput.ScriptPubKey); Assert.Single(res.Transaction.Transaction.Outputs); var maxBuiltTxOutput = res.Transaction.Transaction.Outputs.Single(); Assert.Equal(receive, maxBuiltTxOutput.ScriptPubKey); Assert.Equal(wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) - res.Fee, maxBuiltTxOutput.Value); await broadcaster.SendTransactionAsync(res.Transaction); #endregion MaxAmount #region InputSelection receive = keyManager.GetNextReceiveKey("InputSelection", out _).P2wpkhScript; var inputCountBefore = res.SpentCoins.Count(); res = wallet.BuildTransaction(password, new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true, allowedInputs: wallet.Coins.Where(x => x.IsAvailable()).Select(x => x.OutPoint).Take(1)); Assert.Single(res.InnerWalletOutputs); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); Assert.True(inputCountBefore >= res.SpentCoins.Count()); Assert.Equal(res.SpentCoins.Count(), res.Transaction.Transaction.Inputs.Count); Assert.Equal(receive, activeOutput.ScriptPubKey); Logger.LogInfo($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogInfo($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogInfo($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogInfo($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogInfo($"TxId: {res.Transaction.GetHash()}"); Assert.Single(res.Transaction.Transaction.Outputs); res = wallet.BuildTransaction(password, new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "foo"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true, allowedInputs: new[] { res.SpentCoins.Select(x => x.OutPoint).First() }); Assert.Single(res.InnerWalletOutputs); Assert.Empty(res.OuterWalletOutputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); Assert.Single(res.Transaction.Transaction.Inputs); Assert.Single(res.Transaction.Transaction.Outputs); Assert.Single(res.SpentCoins); #endregion InputSelection #region Labeling Script receive2 = keyManager.GetNextReceiveKey("foo", out _).P2wpkhScript; res = wallet.BuildTransaction(password, new PaymentIntent(receive2, MoneyRequest.CreateAllRemaining(), "my label"), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Single(res.InnerWalletOutputs); Assert.Equal("foo, my label", res.InnerWalletOutputs.Single().HdPubKey.Label); amountToSend = wallet.Coins.Where(x => x.IsAvailable()).Sum(x => x.Amount) / 3; res = wallet.BuildTransaction( password, new PaymentIntent( new DestinationRequest(new Key(), amountToSend, label: "outgoing"), new DestinationRequest(new Key(), amountToSend, label: "outgoing2")), FeeStrategy.SevenDaysConfirmationTargetStrategy, allowUnconfirmed: true); Assert.Single(res.InnerWalletOutputs); Assert.Equal(2, res.OuterWalletOutputs.Count()); IEnumerable <string> change = res.InnerWalletOutputs.Single().HdPubKey.Label.Labels; Assert.Contains("outgoing", change); Assert.Contains("outgoing2", change); await broadcaster.SendTransactionAsync(res.Transaction); IEnumerable <SmartCoin> unconfirmedCoins = wallet.Coins.Where(x => x.Height == Height.Mempool).ToArray(); IEnumerable <string> unconfirmedCoinLabels = unconfirmedCoins.SelectMany(x => x.HdPubKey.Label.Labels).ToArray(); Assert.Contains("outgoing", unconfirmedCoinLabels); Assert.Contains("outgoing2", unconfirmedCoinLabels); IEnumerable <string> allKeyLabels = keyManager.GetKeys().SelectMany(x => x.Label.Labels); Assert.Contains("outgoing", allKeyLabels); Assert.Contains("outgoing2", allKeyLabels); Interlocked.Exchange(ref Common.FiltersProcessedByWalletCount, 0); await rpc.GenerateAsync(1); await Common.WaitForFiltersToBeProcessedAsync(TimeSpan.FromSeconds(120), 1); var bestHeight = new Height(bitcoinStore.SmartHeaderChain.TipHeight); IEnumerable <string> confirmedCoinLabels = wallet.Coins.Where(x => x.Height == bestHeight).SelectMany(x => x.HdPubKey.Label.Labels); Assert.Contains("outgoing", confirmedCoinLabels); Assert.Contains("outgoing2", confirmedCoinLabels); allKeyLabels = keyManager.GetKeys().SelectMany(x => x.Label.Labels); Assert.Contains("outgoing", allKeyLabels); Assert.Contains("outgoing2", allKeyLabels); #endregion Labeling #region AllowedInputsDisallowUnconfirmed inputCountBefore = res.SpentCoins.Count(); receive = keyManager.GetNextReceiveKey("AllowedInputsDisallowUnconfirmed", out _).P2wpkhScript; var allowedInputs = wallet.Coins.Where(x => x.IsAvailable()).Select(x => x.OutPoint).Take(1); var toSend = new PaymentIntent(receive, MoneyRequest.CreateAllRemaining(), "fizz"); // covers: // disallow unconfirmed with allowed inputs res = wallet.BuildTransaction(password, toSend, FeeStrategy.TwentyMinutesConfirmationTargetStrategy, false, allowedInputs: allowedInputs); activeOutput = res.InnerWalletOutputs.Single(x => x.ScriptPubKey == receive); Assert.Single(res.InnerWalletOutputs); Assert.Empty(res.OuterWalletOutputs); Assert.Equal(receive, activeOutput.ScriptPubKey); Logger.LogDebug($"{nameof(res.Fee)}: {res.Fee}"); Logger.LogDebug($"{nameof(res.FeePercentOfSent)}: {res.FeePercentOfSent} %"); Logger.LogDebug($"{nameof(res.SpendsUnconfirmed)}: {res.SpendsUnconfirmed}"); Logger.LogDebug($"Active Output: {activeOutput.Amount.ToString(false, true)} {activeOutput.ScriptPubKey.GetDestinationAddress(network)}"); Logger.LogDebug($"TxId: {res.Transaction.GetHash()}"); Assert.True(inputCountBefore >= res.SpentCoins.Count()); Assert.False(res.SpendsUnconfirmed); Assert.Single(res.Transaction.Transaction.Inputs); Assert.Single(res.Transaction.Transaction.Outputs); Assert.Single(res.SpentCoins); Assert.True(inputCountBefore >= res.SpentCoins.Count()); Assert.Equal(res.SpentCoins.Count(), res.Transaction.Transaction.Inputs.Count); #endregion AllowedInputsDisallowUnconfirmed #region CustomChange // covers: // customchange // feePc > 1 var k1 = new Key(); var k2 = new Key(); res = wallet.BuildTransaction( password, new PaymentIntent( new DestinationRequest(k1, MoneyRequest.CreateChange()), new DestinationRequest(k2, Money.Coins(0.0003m), label: "outgoing")), FeeStrategy.TwentyMinutesConfirmationTargetStrategy); Assert.Contains(k1.ScriptPubKey, res.OuterWalletOutputs.Select(x => x.ScriptPubKey)); Assert.Contains(k2.ScriptPubKey, res.OuterWalletOutputs.Select(x => x.ScriptPubKey)); #endregion CustomChange #region FeePcHigh res = wallet.BuildTransaction( password, new PaymentIntent(new Key(), Money.Coins(0.0003m), label: "outgoing"), FeeStrategy.TwentyMinutesConfirmationTargetStrategy); Assert.True(res.FeePercentOfSent > 1); var newChangeK = keyManager.GenerateNewKey("foo", KeyState.Clean, isInternal: true); res = wallet.BuildTransaction( password, new PaymentIntent( new DestinationRequest(newChangeK.P2wpkhScript, MoneyRequest.CreateChange(), "boo"), new DestinationRequest(new Key(), Money.Coins(0.0003m), label: "outgoing")), FeeStrategy.TwentyMinutesConfirmationTargetStrategy); Assert.True(res.FeePercentOfSent > 1); Assert.Single(res.OuterWalletOutputs); Assert.Single(res.InnerWalletOutputs); SmartCoin changeRes = res.InnerWalletOutputs.Single(); Assert.Equal(newChangeK.P2wpkhScript, changeRes.ScriptPubKey); Assert.Equal(newChangeK.Label, changeRes.HdPubKey.Label); Assert.Equal(KeyState.Clean, newChangeK.KeyState); // Still clean, because the tx wasn't yet propagated. #endregion FeePcHigh } finally { bitcoinStore.IndexStore.NewFilter -= Common.Wallet_NewFilterProcessed; await walletManager.RemoveAndStopAllAsync(CancellationToken.None); // Dispose wasabi synchronizer service. if (synchronizer is { })
protected override void updateInternal() { if (!roomsVisited.Contains(GameplayManager.ActiveZone.TopLeftPosition)) { roomsVisited.Add(GameplayManager.ActiveZone.TopLeftPosition); this.model.setStat("roomsVisited", this.model.getStat("roomsVisited") + 1); } #region Gather Movement Inputs if (!IsAirborne && InputSet.getInstance().getButton(InputsEnum.BUTTON_1) && (m_previousHeight != Height.Ball || Inventory.HasItem(Item.SpringBall))) { m_attemptedVelocity.Y -= 40; } // Debug movement, flies through stuff if (InputSet.getInstance().getButton(InputsEnum.BUTTON_4)) { Vector2 debugDp = new Vector2(); if (InputSet.getInstance().getLeftDirectionalX() > 0) debugDp.X = 10; if (InputSet.getInstance().getLeftDirectionalX() < 0) debugDp.X = -10; if (InputSet.getInstance().getLeftDirectionalY() > 0) debugDp.Y = -10; if (InputSet.getInstance().getLeftDirectionalY() < 0) debugDp.Y = 10; this.getCollider().move(debugDp); this.m_attemptedVelocity = Vector2.Zero; if (InputSet.getInstance().getButton(InputsEnum.BUTTON_3)) { Direction d = Direction.Up; bool dirSelected = true; if (InputSet.getInstance().getLeftDirectionalX() > 0) d = Direction.Right; else if (InputSet.getInstance().getLeftDirectionalX() < 0) d = Direction.Left; else if (InputSet.getInstance().getLeftDirectionalY() > 0) d = Direction.Up; else if (InputSet.getInstance().getLeftDirectionalY() < 0) d = Direction.Down; else dirSelected = false; if (dirSelected) { InputSet.getInstance().setToggle(InputsEnum.LEFT_DIRECTIONAL); GameplayManager.DebugZoneTransition(d); } } return; } Facing facing = Facing.None; if (InputSet.getInstance().getLeftDirectionalX() > 0) { facing = Facing.Right; } else if (InputSet.getInstance().getLeftDirectionalX() < 0) { facing = Facing.Left; } Facing facingPressed = facing; Aiming aiming = Aiming.None; bool downPressed = false; bool upPressed = false; if (InputSet.getInstance().getLeftDirectionalY() > 0) { aiming = Aiming.Up; upPressed = true; } else if (InputSet.getInstance().getLeftDirectionalY() < 0) { aiming = Aiming.Down; downPressed = true; } if (InputSet.getInstance().getButton(InputsEnum.LEFT_TRIGGER) && InputSet.getInstance().getButton(InputsEnum.RIGHT_TRIGGER)) { aiming = Aiming.None; } else if (InputSet.getInstance().getButton(InputsEnum.LEFT_TRIGGER)) { aiming = Aiming.Down; } else if (InputSet.getInstance().getButton(InputsEnum.RIGHT_TRIGGER)) { aiming = Aiming.Up; } #endregion #region Determine States & Animation State nextState = m_previousState; Height nextHeight = m_previousHeight; switch (m_previousState) { case State.Idle: if (m_attemptedVelocity.Y < 0 && aiming != Aiming.None) { nextState = State.Airborne; } else if (m_attemptedVelocity.Y < 0) { nextState = State.Takeoff; } else if (IsAirborne) { nextState = State.Airborne; } else if (facing != Facing.None && facing != m_previousFacing) { nextState = State.Turning; } else if (facing != Facing.None && facing == m_previousFacing && nextHeight != Height.Ball) { nextState = State.Moving; nextHeight = Height.Stand; } else if (facing != Facing.None && facing == m_previousFacing && nextHeight == Height.Ball) { nextState = State.Moving; nextHeight = Height.Ball; } else if (m_previousHeight == Height.Stand && downPressed) { nextState = State.Idle; nextHeight = Height.Crouch; InputSet.getInstance().setToggle(InputsEnum.LEFT_DIRECTIONAL); } else if (m_previousHeight == Height.Crouch && upPressed) { nextState = State.Idle; nextHeight = Height.Stand; } else if (m_previousHeight == Height.Crouch && downPressed && Inventory.HasItem(Item.MorphingBall)) { nextState = State.Idle; nextHeight = Height.Ball; } else if (m_previousHeight == Height.Ball && upPressed) { nextState = State.Idle; nextHeight = Height.Crouch; InputSet.getInstance().setToggle(InputsEnum.LEFT_DIRECTIONAL); } else { nextState = State.Idle; } break; case State.Moving: if (m_attemptedVelocity.Y < 0 && aiming == Aiming.None) { nextState = State.Spin; } else if (m_attemptedVelocity.Y < 0) { nextState = State.Takeoff; } else if (IsAirborne) // fell { nextState = State.Airborne; } else if (facing != Facing.None && facing != m_previousFacing) { nextState = State.Turning; } else if (facing != m_previousFacing) { nextState = State.Idle; } else { nextState = State.Moving; } break; case State.Turning: nextState = State.Idle; break; case State.Spin: if (aiming != Aiming.None) { m_previousState = State.Airborne; // yes, it's a hack } // yes, this is indeed a goto - it's the C# way of supporting fall through. // because it doesn't support real fall through. // ...even though "break" is required at the end of each case. goto case State.Airborne; case State.Airborne: if (!InputSet.getInstance().getButton(InputsEnum.BUTTON_1)) { m_attemptedVelocity.Y = Math.Max(0, m_attemptedVelocity.Y); } if (!IsAirborne && aiming == Aiming.None) { nextState = State.Landing; } else if (!IsAirborne) { nextState = State.Idle; } else { nextState = m_previousState; // see Spin hack } break; case State.Takeoff: nextState = State.Airborne; break; case State.Landing: if (m_previousFacing == facing || facing == Facing.None) { nextState = State.Idle; if (nextHeight != Height.Ball) nextHeight = Height.Stand; } else { nextState = State.Turning; } break; } if (facing == Facing.None && nextState != State.Turning) { facing = m_previousFacing; } bool addHold = facingPressed == Facing.None && ((nextState == State.Idle && upPressed) || (nextState == State.Airborne && (upPressed || downPressed))); string animName = String.Format("{0}{1}{2}{3}{4}", (nextHeight != Height.Ball) ? nextState.ToString() : "", (nextHeight != Height.Ball) ? facing.ToString() : "", (nextState != State.Takeoff && nextState != State.Landing && nextState != State.Spin && nextHeight != Height.Ball) ? aiming.ToString() : "", addHold ? "Hold" : "", (nextState == State.Idle || nextState == State.Turning || nextHeight == Height.Ball) ? nextHeight.ToString() : "" ); try { AnimationController.requestAnimation(animName, AnimationController.AnimationCommand.Play); //System.Console.WriteLine(animName); } catch { System.Console.WriteLine(String.Format("Animation '{0}' not found", animName)); } #endregion #region Handle Movement if (nextState == State.Moving) { if (facing == Facing.Left) { m_attemptedVelocity.X -= m_speedMax; } else if (facing == Facing.Right) { m_attemptedVelocity.X += m_speedMax; } } if ((nextState == State.Airborne || nextState == State.Spin) && facingPressed != Facing.None) { if (facing == Facing.Left) { m_attemptedVelocity.X -= m_speedMax * 2 / 3; } else if (facing == Facing.Right) { m_attemptedVelocity.X += m_speedMax * 2 / 3; } } #endregion #region Handle Shooting //Fire a weapon if (InputSet.getInstance().getButton(InputsEnum.BUTTON_3) && nextState != State.Spin && nextHeight != Height.Ball) { model.setStat("shots", model.getStat("shots") + 1); InputSet.getInstance().setToggle(InputsEnum.BUTTON_3); if (this.SelectedWeapon == ProjectileType.Bullet) { fire(animName, facing, aiming, ProjectileType.Bullet); } else if (this.SelectedWeapon == ProjectileType.Missile) { fire(animName, facing, aiming, ProjectileType.Missile); } } if (InputSet.getInstance().getButton(InputsEnum.BUTTON_2)) { InputSet.getInstance().setToggle(InputsEnum.BUTTON_2); if (this.SelectedWeapon == ProjectileType.Bullet) { this.SelectedWeapon = ProjectileType.Missile; } else if (this.SelectedWeapon == ProjectileType.Missile) { this.SelectedWeapon = ProjectileType.Bullet; } } #endregion m_previousFacing = facing; m_previousAiming = aiming; m_previousHeight = nextHeight; m_previousState = nextState; DoubleRect oldBounds = this.getCollider().Bounds; double heightDiff = oldBounds.Height - Math.Min(AnimationController.CurrentSprite.box.Height * AnimationController.Scale - 5, m_baseCollisionBoxHeight); DoubleRect newBounds = oldBounds; newBounds.Height -= heightDiff; newBounds.Y += heightDiff; if (this.getCollider().queryDetector(oldBounds).Count < this.getCollider().queryDetector(newBounds).Count) { newBounds = oldBounds; } this.getCollider().Bounds = newBounds; }
public override int GetHashCode() { return(Width.GetHashCode() ^ Height.GetHashCode() ^ Format.GetHashCode()); }
private void FormCaptureBox_Resize(object sender, EventArgs e) { updateRegion(); lblSize.Text = Width.ToString() + ":" + Height.ToString(); }
public static int[] GetArrayItem(Height height) { return Array[(byte)height - 1]; }
private void Initialize(Height height, Shape shape, Top top, Color color) { Height = height; Shape = shape; Top = top; Color = color; }