public static void ProcessUseSkill(this World world, ClientConnection client, UseSkill message) { var source = client.Avatar as CombatantModel; if (source == null) { client.LogMessage("Requested a skill without an avatar."); return; } Schema.EnumSkillRow esr = Global.Schema.EnumSkill.FindByEnumSkillID((int)message.Skill); if (esr == null) { client.LogMessage("Requested an invalid skill " + message.Skill); return; } EntityModel target; switch ((EnumTargetType)esr.EnumTargetTypeID) { case EnumTargetType.TargetSelf: target = source; break; case EnumTargetType.TargetMobile: if (message.TargetPhysicalObjectIDs.Length == 0) { world.LogMessage(source, "No target specified, this skill may only be used on Mobiles."); return; } target = world.History.Head.Entities.ValueOrDefault(message.TargetPhysicalObjectIDs[0]); if (target == null) { world.LogMessage(source, "Target " + message.TargetPhysicalObjectIDs[0] + " not found."); return; } break; default: world.LogMessage(source, "That skill has an unsupported target type " + esr.EnumTargetTypeID); Log.Error("Unhandled target type " + esr.EnumTargetTypeID + " for skill " + esr.EnumSkillID + " " + esr.EnumSkillName); return; } if (source.ActivatingSkill != EnumSkill.None) // queue the request for later. world.Apply(new EntityUpdateEvent( source.EnqueueSkill(message.Skill, target), "Enqueuing Skill " + message.Skill)); else if (esr.LeadTime <= 0) // process it now world.UseSkillNow(source, esr, target); else // process it later, after lead-time has elapsed world.Apply(new EntityUpdateEvent( source.StartSkill(message.Skill, target, Global.Now, TimeSpan.FromSeconds(esr.LeadTime)), "Activating Skill " + message.Skill)); }
public static DateTime Equal(this IShould<DateTime> should, DateTime expected, TimeSpan tolerance) { return should.Apply( (t, a) => a.AreEqual(expected, t, tolerance), (t, a) => a.AreNotEqual(expected, t, tolerance) ); }
//========================================================================= // Methods created by petrucio -> http://answers.unity3d.com/questions/238922/png-transparency-has-white-borderhalo.html // // Copy the values of adjacent pixels to transparent pixels color info, to // remove the white border artifact when importing transparent .PNGs. public static void FixTransparency(this Texture2D texture) { Color32[] pixels = texture.GetPixels32(); int w = texture.width; int h = texture.height; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int idx = y * w + x; Color32 pixel = pixels[idx]; if (pixel.a == 0) { bool done = false; if (!done && x > 0) done = TryAdjacent(ref pixel, pixels[idx - 1]); // Left pixel if (!done && x < w - 1) done = TryAdjacent(ref pixel, pixels[idx + 1]); // Right pixel if (!done && y > 0) done = TryAdjacent(ref pixel, pixels[idx - w]); // Top pixel if (!done && y < h - 1) done = TryAdjacent(ref pixel, pixels[idx + w]); // Bottom pixel pixels[idx] = pixel; } } } texture.SetPixels32(pixels); texture.Apply(); }
public static Rect[] PackTextures(this Texture2D atlas,Texture2D[] textures,int padding, bool uniformDimension){ List<Rect> rects = new List<Rect> (); if (uniformDimension) { Vector2 maxSize = GetMaxSize (textures); float max=maxSize.x>maxSize.y?maxSize.x:maxSize.y; int x = 0; int y = 0; int p = (int)Mathf.Ceil (Mathf.Log (textures.Length) / Mathf.Log (2)); Vector2 offset=Vector2.zero; for (int t=0; t< textures.Length; t++) { Color[] pixels = textures [t].GetPixels (); if (x >= p) { y++; x = 0; } offset= new Vector2((max-textures[t].width)*0.5f,(max-textures[t].height)*0.5f); rects.Add (new Rect (x * max + x * padding, y * max + y * padding, max, max)); atlas.SetPixels ((int)(x * max + padding+offset.x), (int)(y * max + padding+offset.y), (int)textures [t].width, (int)textures [t].height, pixels); x++; } atlas.Apply (); } else { Rect[] r=atlas.PackTextures(textures,padding); for(int i=0;i<r.Length;i++){ rects.Add(new Rect(r[i].x*atlas.width,r[i].y*atlas.height,textures[i].width,textures[i].height)); } } return rects.ToArray (); }
public static Texture2D MakeOutline(this Texture2D texture, int width) { Color[] c = texture.GetPixels(); Color[] nc = new Color[c.Length]; for (int y = 0; y < texture.height; y++) for (int x = 0; x < texture.width; x++) { Color cc = c[x + y * texture.width]; if (cc.a < 0.1) { float a = 0; for (int cy = Mathf.Max(y - width, 0); cy <= Mathf.Min(y + width, texture.height - 1); cy++) for (int cx = Mathf.Max(x - width, 0); cx <= Mathf.Min(x + width, texture.width - 1); cx++) a = Mathf.Max(c[cx + cy * texture.width].a, a); if (a > 0.1) { nc[x + y * texture.width] = Color.black.Alpha(a); goto skip; } } if (cc.a > 0) { cc = cc.Alpha(1.0f); } nc[x + y * texture.width] = cc; skip:; } texture.SetPixels(nc, 0); texture.Apply(); return texture; }
public static DateTime Equal(this IShould<DateTime> should, DateTime expected, DatePrecision precision) { return should.Apply( (t, a) => a.AreEqual(expected, t, precision), (t, a) => a.AreNotEqual(expected, t, precision) ); }
public static void OwnershipToTable(this IDDLRunner runner, StoreOptions options, TableName table) { if (options.OwnerName.IsNotEmpty()) { runner.Apply(table, $"ALTER TABLE {table.QualifiedName} OWNER TO {options.OwnerName};"); } }
public static double Equal(this IShould<double> should, double expected, double tolerance) { return should.Apply( (t, a) => a.AreEqual(expected, t, tolerance), (t, a) => a.AreNotEqual(expected, t, tolerance) ); }
/// <summary> /// Floods this Texture2D with given color (EXPENSIVE OPERATION!) /// </summary> /// <param name="texture"></param> /// <param name="color"></param> public static void Fill(this Texture2D texture, Color color) { int width = texture.width; int height = texture.height; Color[] colors = Enumerable.Repeat(color, width * height).ToArray(); texture.SetPixels(0, 0, width, height, colors); texture.Apply(); }
public static IDictionary<string, string> Values(this IVaryBy varyBy) { var dictionary = new Dictionary<string, string>(); varyBy.Apply(dictionary); return dictionary; }
public static void Fill(this Texture2D tex, Color aColor) { MakeFormatWritable(tex); Color[] pixels = tex.GetPixels(0); for (int i=0; i<pixels.Length; i++) { pixels[i] = aColor; } tex.SetPixels(pixels, 0); tex.Apply(tex.mipmapCount > 1, false); }
//------------------------------------------------------------------------------------------------------------ public static void ConvertLightmapToMobile(this Texture2D lTexture) { Color[] lColorData = lTexture.GetPixels(); for (int lCount = 0; lCount < lColorData.Length; ++lCount) { lColorData[lCount] = (lColorData[lCount] * (8f * lColorData[lCount].a)) * 0.5f; } lTexture.SetPixels(lColorData); lTexture.Apply(); lColorData = null; }
public static string Contain(this IShould<string> should, string expectedSubstring) { return should.Apply( (t, a) => a.IsSubstringOf(t, expectedSubstring), (t, a) => { if (t.Contains(expectedSubstring)) { a.Fail("Expected string '{0}' to not contain '{1}', but it did.", t, expectedSubstring); } }); }
/// <summary> /// Set to 0 all alpha values below a threshold. /// Warning: this operation applies the modifications directly to the texture/asset, /// so don't use it on your original art. /// If in doubt, /// use <see cref="Texture2DExtensions.ClearedAlpha"/> to create a new alpha cleared texture. /// </summary> /// <param name="tex"></param> /// <param name="threshold">Alpha value below which alpha is set to 0.</param> public static void ClearAlpha(this Texture2D tex, float threshold = .05f) { var pixels = tex.GetPixels(); for (int i = 0; i < pixels.Length; ++i) { if (pixels[i].a < threshold) { pixels[i].a = 0; } } tex.SetPixels( pixels ); tex.Apply(); }
public static void CopyFrom(this Texture2D tex, Texture2D fromTex, int toX, int toY, int fromX, int fromY, int width, int height) { MakeFormatWritable(tex); int fullWidth = tex.width; Color[] pixels = tex.GetPixels(0); Color[] fromPixels = fromTex.GetPixels(fromX, fromY, width, height, 0); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixels[((y + toY) * fullWidth) + x + toX] = fromPixels[(y * width) + x]; } } tex.SetPixels(pixels,0); tex.Apply((tex.mipmapCount > 1), false); }
public static IReadOnlyResult ApplySql(this IConnection conn, Command sql, params object[] parameters) { if (parameters != null) { for (var i = 0; i < parameters.Length; i++) { sql.WithParam(i.ToString(), parameters[i]); } } if (!sql.Aml.TrimStart().StartsWith("<")) { sql.Aml = "<sql>" + sql.Aml + "</sql>"; } return conn.Apply(sql.WithAction(CommandAction.ApplySQL)); }
public static string EndWith(this IShould<string> should, string expectedSubstring) { return should.Apply( (t, a) => { if (!t.EndsWith(expectedSubstring)) { a.Fail("Expected string '{0}' to end with '{1}', but it did not.", t, expectedSubstring); } }, (t, a) => { if (t.EndsWith(expectedSubstring)) { a.Fail("Expected string '{0}' to not end with '{1}', but it did.", t, expectedSubstring); } }); }
internal static BitMatrix GetLowestPenaltyMatrix(this TriStateMatrix matrix, ErrorCorrectionLevel errorlevel) { PatternFactory patternFactory = new PatternFactory(); int score = int.MaxValue; int tempScore; TriStateMatrix result = new TriStateMatrix(matrix.Width); TriStateMatrix triMatrix; foreach(Pattern pattern in patternFactory.AllPatterns()) { triMatrix = matrix.Apply(pattern, errorlevel); tempScore = triMatrix.PenaltyScore(); if(tempScore < score) { score = tempScore; result = triMatrix; } } return result; }
public static void perlinNoise( this Texture2D texture,int seed) { Color [] pix=new Color[texture.width*texture.height]; int y = 0; int xOrg=0; int yOrg=0; int scale=1; while (y < texture.height) { int x = 0; while (x < texture.width) { float xCoord = seed + (float)x / texture.width * scale; float yCoord = seed + (float)y / texture.height * scale; float sample =Mathf.Lerp( 0.46f,0.54f, Mathf.PerlinNoise(xCoord, yCoord)); pix[y * texture.width + x] = new Color(sample, sample, sample); x++; } y++; } texture.SetPixels(pix); texture.Apply(); }
public static void UpdateWithMat(this Texture2D texture, Mat image) { int channels = image.NumberOfChannels; byte[] pixels = image.GetData(new int[]{}); int pixelCount = pixels.Length / channels; Color[] textureColors = new Color[pixelCount]; Parallel.For(0, pixelCount, i => { int pixelIndex = i * channels; Color col; byte bb = pixels[pixelIndex]; float b = (float)bb / 255.0f; if(channels == 1) { col = new Color(b,b,b); } else if(channels == 3) { byte gb = pixels[pixelIndex+1]; float g = (float)gb / 255.0f; byte rb = pixels[pixelIndex+2]; float r = (float)rb / 255.0f; col = new Color(r,g,b); } else col = Color.magenta; textureColors[i] = col; }); texture.SetPixels(textureColors); texture.Apply(); }
public static void UseSkillNow(this World world, CombatantModel source, Schema.EnumSkillRow skill, EntityModel target) { if (source.MobileState == EnumMobileState.Dead || source.MobileState == EnumMobileState.Incapacitated) { world.LogMessage(source, "Unable to use " + skill.EnumSkillName + " while " + source.MobileState); return; } /* TODO: skill specific states if ( skill.EnumMobileState > caster.MobileState ) { caster.SendLog( "Not while " + caster.MobileState.Name ); } */ if ((source.Position - target.Position).Length > skill.Range) { world.LogMessage(source, target.Name + " is out of range"); return; } if (skill.EnergyCost > source.Energy) { world.LogMessage(source, "Not enough energy to use " + skill.EnumSkillName + ", requires " + skill.EnergyCost); return; } // deduct energy regardless // TODO: can remove the explicit cast here by using generics source = (CombatantModel)source.WithEnergyChange(-skill.EnergyCost); bool succeeds = source.Succeeds(skill); bool hits = source.Hits(target, skill); bool avoids = target.Avoids(source, skill); // successful casting affects affinity with the elements if (succeeds && hits && !avoids) { // TODO: can remove the explicit cast here by using generics source = (CombatantModel)source.WithAffinityChange( skill.AirAffinity / 1000f, skill.EarthAffinity / 1000f, skill.FireAffinity / 1000f, skill.LifeAffinity / 1000f, skill.WaterAffinity / 1000f); // TODO: just get the damage number instead?? switch ((EnumActivationType)skill.EnumActivationTypeID) { case EnumActivationType.AttackSpell: target = target.MagicallyDamagedBy(source, skill); break; case EnumActivationType.Enchantment: target = target.EnchantedBy(source, skill); break; case EnumActivationType.Glamour: source.Activates(skill, target); break; case EnumActivationType.HealingSpell: target = target.HealedBy(source, skill); break; case EnumActivationType.Skill: target = target.DamagedBy(source, skill); target = target.AffectedBy(source, skill); source.Activates(skill, target); break; case EnumActivationType.Sorcery: break; default: world.LogMessage(source, "That skill does not work yet, contact admin."); Log.Error("Unhandled activation type " + (EnumActivationType)skill.EnumActivationTypeID + " for skill " + skill.EnumSkillName); break; } } source = source.FinishSkill(); string description = avoids ? "Avoided" : !hits ? "Missed" : !succeeds ? "Failed" : "Success"; world.Apply(new SkillEvent(source, (EnumSkill)skill.EnumSkillID, target, succeeds, hits, avoids, description)); }
/// <summary> /// Draws a <see cref="GenericImage{T}"/> on to a <see cref="Texture2D"/> texture. /// </summary> /// <param name="texture">A reference to a <see cref="Texture2D"/> type.</param> /// <param name="sourceImage">A reference to the <see cref="GenericImage{T}"/> that will be drawn.</param> /// <param name="x">The x position where the <see cref="sourceImage"/> will be drawn.</param> /// <param name="y">The y position where the <see cref="sourceImage"/> will be drawn.</param> /// <param name="sourceX">The source x position within <see cref="sourceImage"/>.</param> /// <param name="sourceY">The source y position within <see cref="sourceImage"/>.</param> /// <param name="sourceWidth">The source width within the <see cref="sourceImage"/>.</param> /// <param name="sourceHeight">The source height within the <see cref="sourceImage"/>.</param> /// <param name="flipHorizontally">If true will flip the <see cref="sourceImage"/> horizontally before drawing.</param> /// <param name="flipVertically">If true will flip the <see cref="sourceImage"/> vertically before drawing.</param> public static void Draw(this Texture2D texture, GenericImage<Color> sourceImage, int x, int y, int sourceX, int sourceY, int sourceWidth, int sourceHeight, bool flipHorizontally, bool flipVertically) { var textureRectangle = new Rect(0, 0, texture.width, texture.height); var sourceRectangle = new Rect(x, y, sourceWidth, sourceHeight); var intersect = textureRectangle.Intersect(sourceRectangle); if (!intersect.Intersects(new Rect(0, 0, sourceImage.Width, sourceImage.Height))) { return; } var tempImage = new GenericImage<Color>((int)intersect.width, (int)intersect.height); tempImage.Draw(sourceImage, 0, 0, sourceX, sourceY, tempImage.Width, tempImage.Height, (source, blendWith) => blendWith); if (flipHorizontally) { tempImage.FlipHorizontally(); } if (flipVertically) { tempImage.FlipVertically(); } var colors = tempImage.ToUnityColorArray(); texture.SetPixels(x, y, (int)intersect.width, (int)intersect.height, colors); texture.Apply(); }
public static IJsValue Apply(this IJsFunction function, IJsValue @this, params IJsValue[] arguments) { return function.Apply(@this, (IList<IJsValue>)arguments); }
public static IJsValue Apply(this IJsFunction function, IJsValue @this, IEnumerable<IJsValue> arguments) { return function.Apply(@this, arguments.ToList()); }
public static void ProcessCancelSkill(this World world, ClientConnection client, CancelSkill message) { var avatar = client.Avatar as CombatantModel; if (avatar == null) { client.LogMessage("Canceled a skill invocation, but don't have an avatar."); return; } // If already performing invocation, just cancel it bool found = false; if (avatar.ActivatingSkill != EnumSkill.None) // TODO: //&& avatar.ActivatingSkill.InvokationId == message.InvokationId) { world.Apply(new EntityUpdateEvent(avatar.StartSkill(EnumSkill.None, null, Global.Now, TimeSpan.FromSeconds(0)), "Started using skill")); found = true; } else { // TODO: search for it in queued skill invocations // just generate a new queue with the invocation missing /* var newQueue = new Queue<UseSkill>(); foreach (UseSkill m in avatar.SkillQueue) { if (m.InvokationId == message.InvokationId) { // don't add it found = true; } else newQueue.Enqueue(m); } avatar.SkillQueue = newQueue; */ avatar.EmptyQueue(); } if (found) client.LogMessage("Successfully canceled invocation " + message.InvokationId); else client.LogMessage("Failed to cancel invocation " + message.InvokationId); }
static void ApplyPMA (this Texture2D texture, bool applyImmediately = true) { var pixels = texture.GetPixels(); for (int i = 0, n = pixels.Length; i < n; i++) { Color p = pixels[i]; float a = p.a; p.r = p.r * a; p.g = p.g * a; p.b = p.b * a; pixels[i] = p; } texture.SetPixels(pixels); if (applyImmediately) texture.Apply(); }
public static void RemoveColumn(this IDDLRunner runner, object subject, TableName table, string columnName) { var sql = $"alter table if exists {table.QualifiedName} drop column if exists {columnName};"; runner.Apply(subject, sql); }
public static RawExpression Apply(this RawExpression e, string name, double value) { return e.Apply(new Dictionary<string, double> { { name, value } }); }
public static void Drop(this IDDLRunner runner, object subject, TableName table) { var sql = $"drop table if exists {table.QualifiedName} cascade;"; runner.Apply(subject, sql); }
/// <summary> /// /// </summary> /// <param name="lTexture2D"></param> /// <param name="lData"></param> /// <param name="lError"></param> public static unsafe void LoadWebP(this Texture2D lTexture2D, byte[] lData, out Error lError, ScalingFunction scalingFunction = null) { lError = 0; bool lMipmaps = lTexture2D.mipmapCount != 1; int lWidth = 0, lHeight = 0; GetWebPDimensions(lData, out lWidth, out lHeight); byte[] lRawData = LoadRGBAFromWebP(lData, ref lWidth, ref lHeight, lMipmaps, out lError, scalingFunction); if (lError == Error.Success) { lTexture2D.LoadRawTextureData(lRawData); lTexture2D.Apply(lMipmaps, true); } }