# System.Math.Max(float, float)

Here are the examples of the csharp api System.Math.Max(float, float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

## 1201 Examples

19 View Source File : InscribedRectangle.cs
Project Creator : abist-co-ltd

``````private bool TryFixMaximumRectangle(
Edge[] geometryEdges,
Vector2 centerPoint,
float minArea,
out float width,
out float height)
{
width = 0.0f;
height = 0.0f;

Vector2 topCollisionPoint;
Vector2 bottomCollisionPoint;
Vector2 leftCollisionPoint;
Vector2 rightCollisionPoint;

// Find the collision points with the geometry
out topCollisionPoint, out bottomCollisionPoint, out leftCollisionPoint, out rightCollisionPoint))
{
return false;
}

// Start by calculating max width and height by ray-casting a cross from the point at the given angle
// and taking the shortest leg of each ray. Width is the longest.
float verticalMinDistanceToEdge = Mathf.Min(
Vector2.Distance(centerPoint, topCollisionPoint),
Vector2.Distance(centerPoint, bottomCollisionPoint));

float horizontalMinDistanceToEdge = Mathf.Min(
Vector2.Distance(centerPoint, leftCollisionPoint),
Vector2.Distance(centerPoint, rightCollisionPoint));

// Width is the largest of the possible dimensions
float maxWidth = Math.Max(verticalMinDistanceToEdge, horizontalMinDistanceToEdge) * 2.0f;
float maxHeight = Math.Min(verticalMinDistanceToEdge, horizontalMinDistanceToEdge) * 2.0f;

float aspectRatio = 0.0f;

// For each aspect ratio we do a binary search to find the maximum rectangle that fits,
// though once we start increasing our area by minimumHeightGain we call it good enough.
for (int i = 0; i < aspectRatios.Length; i++)
{
// The height is limited by the width. If a height would make our width exceed maxWidth, it can't be used
float searchHeightUpperBound = Mathf.Max(maxHeight, maxWidth / aspectRatios[i]);

// Set to the min height that will out perform our previous area at the given aspect ratio. This is 0 the first time.
// Derived from biggestAreaSoFar=height*(height*aspectRatio)
float searchHeightLowerBound = Mathf.Sqrt(Mathf.Max((width * height), minArea) / aspectRatios[i]);

// If the lowest value needed to outperform the previous best is greater than our max,
// this aspect ratio can't outperform what we've already calculated.
if ((searchHeightLowerBound > searchHeightUpperBound) ||
(searchHeightLowerBound * aspectRatios[i] > maxWidth))
{
continue;
}

float currentTestingHeight = Mathf.Max(searchHeightLowerBound, maxHeight * 0.5f);

// Perform the binary search until continuing to search will not give us a significant win.
do
{
if (CheckRectangleFit(geometryEdges,
centerPoint,
aspectRatios[i] * currentTestingHeight,
currentTestingHeight))
{
// Binary search up-ward
// If the rectangle will fit, increase the lower bounds of our binary search
searchHeightLowerBound = currentTestingHeight;

width = currentTestingHeight * aspectRatios[i];
height = currentTestingHeight;
aspectRatio = aspectRatios[i];
currentTestingHeight = (searchHeightUpperBound + currentTestingHeight) * 0.5f;
}
else
{
// If the rectangle won't fit, update our upper bound and lower our binary search
searchHeightUpperBound = currentTestingHeight;
currentTestingHeight = (currentTestingHeight + searchHeightLowerBound) * 0.5f;
}
}
while ((searchHeightUpperBound - searchHeightLowerBound) > minimumHeightGain);
}

return (aspectRatio > 0.0f);
}``````

19 View Source File : BaseNearInteractionTouchable.cs
Project Creator : abist-co-ltd

``````protected virtual void OnValidate()
{
debounceThreshold = Math.Max(debounceThreshold, 0);
}``````

19 View Source File : Rand.cs
Project Creator : ABTSoftware

``````public float NextWalk()
{
// Random walk
_current += (float)((InstanceRandom.NextDouble() - 0.5) * 0.002);

// Clamp to 0..1
_current = Math.Max(Math.Min(_current, 1.0f), 0.0f);
return _current;
}``````

19 View Source File : ChessLogic.cs
Project Creator : ACEmulator

``````public float MinimaxAlphaBeta(uint depth, float alpha, float beta, bool isMaximizingPower, ref uint counter)
{
counter++;
if (depth <= 0)
return -EvaluateBoard();

var storage = new List<ChessMove>();
GenerateMoves(Turn, storage);

if (isMaximizingPower)
{
var bestBoardScore = -9999.0f;
foreach (var move in storage)
{
FinalizeMove(move);
bestBoardScore = Math.Max(bestBoardScore, MinimaxAlphaBeta(depth - 1, alpha, beta, false, ref counter));
UndoMove(1);

alpha = Math.Max(alpha, bestBoardScore);
if (beta <= alpha)
return bestBoardScore;
}
return bestBoardScore;
}
else
{
var bestBoardScore = 9999.0f;
foreach (var move in storage)
{
FinalizeMove(move);
bestBoardScore = Math.Max(bestBoardScore, MinimaxAlphaBeta(depth - 1, alpha, beta, true, ref counter));
UndoMove(1);

beta = Math.Max(beta, bestBoardScore);
if (beta <= alpha)
return bestBoardScore;
}
return bestBoardScore;
}
}``````

19 View Source File : Cloak.cs
Project Creator : ACEmulator

``````public static float GetReducedAmount(WorldObject source, float damage)
{
var damageReductionAmount = GetDamageReductionAmount(source);

return Math.Max(0, damage - damageReductionAmount);
}``````

19 View Source File : Monster_Navigation.cs
Project Creator : ACEmulator

``````public bool IsFacing(WorldObject target)
{
if (target?.Location == null) return false;

var angle = GetAngle(target);
var dist = Math.Max(0, GetDistanceToTarget());

// rotation accuracy?
var threshold = 5.0f;

var minDist = 10.0f;

if (dist < minDist)
threshold += (minDist - dist) * 1.5f;

if (DebugMove)
Console.WriteLine(\$"{Name}.IsFacing({target.Name}): Angle={angle}, Dist={dist}, Threshold={threshold}, {angle < threshold}");

return angle < threshold;
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetWeaponCriticalChance(WorldObject weapon, Creature wielder, CreatureSkill skill, Creature target)
{
var critRate = (float)(weapon?.CriticalFrequency ?? defaultPhysicalCritFrequency);

if (weapon != null && weapon.HasImbuedEffect(ImbuedEffectType.CriticalStrike))
{
var criticalStrikeBonus = GetCriticalStrikeMod(skill);

critRate = Math.Max(critRate, criticalStrikeBonus);
}

if (wielder != null)
critRate += wielder.GetCritRating() * 0.01f;

// mitigation
var critResistRatingMod = Creature.GetNegativeRatingMod(target.GetCritResistRating());
critRate *= critResistRatingMod;

return critRate;
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetWeaponMagicCritFrequency(WorldObject weapon, Creature wielder, CreatureSkill skill, Creature target)
{
// TODO : merge with above function

if (weapon == null)
return defaultMagicCritFrequency;

var critRate = (float)(weapon.GetProperty(PropertyFloat.CriticalFrequency) ?? defaultMagicCritFrequency);

if (weapon.HasImbuedEffect(ImbuedEffectType.CriticalStrike))
{
var isPvP = wielder is Player && target is Player;

var criticalStrikeMod = GetCriticalStrikeMod(skill, isPvP);

critRate = Math.Max(critRate, criticalStrikeMod);
}

critRate += wielder.GetCritRating() * 0.01f;

// mitigation
var critResistRatingMod = Creature.GetNegativeRatingMod(target.GetCritResistRating());
critRate *= critResistRatingMod;

return critRate;
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetWeaponCritDamageMod(WorldObject weapon, Creature wielder, CreatureSkill skill, Creature target)
{
var critDamageMod = (float)(weapon?.GetProperty(PropertyFloat.CriticalMultiplier) ?? defaultCritDamageMultiplier);

if (weapon != null && weapon.HasImbuedEffect(ImbuedEffectType.CripplingBlow))
{
var cripplingBlowMod = GetCripplingBlowMod(skill);

critDamageMod = Math.Max(critDamageMod, cripplingBlowMod);
}
return critDamageMod;
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetWeaponResistanceModifier(WorldObject weapon, Creature wielder, CreatureSkill skill, DamageType damageType)
{
float resistMod = defaultModifier;

if (wielder == null || weapon == null)
return defaultModifier;

// handle quest weapon fixed resistance cleaving
if (weapon.ResistanceModifierType != null && weapon.ResistanceModifierType == damageType)
resistMod = 1.0f + (float)(weapon.ResistanceModifier ?? defaultModifier);       // 1.0 in the data, equivalent to a level 5 vuln

// handle elemental resistance rending
var rendDamageType = GetRendDamageType(damageType);

if (rendDamageType == ImbuedEffectType.Undef)
log.Debug(\$"{wielder.Name}.GetRendDamageType({damageType}) unexpected damage type for {weapon.Name} ({weapon.Guid})");

if (rendDamageType != ImbuedEffectType.Undef && weapon.HasImbuedEffect(rendDamageType) && skill != null)
{
var rendingMod = GetRendingMod(skill);

resistMod = Math.Max(resistMod, rendingMod);
}

return resistMod;
}``````

19 View Source File : Player_Move.cs
Project Creator : ACEmulator

``````public void CreateMoveToChain(WorldObject target, Action<bool> callback, float? useRadius = null, bool rotate = true)
{
if (FastTick)
{
return;
}

var thisMoveToChainNumber = GetNextMoveToChainNumber();

if (target.Location == null)
{
StopExistingMoveToChains();
log.Error(\$"{Name}.CreateMoveToChain({target.Name}): target.Location is null");

callback(false);
return;
}

// fix bug in magic combat mode after walking to target,
// crouch animation steps out of range

if (CombatMode == CombatMode.Magic)

{
if (rotate)
{
// send TurnTo motion
var rotateTime = Rotate(target);
var actionChain = new ActionChain();
{
lastCompletedMove = thisMoveToChainNumber;
callback(true);
});
actionChain.EnqueueChain();
}
else
{
lastCompletedMove = thisMoveToChainNumber;
callback(true);
}
return;
}

if (target.WeenieType == WeenieType.Portal)
MoveToPosition(target.Location);
else

moveToChainStartTime = DateTime.UtcNow;

}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetWeaponMeleeDefenseModifier(Creature wielder)
{
// creatures only receive defense bonus in combat mode
if (wielder == null || wielder.CombatMode == CombatMode.NonCombat)
return defaultModifier;

var mainhand = GetWeapon(wielder, true);
var offhand = wielder.GetDualWieldWeapon();

if (offhand == null)
{
return GetWeaponMeleeDefenseModifier(wielder, mainhand);
}
else
{
var mainhand_defenseMod = GetWeaponMeleeDefenseModifier(wielder, mainhand);
var offhand_defenseMod = GetWeaponMeleeDefenseModifier(wielder, offhand);

return Math.Max(mainhand_defenseMod, offhand_defenseMod);
}
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetCriticalStrikeMod(CreatureSkill skill, bool isPvP = false)
{
var baseMod = 0.0f;

var skillType = GetImbuedSkillType(skill);

var baseSkill = GetBaseSkillImbued(skill);

switch (skillType)
{
case ImbuedSkillType.Melee:

baseMod = Math.Max(0, baseSkill - 100) / 600.0f;
break;

case ImbuedSkillType.Missile:
case ImbuedSkillType.Magic:

baseMod = Math.Max(0, baseSkill - 60) / 600.0f;
break;

default:
return 0.0f;
}

// http://acpedia.org/wiki/Announcements_-_2004/07_-_Treaties_in_Stone#Letter_to_the_Players

// For PvE only:

// Critical Strike for War Magic currently scales from 5% critical hit chance to 25% critical hit chance at maximum effectiveness.
// In July, the maximum effectiveness will be increased to 50% chance.

if (skillType == ImbuedSkillType.Magic && isPvP)
baseMod *= 0.5f;

// In the original formula for CS Magic pre-July 2004, (BS - 60) / 1200.0f, the minimum 5% crit rate would have been achieved at BS 120,
// which is exactly equal to the minimum base skill for CS Missile becoming effective.

// CS Magic is slightly different from all the other skill/imbue combinations, in that the MinCriticalStrikeMagicMod
// is different from the defaultMagicCritFrequency (5% vs. 2%)

// If we simply clamp to min. 5% here, then a player will be getting a +3% bonus from from base skill 0-90 in PvE,
// and base skill 0-120 in PvP

// This code is checking if the player has reached the skill threshold for receiving the 5% bonus
// (base skill 90 in PvE, base skill 120 in PvP)

/*var criticalStrikeMod = skillType == ImbuedSkillType.Magic ? defaultMagicCritFrequency : defaultPhysicalCritFrequency;

var minEffective = skillType == ImbuedSkillType.Magic ? MinCriticalStrikeMagicMod : defaultPhysicalCritFrequency;

if (baseMod >= minEffective)
criticalStrikeMod = baseMod;*/

var defaultCritFrequency = skillType == ImbuedSkillType.Magic ? defaultMagicCritFrequency : defaultPhysicalCritFrequency;

var criticalStrikeMod = Math.Max(defaultCritFrequency, baseMod);

//Console.WriteLine(\$"CriticalStrikeMod: {criticalStrikeMod}");

return criticalStrikeMod;
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetCripplingBlowMod(CreatureSkill skill)
{
// increases the critical damage multiplier, additive

// http://acpedia.org/wiki/Announcements_-_2004/07_-_Treaties_in_Stone#Letter_to_the_Players

// PvP only:

// Crippling Blow for War Magic currently scales from adding 50% of the spells damage on critical hits to adding 100% at maximum effectiveness.
// In July, the maximum effectiveness will be increased to adding up to 500% of the spell's damage.

// ( +500% sounds like it would be 6.0 multiplier)

var baseSkill = GetBaseSkillImbued(skill);

var baseMod = 1.0f;

switch(GetImbuedSkillType(skill))
{
case ImbuedSkillType.Melee:
baseMod = Math.Max(0, baseSkill - 40) / 60.0f;
break;

case ImbuedSkillType.Missile:
case ImbuedSkillType.Magic:

baseMod = baseSkill / 60.0f;
break;
}

var cripplingBlowMod = Math.Max(1.0f, baseMod);

//Console.WriteLine(\$"CripplingBlowMod: {cripplingBlowMod}");

return cripplingBlowMod;
}``````

19 View Source File : SkillFormula.cs
Project Creator : ACEmulator

``````public static float GetAttributeMod(int currentSkill, bool isBow = false)
{
var factor = isBow ? BowMod : DefaultMod;

return Math.Max(1.0f + (currentSkill - 55) * factor, 1.0f);
}``````

19 View Source File : WorldObject_Weapon.cs
Project Creator : ACEmulator

``````public static float GetWeaponOffenseModifier(Creature wielder)
{
// creatures only receive offense bonus in combat mode
if (wielder == null || wielder.CombatMode == CombatMode.NonCombat)
return defaultModifier;

var mainhand = GetWeapon(wielder, true);
var offhand = wielder.GetDualWieldWeapon();

if (offhand == null)
{
return GetWeaponOffenseModifier(wielder, mainhand);
}
else
{
var mainhand_attackMod = GetWeaponOffenseModifier(wielder, mainhand);
var offhand_attackMod = GetWeaponOffenseModifier(wielder, offhand);

return Math.Max(mainhand_attackMod, offhand_attackMod);
}
}``````

19 View Source File : MinikinFont.h.cs

``````public void join(MinikinRect r)
{
if (isEmpty())
{
set(r);
}
else if (!r.isEmpty())
{
mLeft = Math.Min(mLeft, r.mLeft);
mTop = Math.Min(mTop, r.mTop);
mRight = Math.Max(mRight, r.mRight);
mBottom = Math.Max(mBottom, r.mBottom);
}
}``````

19 View Source File : BatFamiliar.cs
Project Creator : aedenthorn

``````public override void behaviorAtGameTick(GameTime time)
{
invincibleCountdown = 1000;
if (timeBeforeAIMovementAgain > 0f)
{
timeBeforeAIMovementAgain -= (float)time.ElapsedGameTime.Milliseconds;
}
if (lastHitCounter >= 0)
{
lastHitCounter.Value -= time.ElapsedGameTime.Milliseconds;
}
if (lastScreechCounter >= 0)
{
lastScreechCounter.Value -= time.ElapsedGameTime.Milliseconds;
}
if (lastScreechCounter < 0 && GetBoundingBox().Intersects(GetOwner().GetBoundingBox()))
{
if(ModEntry.Config.BatSoundEffects)
currentLocation.playSound("batScreech", NetAudio.SoundContext.Default);
lastScreechCounter.Value = 10000;
}

chargingMonster = false;
if(lastHitCounter < 0 && !(currentLocation is SlimeHutch))
{
foreach (NPC npc in currentLocation.characters)
{
if (npc is Familiar)
continue;

if (npc is Monster && FamiliarsUtils.monstersColliding(this, (Monster)npc))
{
if (BaseDamage() >= 0)
{
int damageAmount = Game1.random.Next(BaseDamage(), BaseDamage() * 2 + 1);
damageAmount = (npc as Monster).takeDamage(damageAmount, 0, 0, false, 0, GetOwner());
if((npc as Monster).Health <= 0)
{
}
else
{
}
}
lastHitCounter.Value = AttackInterval();
chargingMonster = false;
break;
}
else if (npc is Monster && FamiliarsUtils.withinMonsterThreshold(this, (Monster)npc, 2))
{
chargingMonster = true;
if (currentTarget == null || Vector2.Distance(npc.position, position) < Vector2.Distance(currentTarget.position, position))
{
currentTarget = (Monster)npc;
}
}
}
}

if (wareplacedCounter >= 0)
{
wareplacedCounter.Value -= time.ElapsedGameTime.Milliseconds;
}

if (chargingMonster || followingOwner)
{
seenPlayer.Value = true;

Vector2 center = Position + new Vector2(8, 8);
Vector2 playerCenter = GetOwner().position + new Vector2(64, 92);
if (Vector2.Distance(playerCenter, center) > 256)
{
Position = Vector2.Distance(playerCenter, center) * 0.03f * Vector2.Normalize(playerCenter - center) + center - new Vector2(8, 8);

}

float xSlope = (float)(-(float)(playerCenter.X - center.X));
float ySlope = (float)(playerCenter.Y - center.Y);
float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
if (t < (float)((extraVelocity > 0f) ? 192 : 64))
{
xVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, xVelocity * 1.05f));
yVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, yVelocity * 1.05f));
}
xSlope /= t;
ySlope /= t;
if (wareplacedCounter <= 0)
{
targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
{
turningRight.Value = true;
}
else if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) < 0.39269908169872414)
{
turningRight.Value = false;
}
if (turningRight)
{
rotation -= (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
}
else
{
rotation += (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
}
rotation %= 6.28318548f;
wareplacedCounter.Value = 0;
}
float maxAccel = Math.Min(5f, Math.Max(1f, 5f - t / 64f / 2f)) + extraVelocity;
xSlope = (float)Math.Cos((double)rotation + 1.5707963267948966);
ySlope = -(float)Math.Sin((double)rotation + 1.5707963267948966);
xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
if (Math.Abs(xVelocity) > Math.Abs(-xSlope * maxSpeed))
{
xVelocity -= -xSlope * maxAccel / 6f;
}
if (Math.Abs(yVelocity) > Math.Abs(-ySlope * maxSpeed))
{
yVelocity -= -ySlope * maxAccel / 6f;
}
}
}``````

19 View Source File : ToughGhost.cs
Project Creator : aedenthorn

``````public override void behaviorAtGameTick(GameTime time)
{
base.behaviorAtGameTick(time);
this.faceDirection(0);
float xSlope = (float)(-(float)(base.Player.GetBoundingBox().Center.X - this.GetBoundingBox().Center.X));
float ySlope = (float)(base.Player.GetBoundingBox().Center.Y - this.GetBoundingBox().Center.Y);
float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
if (t < 64f)
{
this.xVelocity = Math.Max(-7f, Math.Min(7f, this.xVelocity * 1.1f));
this.yVelocity = Math.Max(-7f, Math.Min(7f, this.yVelocity * 1.1f));
}
xSlope /= t;
ySlope /= t;
if (this.wareplacedCounter <= 0)
{
this.targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
if ((double)(Math.Abs(this.targetRotation) - Math.Abs(this.rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
{
this.turningRight = true;
}
else if ((double)(Math.Abs(this.targetRotation) - Math.Abs(this.rotation)) < 0.39269908169872414)
{
this.turningRight = false;
}
if (this.turningRight)
{
this.rotation -= (float)Math.Sign(this.targetRotation - this.rotation) * 0.0490873866f;
}
else
{
this.rotation += (float)Math.Sign(this.targetRotation - this.rotation) * 0.0490873866f;
}
this.rotation %= 6.28318548f;
this.wareplacedCounter = 5 + Game1.random.Next(-1, 2);
}
float maxAccel = Math.Min(7f, Math.Max(2f, 7f - t / 64f / 2f))*2;
xSlope = (float)Math.Cos((double)this.rotation + 1.5707963267948966);
ySlope = -(float)Math.Sin((double)this.rotation + 1.5707963267948966);
this.xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
this.yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
if (Math.Abs(this.xVelocity) > Math.Abs(-xSlope * 7f))
{
this.xVelocity -= -xSlope * maxAccel / 6f;
}
if (Math.Abs(this.yVelocity) > Math.Abs(-ySlope * 7f))
{
this.yVelocity -= -ySlope * maxAccel / 6f;
}
}``````

19 View Source File : Visuals.cs
Project Creator : aedenthorn

``````public static void Display_RenderedWorld(object sender, RenderedWorldEventArgs e)
{

if (api.IsCallingNPC())
return;

Vector2 screenPos = api.GetScreenPosition();
Vector2 screenSize = api.GetScreenSize();
if (!api.GetPhoneOpened() || !api.GetAppRunning() || api.GetRunningApp() != Helper.ModRegistry.ModID)
{
Monitor.Log(\$"Closing app: phone opened {api.GetPhoneOpened()} app running {api.GetAppRunning()} running app {api.GetRunningApp()}");
CataloguesApp.CloseApp();
return;
}

if (!clicking)
dragging = false;

Point mousePos = Game1.getMousePosition();
if (clicking)
{
if (mousePos.Y != lastMousePosition.Y && (dragging || api.GetScreenRectangle().Contains(mousePos)))
{
dragging = true;
offsetY += mousePos.Y - lastMousePosition.Y;
//Monitor.Log(\$"offsetY {offsetY} max {screenSize.Y - Config.MarginY + (Config.MarginY + Game1.dialogueFont.LineSpacing * 0.9f) * audio.Length}");
offsetY = Math.Min(0, Math.Max(offsetY, (int)(screenSize.Y - (Config.AppHeaderHeight + Config.MarginY + (Config.MarginY + Config.AppRowHeight) * CataloguesApp.catalogueList.Count))));
lastMousePosition = mousePos;
}
}

if (clicking && !Helper.Input.IsSuppressed(SButton.MouseLeft))
{
Monitor.Log(\$"unclicking; dragging = {dragging}");
if (dragging)
dragging = false;
else if (api.GetScreenRectangle().Contains(mousePos) && !new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, Config.AppHeaderHeight).Contains(mousePos))
{
CataloguesApp.ClickRow(mousePos);
}
clicking = false;
}

e.SpriteBatch.Draw(backgroundTexture, new Rectangle((int)screenPos.X, (int)screenPos.Y, (int)screenSize.X, (int)screenSize.Y), Color.White);
for (int i = 0; i < CataloguesApp.catalogueList.Count; i++)
{
string a = Helper.Translation.Get(CataloguesApp.catalogueList[i]);
float posY = screenPos.Y + Config.AppHeaderHeight + Config.MarginY * (i + 1) + i * Config.AppRowHeight + offsetY;
Rectangle r = new Rectangle((int)screenPos.X, (int)posY, (int)screenSize.X, Config.AppRowHeight);
bool bought = !Config.RequireCataloguePurchase || Game1.player.mailReceived.Contains(\$"BoughtCatalogue{a}");
if (!bought)
{
float backPosY = posY;
int cutTop = 0;
int cutBottom = 0;

if (posY < screenPos.Y + Config.AppHeaderHeight)
{
cutTop = (int)(screenPos.Y - posY);
backPosY = screenPos.Y;
}
if (posY > screenPos.Y + screenSize.Y - Config.AppRowHeight)
cutBottom = (int)(posY - screenPos.Y + screenSize.Y - Config.AppRowHeight);
r = new Rectangle((int)screenPos.X, (int)backPosY, (int)screenSize.X, (int)(Config.AppRowHeight) - cutTop - cutBottom);
if (!r.Contains(mousePos))
e.SpriteBatch.Draw(greyedTexture, r, Color.White);
}

if(r.Contains(mousePos))
e.SpriteBatch.Draw(hightlightTexture, r, Color.White);

float textHeight = Game1.dialogueFont.MeasureString(a).Y * Config.TextScale;
if (posY > screenPos.Y && posY < screenPos.Y + screenSize.Y - Config.AppRowHeight / 2f + textHeight / 2f)
{
e.SpriteBatch.DrawString(Game1.dialogueFont, a, new Vector2(screenPos.X + Config.MarginX, posY + Config.AppRowHeight / 2f - textHeight / 2f), Config.TextColor, 0f, Vector2.Zero, Config.TextScale, SpriteEffects.None, 0.86f);
if (!bought)
{
string cost = ""+CataloguesApp.GetCataloguePrice(CataloguesApp.catalogueList[i]);
Vector2 buySize = Game1.dialogueFont.MeasureString(cost) * Config.TextScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, cost, new Vector2(screenPos.X + screenSize.X - buySize.X - Config.AppRowHeight * 3 / 4, posY + Config.AppRowHeight / 2f - buySize.Y / 2f), Config.TextColor, 0f, Vector2.Zero, Config.TextScale, SpriteEffects.None, 0.86f);
e.SpriteBatch.Draw(coinTexture, new Rectangle((int)(screenPos.X + screenSize.X - Config.AppRowHeight * 3 / 4f), (int)(posY + Config.AppRowHeight / 4f), (int)(Config.AppRowHeight / 2f), (int)(Config.AppRowHeight / 2f)), Color.White);
}
}
}
Vector2 xSize = Game1.dialogueFont.MeasureString("x") * Config.HeaderTextScale;
e.SpriteBatch.DrawString(Game1.dialogueFont, "x", new Vector2(screenPos.X + screenSize.X - Config.AppHeaderHeight / 2f - xSize.X / 2f, screenPos.Y + Config.AppHeaderHeight / 2f - xSize.Y / 2f), Config.HeaderTextColor, 0f, Vector2.Zero, Config.HeaderTextScale, SpriteEffects.None, 0.86f);
}``````

19 View Source File : ButterflyFamiliar.cs
Project Creator : aedenthorn

``````public override void behaviorAtGameTick(GameTime time)
{
invincibleCountdown = 1000;
if (timeBeforeAIMovementAgain > 0f)
{
timeBeforeAIMovementAgain -= time.ElapsedGameTime.Milliseconds;
}
if (lastBuff >= 0)
{
lastBuff.Value -= time.ElapsedGameTime.Milliseconds;
}

if (wareplacedCounter >= 0)
{
wareplacedCounter.Value -= time.ElapsedGameTime.Milliseconds;
}

if (followingOwner)
{

Vector2 center = Position + new Vector2(8, 8);
Vector2 playerCenter = GetOwner().position + new Vector2(64, 92);
if (Vector2.Distance(playerCenter, center) > 256)
{
Position = Vector2.Distance(playerCenter, center) * 0.03f * Vector2.Normalize(playerCenter - center) + center - new Vector2(8,8);

}

float xSlope = (float)(-(float)(playerCenter.X - center.X));
float ySlope = (float)(playerCenter.Y - center.Y);
float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
if (t < (float)((extraVelocity > 0f) ? 192 : 64))
{
xVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, xVelocity * 1.05f));
yVelocity = Math.Max(-maxSpeed, Math.Min(maxSpeed, yVelocity * 1.05f));
}
xSlope /= t;
ySlope /= t;
if (wareplacedCounter <= 0)
{
targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
{
turningRight.Value = true;
}
else if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) < 0.39269908169872414)
{
turningRight.Value = false;
}
if (turningRight)
{
rotation -= (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
}
else
{
rotation += (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
}
rotation %= 6.28318548f;
wareplacedCounter.Value = 0;
}
float maxAccel = Math.Min(5f, Math.Max(1f, 5f - t / 64f / 2f)) + extraVelocity;
xSlope = (float)Math.Cos((double)rotation + 1.5707963267948966);
ySlope = -(float)Math.Sin((double)rotation + 1.5707963267948966);
xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
if (Math.Abs(xVelocity) > Math.Abs(-xSlope * maxSpeed))
{
xVelocity -= -xSlope * maxAccel / 6f;
}
if (Math.Abs(yVelocity) > Math.Abs(-ySlope * maxSpeed))
{
yVelocity -= -ySlope * maxAccel / 6f;
}
if (lastBuff <= 0 && Vector2.Distance(GetOwner().getTileLocation(), getTileLocation()) < 3)
{
if (Game1.random.NextDouble() < BuffChance())
{
if (ModEntry.Config.ButterflySoundEffects)
Game1.playSound("yoba");
BuffsDisplay buffsDisplay = Game1.buffsDisplay;
Buff buff2 = GetBuff();
lastBuff.Value = GetBuffInterval();
}
else
lastBuff.Value = 1000;
}
}
}``````

19 View Source File : ModEntry.cs
Project Creator : aedenthorn

``````private static async void HereFishyFishy(Farmer who, int x, int y)
{
hereFishying = true;
if (fishySound != null)
{
fishySound.Play();
}
who.completelyStopAnimatingOrDoingAction();
who.jitterStrength = 2f;
List<FarmerSprite.AnimationFrame> animationFrames = new List<FarmerSprite.AnimationFrame>(){
new FarmerSprite.AnimationFrame(94, 100, false, false, null, false).AddFrameAction(delegate (Farmer f)
{
f.jitterStrength = 2f;
})
};
who.FarmerSprite.setCurrentAnimation(animationFrames.ToArray());
who.FarmerSprite.PauseForSingleAnimation = true;
who.FarmerSprite.loop = true;
who.FarmerSprite.loopThisAnimation = true;
who.Sprite.currentFrame = 94;

canPerfect = true;
perfect = false;

who.synchronizedJump(8f);

canPerfect = false;

who.stopJittering();
who.completelyStopAnimatingOrDoingAction();
who.forceCanMove();

hereFishying = false;

Object o = who.currentLocation.getFish(0, -1, 1, who, 0, new Vector2(x, y), who.currentLocation.Name);
if (o == null || o.ParentSheetIndex <= 0)
{
o = new Object(Game1.random.Next(167, 173), 1, false, -1, 0);
}

int parentSheetIndex = o.parentSheetIndex;
animations.Clear();
float t;
lastUser = who;
whichFish = parentSheetIndex;
Dictionary<int, string> data = Game1.content.Load<Dictionary<int, string>>("Data\\Fish");
string[] datas = null;
if (data.ContainsKey(whichFish))
{
datas = data[whichFish].Split('/');
}

bool non_fishable_fish = false;
if (o is Furniture)
{
non_fishable_fish = true;
}
else if (Utility.IsNormalObjectAtParentSheetIndex(o, o.ParentSheetIndex) && data.ContainsKey(o.ParentSheetIndex))
{
string[] array = data[o.ParentSheetIndex].Split(new char[]
{
'/'
});
int difficulty = -1;
if (!int.TryParse(array[1], out difficulty))
{
non_fishable_fish = true;
}
}
else
{
non_fishable_fish = true;
}

float fs = 1f;
int minimumSizeContribution = 1 + who.FishingLevel / 2;
fs *= (float)Game1.random.Next(minimumSizeContribution, Math.Max(6, minimumSizeContribution)) / 5f;
fs *= 1.2f;
fs *= 1f + (float)Game1.random.Next(-10, 11) / 100f;
fs = Math.Max(0f, Math.Min(1f, fs));
if(datas != null && !non_fishable_fish)
{
try
{
int minFishSize = int.Parse(datas[3]);
int maxFishSize = int.Parse(datas[4]);
fishSize = (int)((float)minFishSize + (float)(maxFishSize - minFishSize) * fishSize);
fishSize++;
fishQuality = (((double)fishSize < 0.33) ? 0 : (((double)fishSize < 0.66) ? 1 : 2));
if (perfect)
fishQuality *= 2;
}
catch
{
context.Monitor.Log(\$"Error getting fish size from {data[whichFish]}", LogLevel.Error);
}
}
bossFish = FishingRod.isFishBossFish(whichFish);
caughtDoubleFish = !bossFish && Game1.random.NextDouble() < 0.1 + Game1.player.DailyLuck / 2.0;

context.Monitor.Log(\$"pulling fish {whichFish} {fishSize} {who.Name} {x},{y}");

if (who.IsLocalPlayer)
{
if (datas != null && !non_fishable_fish)
{
fishDifficulty = int.Parse(datas[1]);

}
else
fishDifficulty = 0;

int experience = Math.Max(1, (fishQuality + 1) * 3 + fishDifficulty / 3);
if (bossFish)
{
experience *= 5;
}

if(perfect)
experience += (int)((float)experience * 1.4f);

who.gainExperience(1, experience);
}

if (who.FacingDirection == 1 || who.FacingDirection == 3)
{
float distance = Vector2.Distance(new Vector2(x, y), who.Position);
float gravity = 0.001f;
float height = 128f - (who.Position.Y - y + 10f);
double angle = 1.1423973285781066;
float yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
if (float.IsNaN(yVelocity))
{
yVelocity = 0.6f;
}
float xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
t = distance / xVelocity;
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x,y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
acceleration = new Vector2(0f, gravity),
timeBasedMotion = true,
endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
extraInfoForEndBehavior = parentSheetIndex,
endSound = "tinyWhip"
});
if (caughtDoubleFish)
{
distance = Vector2.Distance(new Vector2(x, y), who.Position);
gravity = 0.0008f;
height = 128f - (who.Position.Y - y + 10f);
angle = 1.1423973285781066;
yVelocity = (float)((double)(distance * gravity) * Math.Tan(angle) / Math.Sqrt((double)(2f * distance * gravity) * Math.Tan(angle) - (double)(2f * gravity * height)));
if (float.IsNaN(yVelocity))
{
yVelocity = 0.6f;
}
xVelocity = (float)((double)yVelocity * (1.0 / Math.Tan(angle)));
t = distance / xVelocity;
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2((float)((who.FacingDirection == 3) ? -1 : 1) * -xVelocity, -yVelocity),
acceleration = new Vector2(0f, gravity),
timeBasedMotion = true,
endSound = "fishSlap",
Parent = who.currentLocation
});
}
}
else
{
float distance2 = y - (float)(who.getStandingY() - 64);
float height2 = Math.Abs(distance2 + 256f + 32f);
if (who.FacingDirection == 0)
{
height2 += 96f;
}
float gravity2 = 0.003f;
float velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
float xVelocity2 = 0f;
if (t != 0f)
{
xVelocity2 = (who.Position.X - x) / t;
}
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2(xVelocity2, -velocity),
acceleration = new Vector2(0f, gravity2),
timeBasedMotion = true,
endFunction = new TemporaryAnimatedSprite.endBehavior(playerCaughtFishEndFunction),
extraInfoForEndBehavior = parentSheetIndex,
endSound = "tinyWhip"
});
if (caughtDoubleFish)
{
distance2 = y - (float)(who.getStandingY() - 64);
height2 = Math.Abs(distance2 + 256f + 32f);
if (who.FacingDirection == 0)
{
height2 += 96f;
}
gravity2 = 0.004f;
velocity = (float)Math.Sqrt((double)(2f * gravity2 * height2));
t = (float)(Math.Sqrt((double)(2f * (height2 - distance2) / gravity2)) + (double)(velocity / gravity2));
xVelocity2 = 0f;
if (t != 0f)
{
xVelocity2 = (who.Position.X - x) / t;
}
animations.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, parentSheetIndex, 16, 16), t, 1, 0, new Vector2(x, y), false, false, y / 10000f, 0f, Color.White, 4f, 0f, 0f, 0f, false)
{
motion = new Vector2(xVelocity2, -velocity),
acceleration = new Vector2(0f, gravity2),
timeBasedMotion = true,
endSound = "fishSlap",
Parent = who.currentLocation
});
}
}
}``````

19 View Source File : ModEntry.cs
Project Creator : aedenthorn

``````public static void Object_draw_Postfix2(Object __instance, SpriteBatch spriteBatch, int x, int y)
{
if (!__instance.name.EndsWith("Pet Bowl") || !__instance.modData.ContainsKey("aedenthorn.PetBowl/Watered") || __instance.modData["aedenthorn.PetBowl/Watered"] != "true")
return;

Vector2 position = Game1.GlobalToLocal(Game1.viewport, new Vector2((float)(x * 64), (float)(y * 64 - 64)));

float draw_layer = Math.Max(0f, ((y + 1) * 64 - 24 + 1) / 10000f) + (x + 1) * 1E-05f;

spriteBatch.Draw(waterTexture, position, new Rectangle(0, 0, waterTexture.Width, waterTexture.Height), Color.White, 0f, Vector2.Zero, 4f, SpriteEffects.None, draw_layer);

}``````

19 View Source File : ModEntry.cs
Project Creator : aedenthorn

``````private static void SquidKid_behaviorAtGameTick_prefix(ref GameTime time, SquidKid __instance, ref float ___lastFireball)
{
if (__instance.Health <= 0 || Config.MonstersIgnorePlayer)
{
___lastFireball = Math.Max(1f, ___lastFireball);
time = new GameTime(TimeSpan.Zero, TimeSpan.Zero);
{
__instance.moveTowardPlayerThreshold.Value = -1;
}
}
}``````

19 View Source File : GrangePatches.cs
Project Creator : aedenthorn

``````public static void Object_draw_Postfix2(Object __instance, SpriteBatch spriteBatch, int x, int y)
{
if (!Game1.player.team.grangeDisplay.Any() || __instance.name != "Grange Display" || !__instance.modData.ContainsKey("spacechase0.BiggerCraftables/BiggerIndex") || __instance.modData["spacechase0.BiggerCraftables/BiggerIndex"] != "9")
return;
float drawLayer = Math.Max(0f, ((y + 1) * 64 - 24) / 10000f) + x * 1E-05f;

drawGrangeItems(__instance, spriteBatch, drawLayer);

}``````

19 View Source File : ModEntry.cs
Project Creator : aedenthorn

``````private static bool Chest_draw_Prefix(Chest __instance, SpriteBatch spriteBatch, int x, int y, float alpha)
{
if (!customChestTypesDict.TryGetValue(__instance.ParentSheetIndex, out var chestInfo))
return true;

float base_sort_order = Math.Max(0f, ((y + 1f) * 64f - 24f) / 10000f) + y * 1E-05f;
int currentFrame = alpha < 1 ? 1 : (int) MathHelper.Clamp(SHelper.Reflection.GetField<int>(__instance, "currentLidFrame").GetValue(), 1, chestInfo.frames);
Texture2D texture = chestInfo.texture.ElementAt(currentFrame-1);
spriteBatch.Draw(texture, Game1.GlobalToLocal(Game1.viewport, new Vector2(x * 64f + (float)((__instance.shakeTimer > 0) ? Game1.random.Next(-1, 2) : 0), (y - texture.Height / 16 + 1) * 64f)), new Rectangle(0,0, texture.Width, texture.Height), __instance.Tint * alpha, 0f, Vector2.Zero, 4f, SpriteEffects.None, base_sort_order);

return false;
}``````

19 View Source File : ModEntry.cs
Project Creator : aedenthorn

``````private static bool Object_draw_Prefix(Object __instance, SpriteBatch spriteBatch, int x, int y, float alpha)
{
if (!customChestTypesDict.TryGetValue(__instance.ParentSheetIndex, out var chestInfo))
return true;

float base_sort_order = Math.Max(0f, ((y + 1f) * 64f - 24f) / 10000f) + y * 1E-05f;
int currentFrame = alpha < 1 ? 1 : (int) MathHelper.Clamp(SHelper.Reflection.GetField<int>(__instance, "currentLidFrame").GetValue(), 1, chestInfo.frames);
Texture2D texture = chestInfo.texture.ElementAt(currentFrame-1);
spriteBatch.Draw(texture, Game1.GlobalToLocal(Game1.viewport, new Vector2(x * 64f + (float)((__instance.shakeTimer > 0) ? Game1.random.Next(-1, 2) : 0), (y - texture.Height / 16 + 1) * 64f)), new Rectangle(0,0, texture.Width, texture.Height), Color.White * alpha, 0f, Vector2.Zero, 4f, SpriteEffects.None, base_sort_order);

return false;
}``````

19 View Source File : Fishie.cs
Project Creator : aedenthorn

``````protected override void updateAnimation(GameTime time)
{
base.updateAnimation(time);
if (wareplacedCounter >= 0)
{
wareplacedCounter -= time.ElapsedGameTime.Milliseconds;
}
Sprite.Animate(time, 0, 9, 40f);
float xSlope = (float)(-(float)(base.Player.GetBoundingBox().Center.X - GetBoundingBox().Center.X));
float ySlope = (float)(base.Player.GetBoundingBox().Center.Y - GetBoundingBox().Center.Y);
float t = Math.Max(1f, Math.Abs(xSlope) + Math.Abs(ySlope));
if (t < 64f)
{
xVelocity = Math.Max(-7f, Math.Min(7f, xVelocity * 1.1f));
yVelocity = Math.Max(-7f, Math.Min(7f, yVelocity * 1.1f));
}
xSlope /= t;
ySlope /= t;
if (wareplacedCounter <= 0)
{
targetRotation = (float)Math.Atan2((double)(-(double)ySlope), (double)xSlope) - 1.57079637f;
if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) > 2.748893571891069 && Game1.random.NextDouble() < 0.5)
{
turningRight = true;
}
else if ((double)(Math.Abs(targetRotation) - Math.Abs(rotation)) < 0.39269908169872414)
{
turningRight = false;
}
if (turningRight)
{
rotation -= (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
}
else
{
rotation += (float)Math.Sign(targetRotation - rotation) * 0.0490873866f;
}
rotation %= 6.28318548f;
wareplacedCounter = 5 + Game1.random.Next(-1, 2);
}
float maxAccel = Math.Min(7f, Math.Max(2f, 7f - t / 64f / 2f));
xSlope = (float)Math.Cos((double)rotation + 1.5707963267948966);
ySlope = -(float)Math.Sin((double)rotation + 1.5707963267948966);
xVelocity += -xSlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
yVelocity += -ySlope * maxAccel / 6f + (float)Game1.random.Next(-10, 10) / 100f;
if (Math.Abs(xVelocity) > Math.Abs(-xSlope * 7f))
{
xVelocity -= -xSlope * maxAccel / 6f;
}
if (Math.Abs(yVelocity) > Math.Abs(-ySlope * 7f))
{
yVelocity -= -ySlope * maxAccel / 6f;
}
base.resetAnimationSpeed();
}``````

19 View Source File : ObjectPatches.cs
Project Creator : aedenthorn

``````public static void Object_draw_Prefix(StardewValley.Object __instance, ref float alpha)
{

if (!ModEntry.IsAllowed(__instance.name) || ModEntry.IsOff() || !__instance.bigCraftable.Value)
return;

float maxDistance = Config.TransparencyMaxDistance;
Vector2 playerCenter = new Vector2(Game1.player.position.X + 32, Game1.player.position.Y + 32);
Vector2 objectCenter = new Vector2(__instance.TileLocation.X * 64 + 32, __instance.TileLocation.Y * 64);
float distance = Vector2.Distance(playerCenter, objectCenter);
if (distance < maxDistance)
{
float minAlpha = Math.Min(1f, Math.Max(0, Config.MinTransparency));
float fraction = (Math.Max(0,distance)) / maxDistance;
alpha = minAlpha + (1 - minAlpha) * fraction;
}
}``````

19 View Source File : ObjectPatches.cs
Project Creator : aedenthorn

``````public static void Crop_draw_Prefix(Crop __instance, Vector2 tileLocation, Color toTint, float rotation)
{
__instance.tintColor.A = 255;
if (!__instance.raisedSeeds.Value || !ModEntry.IsAllowed("Crop"+__instance.indexOfHarvest.Value) || ModEntry.IsOff())
return;

float maxDistance = Config.TransparencyMaxDistance;
Vector2 playerCenter = new Vector2(Game1.player.position.X + 32, Game1.player.position.Y + 32);
Vector2 objectCenter = new Vector2(tileLocation.X * 64 + 32, tileLocation.Y * 64);
float distance = Vector2.Distance(playerCenter, objectCenter);
if (distance < maxDistance)
{
float minAlpha = Math.Min(1f, Math.Max(0, Config.MinTransparency));
float fraction = (Math.Max(0,distance)) / maxDistance;
byte alpha = (byte)Math.Round((minAlpha + (1 - minAlpha) * fraction) * 255);
if(__instance.tintColor.Value != Color.White)
{
__instance.tintColor.A = alpha;
}
toTint.A = alpha;
}
}``````

19 View Source File : Utils.cs
Project Creator : aedenthorn

``````internal static float Clamp(float min, float max, float val)
{
return Math.Max(min, Math.Min(max, val));
}``````

19 View Source File : BoxShape.cs
Project Creator : aeroson

``````public override bool RayTest(ref Ray ray, ref RigidTransform transform, float maximumLength, out RayHit hit)
{
hit = new RayHit();

Quaternion conjugate;
Quaternion.Conjugate(ref transform.Orientation, out conjugate);
Vector3 localOrigin;
Vector3.Subtract(ref ray.Position, ref transform.Position, out localOrigin);
Quaternion.Transform(ref localOrigin, ref conjugate, out localOrigin);
Vector3 localDirection;
Quaternion.Transform(ref ray.Direction, ref conjugate, out localDirection);
Vector3 normal = Toolbox.ZeroVector;
float temp, tmin = 0, tmax = maximumLength;

if (Math.Abs(localDirection.X) < Toolbox.Epsilon && (localOrigin.X < -halfWidth || localOrigin.X > halfWidth))
return false;
float inverseDirection = 1 / localDirection.X;
float t1 = (-halfWidth - localOrigin.X) * inverseDirection;
float t2 = (halfWidth - localOrigin.X) * inverseDirection;
var tempNormal = new Vector3(-1, 0, 0);
if (t1 > t2)
{
temp = t1;
t1 = t2;
t2 = temp;
tempNormal *= -1;
}
temp = tmin;
tmin = Math.Max(tmin, t1);
if (temp != tmin)
normal = tempNormal;
tmax = Math.Min(tmax, t2);
if (tmin > tmax)
return false;
if (Math.Abs(localDirection.Y) < Toolbox.Epsilon && (localOrigin.Y < -halfHeight || localOrigin.Y > halfHeight))
return false;
inverseDirection = 1 / localDirection.Y;
t1 = (-halfHeight - localOrigin.Y) * inverseDirection;
t2 = (halfHeight - localOrigin.Y) * inverseDirection;
tempNormal = new Vector3(0, -1, 0);
if (t1 > t2)
{
temp = t1;
t1 = t2;
t2 = temp;
tempNormal *= -1;
}
temp = tmin;
tmin = Math.Max(tmin, t1);
if (temp != tmin)
normal = tempNormal;
tmax = Math.Min(tmax, t2);
if (tmin > tmax)
return false;
if (Math.Abs(localDirection.Z) < Toolbox.Epsilon && (localOrigin.Z < -halfLength || localOrigin.Z > halfLength))
return false;
inverseDirection = 1 / localDirection.Z;
t1 = (-halfLength - localOrigin.Z) * inverseDirection;
t2 = (halfLength - localOrigin.Z) * inverseDirection;
tempNormal = new Vector3(0, 0, -1);
if (t1 > t2)
{
temp = t1;
t1 = t2;
t2 = temp;
tempNormal *= -1;
}
temp = tmin;
tmin = Math.Max(tmin, t1);
if (temp != tmin)
normal = tempNormal;
tmax = Math.Min(tmax, t2);
if (tmin > tmax)
return false;
hit.T = tmin;
Vector3.Multiply(ref ray.Direction, tmin, out hit.Location);
Vector3.Add(ref hit.Location, ref ray.Position, out hit.Location);
Quaternion.Transform(ref normal, ref transform.Orientation, out normal);
hit.Normal = normal;
return true;
}``````

19 View Source File : EllipseSwingLimit.cs
Project Creator : aeroson

``````public override void Update(float dt)
{
//Transform the axes into world space.
basis.rotationMatrix = connectionA.orientationMatrix;
basis.ComputeWorldSpaceAxes();
Matrix3x3.Transform(ref localTwistAxisB, ref connectionB.orientationMatrix, out worldTwistAxisB);

//Compute the individual swing angles.
Quaternion relativeRotation;
Quaternion.GetQuaternionBetweenNormalizedVectors(ref worldTwistAxisB, ref basis.primaryAxis, out relativeRotation);
Vector3 axis;
float angle;
Quaternion.GetAxisAngleFromQuaternion(ref relativeRotation, out axis, out angle);

#if !WINDOWS
Vector3 axisAngle = new Vector3();
#else
Vector3 axisAngle;
#endif
//This combined axis-angle representation is similar to angular velocity in describing a rotation.
//Just like you can dot an axis with angular velocity to get a velocity around that axis,
//dotting an axis with the axis-angle representation gets the angle of rotation around that axis.
//(As far as the constraint is concerned, anyway.)
axisAngle.X = axis.X * angle;
axisAngle.Y = axis.Y * angle;
axisAngle.Z = axis.Z * angle;

float angleX;
Vector3.Dot(ref axisAngle, ref basis.xAxis, out angleX);
float angleY;
Vector3.Dot(ref axisAngle, ref basis.yAxis, out angleY);

//The position constraint states that the angles must be within an ellipse. The following is just a reorganization of the x^2 / a^2 + y^2 / b^2 <= 1 definition of an ellipse's area.
float maxAngleXSquared = maximumAngleX * maximumAngleX;
float maxAngleYSquared = maximumAngleY * maximumAngleY;
error = angleX * angleX * maxAngleYSquared + angleY * angleY * maxAngleXSquared - maxAngleXSquared * maxAngleYSquared;

if (error < 0)
{
isActiveInSolver = false;
error = 0;
acreplacedulatedImpulse = 0;
isLimitActive = false;
return;
}
isLimitActive = true;

//Derive the position constraint with respect to time to get the velocity constraint.
//d/dt(x^2 / a^2 + y^2 / b^2) <= d/dt(1)
//(2x / a^2) * d/dt(x) + (2y / b^2) * d/dt(y) <= 0
//d/dt(x) is dot(angularVelocity, xAxis).
//d/dt(y) is dot(angularVelocity, yAxis).
//By the scalar multiplication properties of dot products, this can be written as:
//dot((2x / a^2) * xAxis, angularVelocity) + dot((2y / b^2) * yAxis, angularVelocity) <= 0
//And by the distribute property, rewrite it as:
//dot((2x / a^2) * xAxis + (2y / b^2) * yAxis, angularVelocity) <= 0
//So, by inspection, the jacobian is:
//(2x / a^2) * xAxis + (2y / b^2) * yAxis

//[some handwaving in the above: 'angularVelocity' is actually the angular velocities of the involved enreplacedies combined.
//Splitting it out fully would reveal two dot products with equivalent but negated jacobians.]

//The jacobian is implemented by first considering the local values (2x / a^2) and (2y / b^2).
#if !WINDOWS
Vector2 tangent = new Vector2();
#else
Vector2 tangent;
#endif
tangent.X = 2 * angleX / maxAngleXSquared;
tangent.Y = 2 * angleY / maxAngleYSquared;

//The tangent is then taken into world space using the basis.

//Create a rotation which swings our basis 'out' to b's world orientation.
Quaternion.Conjugate(ref relativeRotation, out relativeRotation);
Vector3 sphereTangentX, sphereTangentY;
Quaternion.Transform(ref basis.xAxis, ref relativeRotation, out sphereTangentX);
Quaternion.Transform(ref basis.yAxis, ref relativeRotation, out sphereTangentY);

Vector3.Multiply(ref sphereTangentX, tangent.X, out jacobianA); //not actually jA, just storing it there.
Vector3.Multiply(ref sphereTangentY, tangent.Y, out jacobianB); //not actually jB, just storing it there.
Vector3.Add(ref jacobianA, ref jacobianB, out jacobianA);

jacobianB.X = -jacobianA.X;
jacobianB.Y = -jacobianA.Y;
jacobianB.Z = -jacobianA.Z;

float errorReduction;
float inverseDt = 1 / dt;
springSettings.ComputeErrorReductionAndSoftness(dt, inverseDt, out errorReduction, out softness);

//Compute the error correcting velocity
error = error - margin;
biasVelocity = MathHelper.Min(Math.Max(error, 0) * errorReduction, maxCorrectiveVelocity);

if (bounciness > 0)
{
float relativeVelocity;
float dot;
//Find the velocity contribution from each connection
Vector3.Dot(ref connectionA.angularVelocity, ref jacobianA, out relativeVelocity);
Vector3.Dot(ref connectionB.angularVelocity, ref jacobianB, out dot);
relativeVelocity += dot;
biasVelocity = MathHelper.Max(biasVelocity, ComputeBounceVelocity(relativeVelocity));

}

//****** EFFECTIVE Mreplaced MATRIX ******//
//Connection A's contribution to the mreplaced matrix
float entryA;
Vector3 transformedAxis;
if (connectionA.isDynamic)
{
Matrix3x3.Transform(ref jacobianA, ref connectionA.inertiaTensorInverse, out transformedAxis);
Vector3.Dot(ref transformedAxis, ref jacobianA, out entryA);
}
else
entryA = 0;

//Connection B's contribution to the mreplaced matrix
float entryB;
if (connectionB.isDynamic)
{
Matrix3x3.Transform(ref jacobianB, ref connectionB.inertiaTensorInverse, out transformedAxis);
Vector3.Dot(ref transformedAxis, ref jacobianB, out entryB);
}
else
entryB = 0;

//Compute the inverse mreplaced matrix
velocityToImpulse = 1 / (softness + entryA + entryB);

}``````

19 View Source File : WheelShape.cs
Project Creator : aeroson

``````internal void UpdateSpin(float dt)
{
if (wheel.Hreplacedupport && !(wheel.brake.IsBraking && FreezeWheelsWhileBraking))
{
//On the ground, not braking.
}
else if (wheel.Hreplacedupport && wheel.brake.IsBraking && FreezeWheelsWhileBraking)
{
//On the ground, braking
float deceleratedValue = 0;
if (spinVelocity > 0)
deceleratedValue = Math.Max(spinVelocity - brakeFreezeWheelDeceleration * dt, 0);
else if (spinVelocity < 0)
deceleratedValue = Math.Min(spinVelocity + brakeFreezeWheelDeceleration * dt, 0);

if (Math.Abs(deceleratedValue) < Math.Abs(spinVelocity))
spinVelocity = deceleratedValue;
}
else if (!wheel.Hreplacedupport && wheel.drivingMotor.TargetSpeed != 0)
{
//Airborne and accelerating, increase spin velocity.
float maxSpeed = Math.Abs(wheel.drivingMotor.TargetSpeed) / Radius;
spinVelocity = MathHelper.Clamp(spinVelocity + Math.Sign(wheel.drivingMotor.TargetSpeed) * airborneWheelAcceleration * dt, -maxSpeed, maxSpeed);
}
else if (!wheel.Hreplacedupport && wheel.Brake.IsBraking)
{
//Airborne and braking
if (spinVelocity > 0)
spinVelocity = Math.Max(spinVelocity - brakeFreezeWheelDeceleration * dt, 0);
else if (spinVelocity < 0)
spinVelocity = Math.Min(spinVelocity + brakeFreezeWheelDeceleration * dt, 0);
}
else if (!wheel.Hreplacedupport)
{
//Just idly slowing down.
if (spinVelocity > 0)
spinVelocity = Math.Max(spinVelocity - airborneWheelDeceleration * dt, 0);
else if (spinVelocity < 0)
spinVelocity = Math.Min(spinVelocity + airborneWheelDeceleration * dt, 0);
}
spinAngle += spinVelocity * dt;
}``````

19 View Source File : Ray.cs
Project Creator : aeroson

``````public void Intersects(ref BoundingBox boundingBox, out float? result)
{
if (System.Math.Abs(Direction.X) < Toolbox.Epsilon && (Position.X < boundingBox.Min.X || Position.X > boundingBox.Max.X))
{
//If the ray isn't pointing along the axis at all, and is outside of the box's interval, then it
//can't be intersecting.
result = null;
return;
}
float tmin = 0, tmax = float.MaxValue;
float inverseDirection = 1 / Direction.X;
float t1 = (boundingBox.Min.X - Position.X) * inverseDirection;
float t2 = (boundingBox.Max.X - Position.X) * inverseDirection;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
tmin = System.Math.Max(tmin, t1);
tmax = System.Math.Min(tmax, t2);
if (tmin > tmax)
{
result = null;
return;
}
if (System.Math.Abs(Direction.Y) < Toolbox.Epsilon && (Position.Y < boundingBox.Min.Y || Position.Y > boundingBox.Max.Y))
{
//If the ray isn't pointing along the axis at all, and is outside of the box's interval, then it
//can't be intersecting.
result = null;
return;
}
inverseDirection = 1 / Direction.Y;
t1 = (boundingBox.Min.Y - Position.Y) * inverseDirection;
t2 = (boundingBox.Max.Y - Position.Y) * inverseDirection;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
tmin = System.Math.Max(tmin, t1);
tmax = System.Math.Min(tmax, t2);
if (tmin > tmax)
{
result = null;
return;
}
if (System.Math.Abs(Direction.Z) < Toolbox.Epsilon && (Position.Z < boundingBox.Min.Z || Position.Z > boundingBox.Max.Z))
{
//If the ray isn't pointing along the axis at all, and is outside of the box's interval, then it
//can't be intersecting.
result = null;
return;
}
inverseDirection = 1 / Direction.Z;
t1 = (boundingBox.Min.Z - Position.Z) * inverseDirection;
t2 = (boundingBox.Max.Z - Position.Z) * inverseDirection;
if (t1 > t2)
{
float temp = t1;
t1 = t2;
t2 = temp;
}
tmin = System.Math.Max(tmin, t1);
tmax = System.Math.Min(tmax, t2);
if (tmin > tmax)
{
result = null;
return;
}
result = tmin;
}``````

19 View Source File : FirstPersonCamera.cs
Project Creator : aeroson

``````public override void Update(double deltaTime)
{

var mouse = Mouse.GetState();

var mouseDelta = new Point(mouse.X - lastMousePos.X, mouse.Y - lastMousePos.Y);
lastMousePos = new Point(mouse.X, mouse.Y);

int scrollWheelDelta = mouse.ScrollWheelValue - scrollWheelValue;
scrollWheelValue = mouse.ScrollWheelValue;

if (Input.GetKeyDown(Key.Tab))
{
disabledInput = !disabledInput;
Screen.lockCursor = disabledInput;
}

if (disabledInput) return;

speedModifier += scrollWheelDelta;
speedModifier = Math.Max(1.0f, speedModifier);

/*
var p = System.Windows.Forms.Cursor.Position;
p.X -= mouseDelta.X;
p.Y -= mouseDelta.Y;
System.Windows.Forms.Cursor.Position = p;*/

float c = 1f * (float)deltaTime;
facing += mouseDelta.X * c;
pitch += mouseDelta.Y * c;

const float m = (float)Math.PI / 180.0f * 80.0f;
if (pitch > m) pitch = m;
if (pitch < -m) pitch = -m;

var rot = Matrix4.CreateFromQuaternion(
Quaternion.FromAxisAngle(Vector3.UnitY, -facing) *
Quaternion.FromAxisAngle(Vector3.UnitX, -pitch)
);

gameObject.transform.rotation = rot.ExtractRotation();

float d = speedModifier * (float)deltaTime;

if (Input.GetKey(Key.ShiftLeft)) d *= 5;

var targetVelocity = Vector3.Zero;
if (Input.GetKey(Key.W)) targetVelocity.Z -= d;
if (Input.GetKey(Key.S)) targetVelocity.Z += d;
if (Input.GetKey(Key.D)) targetVelocity.X += d;
if (Input.GetKey(Key.A)) targetVelocity.X -= d;
if (Input.GetKey(Key.Space)) targetVelocity.Y += d;
if (Input.GetKey(Key.ControlLeft)) targetVelocity.Y -= d;

//var pos = Matrix4.CreateTranslation(targetVelocity);

targetVelocity = Vector3.TransformPosition(targetVelocity, rot);

currentVelocity = Vector3.Lerp(currentVelocity, targetVelocity, velocityChangeSpeed * (float)deltaTime);

gameObject.transform.position += currentVelocity;

//Debug.Info(gameObject.transform.position);

}``````

19 View Source File : GraphicsManager.cs
Project Creator : aglab2

``````public void SetBackground(Image image, float opacity)
{
float Height = Width * 2;
float ratioX = Width  / image.Width;
float ratioY = Height / image.Height;
float ratio = Math.Max(ratioX, ratioY);

int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);

Background = new Bitmap((int)Width, (int)Height);

using (var graphics = Graphics.FromImage(Background))
{
ColorMatrix matrix = new ColorMatrix
{
Matrix33 = opacity
};
ImageAttributes attrs = new ImageAttributes();
attrs.SetColorMatrix(matrix);

PointF p1 = new PointF(0, 0);
PointF p2 = new PointF(Width, 0);
PointF p3 = new PointF(0, Height);

float x1 = Width / ratio; float x2 = Height / ratio;
graphics.DrawImage(image, new PointF[]{ p1, p2, p3 },
new RectangleF((image.Width - x1) / 2, (image.Height - x2) / 2, x1, x2),
GraphicsUnit.Pixel, attrs);
}
}``````

19 View Source File : Vector2.cs
Project Creator : aillieo

``````public static Vector2 Max(Vector2 lhs, Vector2 rhs)
{
return new Vector2(Math.Max(lhs.x, rhs.x), Math.Max(lhs.y, rhs.y));
}``````

19 View Source File : DynamicTextImage.cs
Project Creator : akasarto

``````public MemoryStream Build(string text)
{
text = text ?? "?";

var stream = new MemoryStream();

var backgroundColor = ColorTranslator.FromHtml(\$"#{_backgroundHexColor.Trim('#')}");
var foreGroundColor = ColorTranslator.FromHtml(\$"#{_foregroundHexColor.Trim('#')}");

using (var baseFont = _fontInstanceCreator())
{
using (var bitmap = new Bitmap(_width, _height, PixelFormat.Format24bppRgb))
{
using (var graphics = Graphics.FromImage(bitmap))
{
var textSize = graphics.MeasureString(text, baseFont);
var fontScale = Math.Max(textSize.Width / bitmap.Width, textSize.Height / bitmap.Height);

using (var scaledFont = new Font(baseFont.FontFamily, baseFont.SizeInPoints / fontScale, baseFont.Style, baseFont.Unit))
{
graphics.Clear(backgroundColor);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.TextRenderingHint = TextRenderingHint.AntiAlias;

StringFormat strinngFormat = new StringFormat(StringFormat.GenericTypographic)
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center,
FormatFlags = StringFormatFlags.MeasureTrailingSpaces
};

textSize = graphics.MeasureString(text, scaledFont);

graphics.DrawString(
text,
scaledFont,
new SolidBrush(foreGroundColor),
new RectangleF(
0,
0,
bitmap.Width,
bitmap.Height
),
strinngFormat
);

bitmap.Save(stream, ImageFormat.Png);

stream.Position = 0;
}
}
}
}

return stream;
}``````

19 View Source File : Misc.cs
Project Creator : Alan-FGR

``````public static float Max(float a, float b, float c, float d)
{
return Math.Max(a, Math.Max(b, Math.Max(c, d)));
}``````

19 View Source File : ContactSolver.cs
Project Creator : Alan-FGR

``````public void SolveVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = _velocityConstraints[i];

int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMreplacedA;
float iA = vc.invIA;
float mB = vc.invMreplacedB;
float iB = vc.invIB;
int pointCount = vc.pointCount;

Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;

Vector2 normal = vc.normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
float friction = vc.friction;

Debug.replacedert(pointCount == 1 || pointCount == 2);

// Solve tangent constraints first because non-penetration is more important
// than friction.
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.points[j];

// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);

// Compute tangent force
float vt = Vector2.Dot(dv, tangent) - vc.tangentSpeed;
float lambda = vcp.tangentMreplaced * (-vt);

// b2Clamp the acreplacedulated force
float maxFriction = friction * vcp.normalImpulse;
float newImpulse = MathUtils.Clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction);
lambda = newImpulse - vcp.tangentImpulse;
vcp.tangentImpulse = newImpulse;

// Apply contact impulse
Vector2 P = lambda * tangent;

vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);

vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}

// Solve normal constraints
if (vc.pointCount == 1)
{
VelocityConstraintPoint vcp = vc.points[0];

// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);

// Compute normal impulse
float vn = Vector2.Dot(dv, normal);
float lambda = -vcp.normalMreplaced * (vn - vcp.velocityBias);

// b2Clamp the acreplacedulated impulse
float newImpulse = Math.Max(vcp.normalImpulse + lambda, 0.0f);
lambda = newImpulse - vcp.normalImpulse;
vcp.normalImpulse = newImpulse;

// Apply contact impulse
Vector2 P = lambda * normal;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);

vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
else
{
// Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
// solution that satisfies the problem is chosen.
//
// In order to account of the acreplacedulated impulse 'a' (because of the iterative nature of the solver which only requires
// that the acreplacedulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
//
// Subsreplacedute:
//
// x = a + d
//
// a := old total impulse
// x := new total impulse
// d := incremental impulse
//
// For the current iteration we extend the formula for the incremental impulse
// to compute the new total impulse:
//
// vn = A * d + b
//    = A * (x - a) + b
//    = A * x + b - A * a
//    = A * x + b'
// b' = b - A * a;

VelocityConstraintPoint cp1 = vc.points[0];
VelocityConstraintPoint cp2 = vc.points[1];

Vector2 a = new Vector2(cp1.normalImpulse, cp2.normalImpulse);
Debug.replacedert(a.X >= 0.0f && a.Y >= 0.0f);

// Relative velocity at contact
Vector2 dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
Vector2 dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);

// Compute normal velocity
float vn1 = Vector2.Dot(dv1, normal);
float vn2 = Vector2.Dot(dv2, normal);

Vector2 b = new Vector2();
b.X = vn1 - cp1.velocityBias;
b.Y = vn2 - cp2.velocityBias;

// Compute b'
b -= MathUtils.Mul(ref vc.K, a);

const float k_errorTol = 1e-3f;
//B2_NOT_USED(k_errorTol);

for (; ; )
{
//
// Case 1: vn = 0
//
// 0 = A * x + b'
//
// Solve for x:
//
// x = - inv(A) * b'
//
Vector2 x = -MathUtils.Mul(ref vc.normalMreplaced, b);

if (x.X >= 0.0f && x.Y >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;

// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));

vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));

// Acreplacedulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;

#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);

// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
vn2 = Vector2.Dot(dv2, normal);

b2replacedert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol);
b2replacedert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}

//
// Case 2: vn1 = 0 and x2 = 0
//
//   0 = a11 * x1 + a12 * 0 + b1'
// vn2 = a21 * x1 + a22 * 0 + b2'
//
x.X = -cp1.normalMreplaced * b.X;
x.Y = 0.0f;
vn1 = 0.0f;
vn2 = vc.K.ex.Y * x.X + b.Y;

if (x.X >= 0.0f && vn2 >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;

// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));

vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));

// Acreplacedulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;

#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);

// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);

b2replacedert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol);
#endif
break;
}

//
// Case 3: vn2 = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2 + b1'
//   0 = a21 * 0 + a22 * x2 + b2'
//
x.X = 0.0f;
x.Y = -cp2.normalMreplaced * b.Y;
vn1 = vc.K.ey.X * x.Y + b.X;
vn2 = 0.0f;

if (x.Y >= 0.0f && vn1 >= 0.0f)
{
// Resubsreplacedute for the incremental impulse
Vector2 d = x - a;

// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));

vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));

// Acreplacedulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;

#if B2_DEBUG_SOLVER
// Postconditions
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);

// Compute normal velocity
vn2 = Vector2.Dot(dv2, normal);

b2replacedert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}

//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = b2;
x.X = 0.0f;
x.Y = 0.0f;
vn1 = b.X;
vn2 = b.Y;

if (vn1 >= 0.0f && vn2 >= 0.0f)
{
// Resubsreplacedute for the incremental impulse
Vector2 d = x - a;

// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));

vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));

// Acreplacedulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;

break;
}

// No solution, give up. This is hit sometimes, but it doesn't seem to matter.
break;
}
}

_velocities[indexA].v = vA;
_velocities[indexA].w = wA;
_velocities[indexB].v = vB;
_velocities[indexB].w = wB;
}
}``````

19 View Source File : PrismaticJoint.cs
Project Creator : Alan-FGR

``````internal override bool SolvePositionConstraints(ref SolverData data)
{
Vector2 cA = data.positions[_indexA].c;
float aA = data.positions[_indexA].a;
Vector2 cB = data.positions[_indexB].c;
float aB = data.positions[_indexB].a;

Rot qA = new Rot(aA), qB = new Rot(aB);

float mA = _invMreplacedA, mB = _invMreplacedB;
float iA = _invIA, iB = _invIB;

// Compute fresh Jacobians
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
Vector2 d = cB + rB - cA - rA;

Vector2 axis = MathUtils.Mul(qA, LocalXAxis);
float a1 = MathUtils.Cross(d + rA, axis);
float a2 = MathUtils.Cross(rB, axis);
Vector2 perp = MathUtils.Mul(qA, _localYAxisA);

float s1 = MathUtils.Cross(d + rA, perp);
float s2 = MathUtils.Cross(rB, perp);

Vector3 impulse;
Vector2 C1 = new Vector2();
C1.X = Vector2.Dot(perp, d);
C1.Y = aB - aA - ReferenceAngle;

float linearError = Math.Abs(C1.X);
float angularError = Math.Abs(C1.Y);

bool active = false;
float C2 = 0.0f;
if (_enableLimit)
{
float translation = Vector2.Dot(axis, d);
if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
{
// Prevent large angular corrections
C2 = MathUtils.Clamp(translation, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection);
linearError = Math.Max(linearError, Math.Abs(translation));
active = true;
}
else if (translation <= _lowerTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.Clamp(translation - _lowerTranslation + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f);
linearError = Math.Max(linearError, _lowerTranslation - translation);
active = true;
}
else if (translation >= _upperTranslation)
{
// Prevent large linear corrections and allow some slop.
C2 = MathUtils.Clamp(translation - _upperTranslation - Settings.LinearSlop, 0.0f, Settings.MaxLinearCorrection);
linearError = Math.Max(linearError, translation - _upperTranslation);
active = true;
}
}

if (active)
{
float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float k12 = iA * s1 + iB * s2;
float k13 = iA * s1 * a1 + iB * s2 * a2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
// For fixed rotation
k22 = 1.0f;
}
float k23 = iA * a1 + iB * a2;
float k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;

Mat33 K = new Mat33();
K.ex = new Vector3(k11, k12, k13);
K.ey = new Vector3(k12, k22, k23);
K.ez = new Vector3(k13, k23, k33);

Vector3 C = new Vector3();
C.X = C1.X;
C.Y = C1.Y;
C.Z = C2;

impulse = K.Solve33(-C);
}
else
{
float k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
float k12 = iA * s1 + iB * s2;
float k22 = iA + iB;
if (k22 == 0.0f)
{
k22 = 1.0f;
}

Mat22 K = new Mat22();
K.ex = new Vector2(k11, k12);
K.ey = new Vector2(k12, k22);

Vector2 impulse1 = K.Solve(-C1);
impulse = new Vector3();
impulse.X = impulse1.X;
impulse.Y = impulse1.Y;
impulse.Z = 0.0f;
}

Vector2 P = impulse.X * perp + impulse.Z * axis;
float LA = impulse.X * s1 + impulse.Y + impulse.Z * a1;
float LB = impulse.X * s2 + impulse.Y + impulse.Z * a2;

cA -= mA * P;
aA -= iA * LA;
cB += mB * P;
aB += iB * LB;

data.positions[_indexA].c = cA;
data.positions[_indexA].a = aA;
data.positions[_indexB].c = cB;
data.positions[_indexB].a = aB;

return linearError <= Settings.LinearSlop && angularError <= Settings.AngularSlop;
}``````

19 View Source File : LineTools.cs
Project Creator : Alan-FGR

``````public static bool LineIntersect2(ref Vector2 a0, ref Vector2 a1, ref Vector2 b0, ref  Vector2 b1, out Vector2 intersectionPoint)
{
intersectionPoint = Vector2.Zero;

if (a0 == b0 || a0 == b1 || a1 == b0 || a1 == b1)
return false;

float x1 = a0.X;
float y1 = a0.Y;
float x2 = a1.X;
float y2 = a1.Y;
float x3 = b0.X;
float y3 = b0.Y;
float x4 = b1.X;
float y4 = b1.Y;

//AABB early exit
if (Math.Max(x1, x2) < Math.Min(x3, x4) || Math.Max(x3, x4) < Math.Min(x1, x2))
return false;

if (Math.Max(y1, y2) < Math.Min(y3, y4) || Math.Max(y3, y4) < Math.Min(y1, y2))
return false;

float ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3));
float ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3));
float denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
if (Math.Abs(denom) < Settings.Epsilon)
{
//Lines are too close to parallel to call
return false;
}
ua /= denom;
ub /= denom;

if ((0 < ua) && (ua < 1) && (0 < ub) && (ub < 1))
{
intersectionPoint.X = (x1 + ua * (x2 - x1));
intersectionPoint.Y = (y1 + ua * (y2 - y1));
return true;
}

return false;
}``````

19 View Source File : Math.cs
Project Creator : Alan-FGR

``````public static float Clamp(float a, float low, float high)
{
return Math.Max(low, Math.Min(a, high));
}``````

19 View Source File : MathHelper.cs
Project Creator : Alan-FGR

``````public static float Max(float value1, float value2)
{
return Math.Max(value1, value2);
}``````

19 View Source File : GvrProfile.cs
Project Creator : alanplotko

``````public void GetLeftEyeVisibleTanAngles(float[] result) {
// Tan-angles from the max FOV.
float fovLeft = Mathf.Tan(-viewer.maxFOV.outer * Mathf.Deg2Rad);
float fovTop = Mathf.Tan(viewer.maxFOV.upper * Mathf.Deg2Rad);
float fovRight = Mathf.Tan(viewer.maxFOV.inner * Mathf.Deg2Rad);
float fovBottom = Mathf.Tan(-viewer.maxFOV.lower * Mathf.Deg2Rad);
// Viewport size.
float halfWidth = screen.width / 4;
float halfHeight = screen.height / 2;
// Viewport center, measured from left lens position.
float centerX = viewer.lenses.separation / 2 - halfWidth;
float centerY = -VerticalLensOffset;
float centerZ = viewer.lenses.screenDistance;
// Tan-angles of the viewport edges, as seen through the lens.
float screenLeft = viewer.distortion.distort((centerX - halfWidth) / centerZ);
float screenTop = viewer.distortion.distort((centerY + halfHeight) / centerZ);
float screenRight = viewer.distortion.distort((centerX + halfWidth) / centerZ);
float screenBottom = viewer.distortion.distort((centerY - halfHeight) / centerZ);
// Compare the two sets of tan-angles and take the value closer to zero on each side.
result[0] = Math.Max(fovLeft, screenLeft);
result[1] = Math.Min(fovTop, screenTop);
result[2] = Math.Min(fovRight, screenRight);
result[3] = Math.Max(fovBottom, screenBottom);
}``````

19 View Source File : GvrProfile.cs
Project Creator : alanplotko

``````public void GetLeftEyeNoLensTanAngles(float[] result) {
// Tan-angles from the max FOV.
float fovLeft = viewer.distortion.distortInv(Mathf.Tan(-viewer.maxFOV.outer * Mathf.Deg2Rad));
float fovTop = viewer.distortion.distortInv(Mathf.Tan(viewer.maxFOV.upper * Mathf.Deg2Rad));
float fovRight = viewer.distortion.distortInv(Mathf.Tan(viewer.maxFOV.inner * Mathf.Deg2Rad));
float fovBottom = viewer.distortion.distortInv(Mathf.Tan(-viewer.maxFOV.lower * Mathf.Deg2Rad));
// Viewport size.
float halfWidth = screen.width / 4;
float halfHeight = screen.height / 2;
// Viewport center, measured from left lens position.
float centerX = viewer.lenses.separation / 2 - halfWidth;
float centerY = -VerticalLensOffset;
float centerZ = viewer.lenses.screenDistance;
// Tan-angles of the viewport edges, as seen through the lens.
float screenLeft = (centerX - halfWidth) / centerZ;
float screenTop = (centerY + halfHeight) / centerZ;
float screenRight = (centerX + halfWidth) / centerZ;
float screenBottom = (centerY - halfHeight) / centerZ;
// Compare the two sets of tan-angles and take the value closer to zero on each side.
result[0] = Math.Max(fovLeft, screenLeft);
result[1] = Math.Min(fovTop, screenTop);
result[2] = Math.Min(fovRight, screenRight);
result[3] = Math.Max(fovBottom, screenBottom);
}``````

19 View Source File : AudioManager.cs
Project Creator : AlbertMN

``````public static float StepMasterVolume(float stepAmount) {
IAudioEndpointVolume masterVol = null;
try {
masterVol = GetMasterVolumeObject();
if (masterVol == null)
return -1;

float stepAmountScaled = stepAmount / 100;

// Get the level
masterVol.GetMasterVolumeLevelScalar(out float volumeLevel);

// Calculate the new level
float newLevel = volumeLevel + stepAmountScaled;
newLevel = Math.Min(1, newLevel);
newLevel = Math.Max(0, newLevel);

masterVol.SetMasterVolumeLevelScalar(newLevel, Guid.Empty);

// Return the new volume level that was set
return newLevel * 100;
} finally {
if (masterVol != null)
Marshal.ReleaseComObject(masterVol);
}
}``````

19 View Source File : TextureSideWallModifier.cs
Project Creator : alen-smajic

``````private void MidFloors(MeshData md)
{
_currentMidHeight = finalMidHeight;
while (_currentMidHeight >= _singleFloorHeight - 0.01f)
{
//first part is the number of floors fitting current wall segment. You can fit max of "row count in mid". Or if wall
//is smaller and it can only fit i.e. 3 floors instead of 5; we use 3/5 of the mid section texture as well.
_midUvInCurrentStep =

//top two vertices
//move offsets bottom
currentY1 -= (_scaledFloorHeight * _midUvInCurrentStep);
currentY2 -= (_scaledFloorHeight * _midUvInCurrentStep);
//bottom two vertices

//we uv narrow walls different so they won't have condensed windows
if (wallSegmentLength >= _minWallLength)
{
}
else
{
}

triIndex += 4;
_currentMidHeight -= Math.Max(0.1f, (_scaledFloorHeight * _midUvInCurrentStep));
}
}``````

19 View Source File : Earcut.cs
Project Creator : alen-smajic

``````public static List<int> Earcut(List<float> data, List<int> holeIndices, int dim)
{
dim = Math.Max(dim, 2);

var hasHoles = holeIndices.Count;
var outerLen = hasHoles > 0 ? holeIndices[0] * dim : data.Count;
var outerNode = linkedList(data, 0, outerLen, dim, true);
var triangles = new List<int>((int)(outerNode.i * 1.5));

if (outerNode == null) return triangles;
var minX = 0f;
var minY = 0f;
var maxX = 0f;
var maxY = 0f;
var x = 0f;
var y = 0f;
var size = 0f;

if (hasHoles > 0) outerNode = EliminateHoles(data, holeIndices, outerNode, dim);

// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if (data.Count > 80 * dim)
{
minX = maxX = data[0];
minY = maxY = data[1];

for (var i = dim; i < outerLen; i += dim)
{
x = data[i];
y = data[i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}

// minX, minY and size are later used to transform coords into integers for z-order calculation
size = Math.Max(maxX - minX, maxY - minY);
}

earcutLinked(outerNode, triangles, dim, minX, minY, size);

return triangles;
}``````

See More Examples