Here are the examples of the csharp api System.Collections.Generic.List.Add(Vector2) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
804 Examples
19
Source : AINavMeshGenerator.cs
with MIT License
from 7ark
with MIT License
from 7ark
private List<Vector2> ShortenPointsByVisibility(Node[] points)
{
//If we have small amount of points, dont bother with all this.
//if(points.Length < 2)
{
List<Vector2> p = new List<Vector2>();
for (int i = 0; i < points.Length; i++)
{
p.Add(points[i].position);
}
return p;
}
List<Vector2> corners = new List<Vector2>();
corners.Add(points[0].position);
Node start = points[0];
Node end = points[1];
//Go through all the points, starting at 1 (since we already set our initial start to the first point)
for (int i = 1; i < points.Length; i++)
{
//Set the end to our current point and check if its in a bad spot to hang out in town.
end = null;
end = points[i];
bool inBadArea = end.AnyConnectionsBad();
if(inBadArea)
{
//If it's a bad boy, we add it to our corners, so we walk this way.
corners.Add(end.position);
//Then start anew.
start = null;
start = end;
}
}
//Add that last rebel into the mix for sure.
corners.Add(points[points.Length - 1].position);
return corners;
}
19
Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static void BuildSphere(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 position, Quaternion rotation, Vector3 scale, Rect rect, float worldScale = 800, int lareplacedudes = 128, int longitudes = 128, float expand_coef = 1.0f)
{
position = Quaternion.Inverse(rotation) * position;
lareplacedudes = Mathf.CeilToInt(lareplacedudes * rect.height);
longitudes = Mathf.CeilToInt(longitudes * rect.width);
float minTheta = Mathf.PI * 2 * ( rect.x);
float minPhi = Mathf.PI * (0.5f - rect.y - rect.height);
float thetaScale = Mathf.PI * 2 * rect.width / longitudes;
float phiScale = Mathf.PI * rect.height / lareplacedudes;
for (int j = 0; j < lareplacedudes + 1; j += 1)
{
for (int k = 0; k < longitudes + 1; k++)
{
float theta = minTheta + k * thetaScale;
float phi = minPhi + j * phiScale;
Vector2 suv = GetSphereUV(theta, phi, expand_coef);
uv.Add(new Vector2((suv.x - rect.x) / rect.width, (suv.y - rect.y) / rect.height));
Vector3 vert = GetSphereVert(theta, phi);
vert.x = (worldScale * vert.x - position.x) / scale.x;
vert.y = (worldScale * vert.y - position.y) / scale.y;
vert.z = (worldScale * vert.z - position.z) / scale.z;
verts.Add(vert);
}
}
for (int j = 0; j < lareplacedudes; j++)
{
for (int k = 0; k < longitudes; k++)
{
triangles.Add((j * (longitudes + 1)) + k);
triangles.Add(((j + 1) * (longitudes + 1)) + k);
triangles.Add(((j + 1) * (longitudes + 1)) + k + 1);
triangles.Add(((j + 1) * (longitudes + 1)) + k + 1);
triangles.Add((j * (longitudes + 1)) + k + 1);
triangles.Add((j * (longitudes + 1)) + k);
}
}
}
19
Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static void BuildCube(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 position, Quaternion rotation, Vector3 scale, float worldScale = 800, int subQuads = 1, float expand_coef = 1.01f)
{
position = Quaternion.Inverse(rotation) * position;
int vertsPerSide = (subQuads + 1) * (subQuads + 1);
for (int i = 0; i < (int)CubeFace.COUNT; i++)
{
for(int j = 0; j < subQuads + 1; j++)
{
for(int k = 0; k < subQuads + 1; k++)
{
float u = j / (float)subQuads;
float v = k / (float)subQuads;
uv.Add(GetCubeUV((CubeFace)i, new Vector2(u, v), expand_coef));
Vector3 vert = GetCubeVert((CubeFace)i, new Vector2(u, v), expand_coef);
vert.x = (worldScale * vert.x - position.x) / scale.x;
vert.y = (worldScale * vert.y - position.y) / scale.y;
vert.z = (worldScale * vert.z - position.z) / scale.z;
verts.Add(vert);
}
}
for(int j = 0; j < subQuads; j++)
{
for(int k = 0; k < subQuads; k++)
{
triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k);
triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k);
triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k + 1);
triangles.Add(vertsPerSide * i + ((j + 1) * (subQuads + 1)) + k + 1);
triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k);
triangles.Add(vertsPerSide * i + (j * (subQuads + 1)) + k + 1);
}
}
}
}
19
Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static void BuildQuad(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Rect rect)
{
verts.Add(new Vector3(rect.x - 0.5f, (1 - rect.y - rect.height) - 0.5f, 0));
verts.Add(new Vector3(rect.x - 0.5f, (1 - rect.y) - 0.5f, 0));
verts.Add(new Vector3(rect.x + rect.width - 0.5f, (1 - rect.y) - 0.5f, 0));
verts.Add(new Vector3(rect.x + rect.width - 0.5f, (1 - rect.y - rect.height) - 0.5f, 0));
uv.Add(new Vector2(0, 0));
uv.Add(new Vector2(0, 1));
uv.Add(new Vector2(1, 1));
uv.Add(new Vector2(1, 0));
triangles.Add(0);
triangles.Add(1);
triangles.Add(2);
triangles.Add(2);
triangles.Add(3);
triangles.Add(0);
}
19
Source : OVROverlayMeshGenerator.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static void BuildHemicylinder(List<Vector3> verts, List<Vector2> uv, List<int> triangles, Vector3 scale, Rect rect, int longitudes = 128)
{
float height = Mathf.Abs(scale.y) * rect.height;
float radius = scale.z;
float arcLength = scale.x * rect.width;
float arcAngle = arcLength / radius;
float minAngle = scale.x * (-0.5f + rect.x) / radius;
int columns = Mathf.CeilToInt(longitudes * arcAngle / (2 * Mathf.PI));
// we don't want super tall skinny triangles because that can lead to artifacting.
// make triangles no more than 2x taller than wide
float triangleWidth = arcLength / columns;
float ratio = height / triangleWidth;
int rows = Mathf.CeilToInt(ratio / 2);
for (int j = 0; j < rows + 1; j += 1)
{
for (int k = 0; k < columns + 1; k++)
{
uv.Add(new Vector2((k / (float)columns), 1 - (j / (float)rows)));
Vector3 vert = Vector3.zero;
// because the scale is used to control the parameters, we need
// to reverse multiply by scale to appear correctly
vert.x = (Mathf.Sin(minAngle + (k * arcAngle / columns)) * radius) / scale.x;
vert.y = (0.5f - rect.y - rect.height + rect.height * (1 - j / (float)rows));
vert.z = (Mathf.Cos(minAngle + (k * arcAngle / columns)) * radius) / scale.z;
verts.Add(vert);
}
}
for (int j = 0; j < rows; j++)
{
for (int k = 0; k < columns; k++)
{
triangles.Add((j * (columns + 1)) + k);
triangles.Add(((j + 1) * (columns + 1)) + k + 1);
triangles.Add(((j + 1) * (columns + 1)) + k);
triangles.Add(((j + 1) * (columns + 1)) + k + 1);
triangles.Add((j * (columns + 1)) + k);
triangles.Add((j * (columns + 1)) + k + 1);
}
}
}
19
Source : BuiltinDebugViewsComponent.cs
with MIT License
from AdultLink
with MIT License
from AdultLink
public void BuildMesh(int columns, int rows)
{
// Base shape
var arrow = new Vector3[6]
{
new Vector3(0f, 0f, 0f),
new Vector3(0f, 1f, 0f),
new Vector3(0f, 1f, 0f),
new Vector3(-1f, 1f, 0f),
new Vector3(0f, 1f, 0f),
new Vector3(1f, 1f, 0f)
};
// make the vertex array
int vcount = 6 * columns * rows;
var vertices = new List<Vector3>(vcount);
var uvs = new List<Vector2>(vcount);
for (int iy = 0; iy < rows; iy++)
{
for (int ix = 0; ix < columns; ix++)
{
var uv = new Vector2(
(0.5f + ix) / columns,
(0.5f + iy) / rows
);
for (int i = 0; i < 6; i++)
{
vertices.Add(arrow[i]);
uvs.Add(uv);
}
}
}
// make the index array
var indices = new int[vcount];
for (int i = 0; i < vcount; i++)
indices[i] = i;
// initialize the mesh object
mesh = new Mesh { hideFlags = HideFlags.DontSave };
mesh.SetVertices(vertices);
mesh.SetUVs(0, uvs);
mesh.SetIndices(indices, MeshTopology.Lines, 0);
mesh.UploadMeshData(true);
// update the properties
columnCount = columns;
rowCount = rows;
}
19
Source : BatFamiliar.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
protected override void updateAnimation(GameTime time)
{
if (followingOwner)
{
Sprite.Animate(time, 0, 4, 80f);
if (Sprite.currentFrame % 3 == 0 && Utility.isOnScreen(Position, 512) && (batFlap == null || !batFlap.IsPlaying) && Game1.soundBank != null && currentLocation == Game1.currentLocation && !cursedDoll)
{
batFlap = Game1.soundBank.GetCue("batFlap");
//batFlap.Play();
}
if (cursedDoll.Value)
{
shakeTimer -= time.ElapsedGameTime.Milliseconds;
if (shakeTimer < 0)
{
if (!hauntedSkull.Value)
{
currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, 103, 16, 16), position + new Vector2(0f, -32f), false, 0.1f, new Color(255, 50, 255) * 0.8f)
{
scale = 4f
});
}
shakeTimer = 50;
}
previousPositions.Add(Position);
if (previousPositions.Count > 8)
{
previousPositions.RemoveAt(0);
}
}
}
else
{
Sprite.currentFrame = 4;
Halt();
}
resetAnimationSpeed();
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static int GetGroupSetOffset(OverlaidDictionary objects, int x, int y)
{
Dictionary<int, List<Vector2>> offsets = new Dictionary<int, List<Vector2>>();
GetSurroundingOffsets(objects, new List<Vector2>(), offsets, new Vector2(x, y));
int offset = 0;
int count = 0;
int dCount = 0;
string debug = "";
if(!check.Contains(new Vector2(x, y)) && offsets.Count > 1)
{
check.Add(new Vector2(x, y));
debug += $"multi: {x},{y}'s group has {offsets.Count} different sets";
}
foreach (var k in offsets.Keys)
{
dCount += offsets[k].Count;
if(debug != "")
{
debug += $"\noffset {k}: {string.Join(" | ", offsets[k])}";
}
if (offsets[k].Count > count || (offsets[k].Count == count && k > offset))
{
count = offsets[k].Count;
offset = k;
}
}
if(debug != "")
{
debug += $"\nfinal offset: {offset}, pieces: {dCount}";
SMonitor.Log(debug);
}
return offset;
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void GetSurroundingOffsets(OverlaidDictionary objects, List<Vector2> tiles, Dictionary<int, List<Vector2>> offsets, Vector2 tile)
{
if (!tiles.Contains(tile))
tiles.Add(tile);
int offset = GetSetOffset(objects[tile].parentSheetIndex);
if (!offsets.ContainsKey(offset))
offsets.Add(offset, new List<Vector2>() { tile });
else
offsets[offset].Add(tile);
if(!tiles.Contains(tile + new Vector2(-1, 0)) && IsRock(objects, (int)tile.X - 1, (int)tile.Y))
GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(-1, 0));
if(!tiles.Contains(tile + new Vector2(1, 0)) && IsRock(objects, (int)tile.X + 1, (int)tile.Y))
GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(1, 0));
if(!tiles.Contains(tile + new Vector2(0, -1)) && IsRock(objects, (int)tile.X, (int)tile.Y - 1))
GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(0, -1));
if(!tiles.Contains(tile + new Vector2(0, 1)) && IsRock(objects, (int)tile.X, (int)tile.Y + 1))
GetSurroundingOffsets(objects, tiles, offsets, tile + new Vector2(0, 1));
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private Vector2 GetLandSpawnPos(GameLocation location)
{
List<Vector2> tiles = new List<Vector2>();
if (location is MineShaft)
{
for (int x2 = 0; x2 < location.map.Layers[0].LayerWidth; x2++)
{
for (int y2 = 0; y2 < location.map.Layers[0].LayerHeight; y2++)
{
Tile t = location.map.Layers[0].Tiles[x2, y2];
if (t != null)
{
Vector2 tile2 = new Vector2((float)x2, (float)y2);
int m = t.TileIndex;
if ((location as MineShaft).isTileClearForMineObjects(tile2))
{
tiles.Add(tile2);
}
}
}
}
}
else
{
for (int x2 = (int)Math.Round(location.map.Layers[0].LayerWidth *0.1f); x2 < (int)Math.Round(location.map.Layers[0].LayerWidth * 0.9f); x2++)
{
for (int y2 = (int)Math.Round(location.map.Layers[0].LayerHeight * 0.1f); y2 < (int)Math.Round(location.map.Layers[0].LayerHeight * 0.9f); y2++)
{
Layer l = location.map.GetLayer("Paths");
if (l != null)
{
Tile t = l.Tiles[x2, y2];
if (t != null)
{
Vector2 tile2 = new Vector2((float)x2, (float)y2);
if (location.isTileLocationTotallyClearAndPlaceable(tile2))
{
tiles.Add(tile2);
}
}
}
if(tiles.Count == 0)
{
Tile t = location.map.Layers[0].Tiles[x2, y2];
if (t != null)
{
Vector2 tile2 = new Vector2((float)x2, (float)y2);
if (location.isTilePreplacedable(new Location((int)tile2.X, (int)tile2.Y),Game1.viewport))
{
tiles.Add(tile2);
}
}
}
}
}
}
if(tiles.Count == 0)
{
return Vector2.Zero;
}
Vector2 posT = tiles[Game1.random.Next(0,tiles.Count)];
return new Vector2(posT.X * 64f, posT.Y * 64f);
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private IOrderedEnumerable<Vector2> GetOpenSpots()
{
Farm farm = Game1.getFarm();
List<Vector2> clearSpots = new List<Vector2>();
for (int x = 0; x < farm.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < farm.map.Layers[0].LayerHeight; y++)
{
Tile tile = farm.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (Vector2.Distance(Game1.player.getTileLocation(), new Vector2(x, y)) < Config.MaxDistanceSpawn && tile != null && farm.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && farm.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !farm.waterTiles[x,y] && !farm.objects.ContainsKey(new Vector2(x, y)))
{
clearSpots.Add(new Vector2(x, y));
}
}
}
return clearSpots.OrderBy(s => Game1.random.NextDouble());
}
19
Source : Utils.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
internal static void CreateIslesMap(GameLocation location)
{
location.loadMap(ModEntry.mapreplacedetKey, true);
TileSheet sheet = location.map.TileSheets[0];
int isles = Game1.random.Next(1, Math.Max(1, Config.MaxIsles) + 1);
List<Point> points = new List<Point>();
double coeff = Math.Sqrt(mapWidth * mapHeight / (float) isles / 144f);
Monitor.Log($"making {isles} isles, max {coeff * 16}x{coeff * 9}");
Rectangle bounds = new Rectangle((int)(coeff * 16 / 8f), (int)(coeff * 9 / 8f), mapWidth - (int)(coeff * 16 / 4f), mapHeight - (int)(coeff * 9 / 4f));
// prefill with ocean tiles
for (int y = 0; y < mapHeight; y++)
{
for (int x = 0; x < mapWidth; x++)
{
Point p = new Point(x, y);
if (bounds.Contains(p))
points.Add(p);
location.map.GetLayer("Back").Tiles[x, y] = new StaticTile(location.map.GetLayer("Back"), sheet, BlendMode.Alpha, GetRandomOceanTile());
}
}
Monitor.Log($"got {points.Count} points");
// determine island no and sizes, positions
List<Rectangle> isleBoxes = new List<Rectangle>();
for (int i = 0; i < isles; i++)
{
List<Point> freePoints = new List<Point>();
int width = Game1.random.Next((int)(coeff * 16 / 2f), (int)(coeff * 16 * 3 / 4f));
int height = Game1.random.Next((int)(coeff * 9 / 2f), (int)(coeff * 9 * 3 / 4f));
Monitor.Log($"trying to make island of size {width}x{height}");
Rectangle bounds2 = new Rectangle(width / 2, height / 2, mapWidth - width, mapHeight - height);
for (int j = points.Count - 1; j >= 0; j--)
{
if (bounds2.Contains(points[j]))
{
Rectangle testRect = new Rectangle(points[j].X - width /2, points[j].Y - height /2, width, height);
bool free = true;
foreach(Rectangle r in isleBoxes)
{
if (r.Intersects(testRect))
{
free = false;
break;
}
}
if (free)
{
freePoints.Add(points[j]);
}
}
}
if (!freePoints.Any())
continue;
Point randPoint = freePoints[Game1.random.Next(freePoints.Count)];
Rectangle isleBox = new Rectangle(randPoint.X - width / 2, randPoint.Y - height / 2, width, height);
isleBoxes.Add(isleBox);
}
Monitor.Log($"got {isleBoxes.Count} island boxes");
// build islands
foreach (Rectangle isleBox in isleBoxes)
{
// preset each tile to land
bool[] landTiles = new bool[isleBox.Width * isleBox.Height];
for (int i = 0; i < isleBox.Width * isleBox.Height; i++)
landTiles[i] = true;
// randomly shape island
for (int x = 0; x < isleBox.Width; x++)
{
for (int y = 0; y < isleBox.Height; y++)
{
int idx = y * isleBox.Width + x;
double land = 1;
if(x == 0 || x == isleBox.Width - 1 || y == 0 || y == isleBox.Height - 1)
{
landTiles[idx] = false;
continue;
}
float widthOffset = Math.Abs(isleBox.Width / 2f - x) / (isleBox.Width / 2f);
float heightOffset = Math.Abs(isleBox.Height / 2f - y) / (isleBox.Height / 2f);
double distance = Math.Sqrt(Math.Pow(widthOffset, 2) + Math.Pow(heightOffset, 2));
if (idx > 0 && !landTiles[idx - 1])
land -= 0.1;
if (idx > isleBox.Width - 1 && !landTiles[idx - isleBox.Width])
land -= 0.1;
if (idx < landTiles.Length - 1 && !landTiles[idx + 1])
land -= 0.1;
if (idx < landTiles.Length - isleBox.Width - 1 && !landTiles[idx + isleBox.Width])
land -= 0.1;
land -= distance;
landTiles[idx] = Game1.random.NextDouble() < land;
}
}
// smoothen
bool changed = true;
while (changed)
{
changed = false;
for (int x = 0; x < isleBox.Width; x++)
{
for (int y = 0; y < isleBox.Height; y++)
{
int idx = y * isleBox.Width + x;
if (!landTiles[idx])
{
bool[] surround = GetSurroundingTiles(isleBox, landTiles, idx);
if ((surround[0] && surround[7]) || (surround[2] && surround[5])
|| (surround[1] && (surround[5] || surround[6] || surround[7]))
|| (surround[3] && (surround[2] || surround[4] || surround[7]))
|| (surround[4] && (surround[0] || surround[3] || surround[5]))
|| (surround[6] && (surround[0] || surround[1] || surround[2]))
)
{
if(Game1.random.NextDouble() < 0.85)
{
landTiles[idx] = true;
}
else
{
landTiles[idx - 1 - isleBox.Width] = false;
landTiles[idx - isleBox.Width] = false;
landTiles[idx + 1 - isleBox.Width] = false;
landTiles[idx - 1] = false;
landTiles[idx + 1] = false;
landTiles[idx - 1 + isleBox.Width] = false;
landTiles[idx + isleBox.Width] = false;
landTiles[idx + 1 + isleBox.Width] = false;
}
changed = true;
}
}
}
}
}
// add land and border tiles
for (int x = 0; x < isleBox.Width; x++)
{
for (int y = 0; y < isleBox.Height; y++)
{
int idx = y * isleBox.Width + x;
bool[] surround = GetSurroundingTiles(isleBox, landTiles, idx);
if (landTiles[idx])
{
if(surround.Where(b => b).Count() == 8)
{
location.map.GetLayer("Back").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Back"), sheet, BlendMode.Alpha, GetRandomLandTile());
}
else
{
if (!surround[1])
{
if (!surround[3])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 51);
}
else if (!surround[4])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 54);
}
else if(location.map.GetLayer("Buildings").Tiles[isleBox.X + x - 1, isleBox.Y + y]?.TileIndex == 52)
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 53);
}
else
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 52);
}
}
else if (!surround[6])
{
if (!surround[3])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 51);
}
else if (!surround[4])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 54);
}
else if(location.map.GetLayer("Buildings").Tiles[isleBox.X + x - 1, isleBox.Y + y]?.TileIndex == 52)
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 53);
}
else
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 52);
}
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties.Add("@Flip", 2);
}
else if (!surround[3])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 68);
}
else if (!surround[4])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 71);
}
else if (!surround[0])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 70);
}
else if (!surround[2])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 69);
}
else if (!surround[5])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 87);
}
else if (!surround[7])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = new StaticTile(location.map.GetLayer("Buildings"), sheet, BlendMode.Alpha, 86);
}
}
}
else
{
if(surround.Where(b => b).Any())
{
if (surround[1])
{
if (surround[3])
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 226);
else if (surround[4])
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 175);
else
{
if (location.map.GetLayer("Buildings").Tiles[isleBox.X + x - 1, isleBox.Y + y]?.TileIndex == 141)
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 158);
else
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 141);
}
}
else if (surround[6])
{
if (surround[3])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 226);
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties.Add("@Flip", 2);
}
else if (surround[4])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 175);
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties.Add("@Flip", 2);
}
else
{
if (location.map.GetLayer("Buildings").Tiles[isleBox.X + x - 1, isleBox.Y + y]?.TileIndex == 141)
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 158);
else
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 141);
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties.Add("@Flip", 2);
}
}
else if (surround[3])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 260);
}
else if (surround[4])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 209);
}
else if (surround[0])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 243);
}
else if (surround[2])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 192);
}
else if (surround[5])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 243);
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties.Add("@Flip", 2);
}
else if (surround[7])
{
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y] = CreateAnimatedTile(location, sheet, 192);
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties.Add("@Flip", 2);
}
location.map.GetLayer("Buildings").Tiles[isleBox.X + x, isleBox.Y + y].Properties["Preplacedable"] = "T";
//location.map.GetLayer("Back").Tiles[isleBox.X + x, isleBox.Y + y].TileIndexProperties["NPCBarrier"] = "t";
}
}
}
}
}
// add water tiles
location.waterTiles = new bool[location.map.Layers[0].LayerWidth, location.map.Layers[0].LayerHeight];
bool foundAnyWater = false;
for (int x = 0; x < location.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < location.map.Layers[0].LayerHeight; y++)
{
if (location.doesTileHaveProperty(x, y, "Water", "Back") != null)
{
foundAnyWater = true;
location.waterTiles[x, y] = true;
}
}
}
if (!foundAnyWater)
{
location.waterTiles = null;
}
// add terrain features
foreach (Rectangle isleBox in isleBoxes)
{
// get free spots
List<Vector2> freeSpots = new List<Vector2>();
List<Vector2> freeCenters = new List<Vector2>();
for (int x = isleBox.X; x < isleBox.Right; x++)
{
for (int y = isleBox.Y; y < isleBox.Bottom; y++)
{
if (location.doesTileHaveProperty(x, y, "Water", "Back") == null)
{
freeSpots.Add(new Vector2(x, y));
if (
location.doesTileHaveProperty(x - 1, y - 1, "Water", "Back") == null
&& location.doesTileHaveProperty(x, y - 1, "Water", "Back") == null
&& location.doesTileHaveProperty(x + 1, y - 1, "Water", "Back") == null
&& location.doesTileHaveProperty(x - 1, y, "Water", "Back") == null
&& location.doesTileHaveProperty(x + 1, y, "Water", "Back") == null
&& location.doesTileHaveProperty(x - 1, y + 1, "Water", "Back") == null
&& location.doesTileHaveProperty(x, y + 1, "Water", "Back") == null
&& location.doesTileHaveProperty(x + 1, y + 1, "Water", "Back") == null
)
{
freeCenters.Add(new Vector2(x, y));
}
}
}
}
Monitor.Log($"Island has {freeSpots.Count} free spots, {freeCenters.Count} centers");
List<Vector2> randFreeSpots = new List<Vector2>(freeSpots);
int n = randFreeSpots.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = randFreeSpots[k];
randFreeSpots[k] = randFreeSpots[n];
randFreeSpots[n] = value;
}
List<Vector2> randFreeCenters = new List<Vector2>(freeCenters);
n = randFreeCenters.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = randFreeCenters[k];
randFreeCenters[k] = randFreeCenters[n];
randFreeCenters[n] = value;
}
int taken = 0;
if (Game1.random.NextDouble() < Config.TreasureChance)
{
Monitor.Log($"Island has treasure chest");
location.overlayObjects[randFreeSpots[taken]] = new Chest(0, new List<Item>() { MineShaft.getTreasureRoomItem() }, randFreeSpots[taken], false, 0);
taken++;
}
if (Game1.random.NextDouble() < Config.TreesChance)
{
Monitor.Log($"Island has trees");
int trees = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.TreesPortion)));
for (int i = 0; i < trees; i++)
{
location.terrainFeatures.Add(randFreeSpots[i + taken], new Tree(6, 5));
}
taken += trees;
if (Game1.random.NextDouble() < Config.CoconutChance)
{
Monitor.Log($"Island has coconuts");
int nuts = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.CoconutPortion)));
for (int i = 0; i < nuts; i++)
{
Vector2 position = randFreeSpots[i + taken];
location.dropObject(new Object(88, 1, false, -1, 0), position * 64f, Game1.viewport, true, null);
}
taken += nuts;
}
}
if (Game1.random.NextDouble() < Config.FaunaChance)
{
Monitor.Log($"Island has fauna");
int fauna = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.FaunaPortion)));
for (int i = 0; i < fauna; i++)
{
Vector2 position = randFreeSpots[i + taken];
int index = 393;
if (Game1.random.NextDouble() < 0.2)
{
index = 397;
}
else if (Game1.random.NextDouble() < 0.1)
{
index = 152;
}
location.dropObject(new Object(index, 1, false, -1, 0), position * 64f, Game1.viewport, true, null);
}
taken += fauna;
}
if (Game1.random.NextDouble() < Config.ArtifactChance)
{
Monitor.Log($"Island has artifacts");
int artifacts = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.ArtifactPortion)));
for (int i = 0; i < artifacts; i++)
{
Vector2 position = randFreeSpots[i + taken];
location.objects.Add(position, new Object(position, 590, 1));
}
taken += artifacts;
}
if (Game1.random.NextDouble() < Config.MonsterChance)
{
int monsters = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.MonsterPortion)));
double type = Game1.random.NextDouble();
if (type < 0.2)
{
Monitor.Log($"Island has skeletons");
}
else if (type < 0.3)
{
Monitor.Log($"Island has dinos");
}
else if (type < 0.5)
{
Monitor.Log($"Island has golems");
}
else
{
Monitor.Log($"Island has crabs");
}
for (int i = 0; i < monsters; i++)
{
Vector2 position = randFreeSpots[i + taken];
if (type < 0.2)
{
location.characters.Add(new Skeleton(position * Game1.tileSize));
}
else if (type < 0.3)
{
location.characters.Add(new DinoMonster(position * Game1.tileSize));
}
else if (type < 0.5)
{
location.characters.Add(new RockGolem(position * Game1.tileSize, 10));
}
else
{
location.characters.Add(new RockCrab(position * Game1.tileSize));
}
}
taken += monsters;
}
if (Game1.random.NextDouble() < Config.GrreplacedChance)
{
Monitor.Log($"Island has grreplaced");
int grreplaced = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.GrreplacedPortion)));
for (int i = 0; i < grreplaced; i++)
{
location.terrainFeatures.Add(randFreeSpots[i + taken], new Grreplaced(Game1.random.Next(2, 5), Game1.random.Next(1, 3)));
}
taken += grreplaced;
}
if (Game1.random.NextDouble() < Config.MineralChance)
{
Monitor.Log($"Island has minerals");
int minerals = Math.Min(freeSpots.Count - taken, (int)(freeSpots.Count * Math.Min(1, Config.MineralPortion)));
for (int i = 0; i < minerals; i++)
{
Vector2 position = randFreeSpots[i + taken];
if (Game1.random.NextDouble() < 0.06)
{
location.terrainFeatures.Add(position, new Tree(1 + Game1.random.Next(2), 1));
}
else if (Game1.random.NextDouble() < 0.02)
{
if (Game1.random.NextDouble() < 0.1)
{
location.objects.Add(position, new Object(position, 46, "Stone", true, false, false, false)
{
MinutesUntilReady = 12
});
}
else
{
location.objects.Add(position, new Object(position, (Game1.random.Next(7) + 1) * 2, "Stone", true, false, false, false)
{
MinutesUntilReady = 5
});
}
}
else if (Game1.random.NextDouble() < 0.1)
{
if (Game1.random.NextDouble() < 0.001)
{
location.objects.Add(position, new Object(position, 765, 1)
{
MinutesUntilReady = 16
});
}
else if (Game1.random.NextDouble() < 0.1)
{
location.objects.Add(position, new Object(position, 764, 1)
{
MinutesUntilReady = 8
});
}
else if (Game1.random.NextDouble() < 0.33)
{
location.objects.Add(position, new Object(position, 290, 1)
{
MinutesUntilReady = 5
});
}
else
{
location.objects.Add(position, new Object(position, 751, 1)
{
MinutesUntilReady = 3
});
}
}
else
{
Object obj = new Object(position, (Game1.random.NextDouble() < 0.25) ? 32 : ((Game1.random.NextDouble() < 0.33) ? 38 : ((Game1.random.NextDouble() < 0.5) ? 40 : 42)), 1);
obj.minutesUntilReady.Value = 2;
obj.Name = "Stone";
location.objects.Add(position, obj);
}
}
taken += minerals;
}
}
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static void ResetPetBowlLocation(Farm farm, Vector2 exception)
{
List<Vector2> potentialBowls = new List<Vector2>();
foreach (KeyValuePair<Vector2, Object> kvp in farm.objects.Pairs)
{
if (kvp.Value.Name.EndsWith("Pet Bowl") && kvp.Key != exception)
{
potentialBowls.Add(kvp.Key);
}
}
if (potentialBowls.Any())
{
Vector2 bowlLoc = potentialBowls[Game1.random.Next(potentialBowls.Count)];
farm.petBowlPosition.Value = Utility.Vector2ToPoint(bowlLoc);
PMonitor.Log($"Set pet bowl location to {bowlLoc}");
return;
}
PMonitor.Log("No pet bowl on farm, setting default", LogLevel.Debug);
Layer back_layer = farm.map.GetLayer("Back");
for (int x = 0; x < back_layer.LayerWidth; x++)
{
for (int y = 0; y < back_layer.LayerHeight; y++)
{
if (back_layer.Tiles[x, y] != null && back_layer.Tiles[x, y].TileIndex == 1938)
{
farm.petBowlPosition.Set(x, y);
PMonitor.Log($"Set pet bowl position to {x}, {y}", LogLevel.Debug);
return;
}
}
}
}
19
Source : SwimUtils.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static List<Vector2> GetTilesInDirection(int count)
{
List<Vector2> tiles = new List<Vector2>();
int dir = Game1.player.facingDirection;
if (dir == 1)
{
for (int i = count; i > 0; i--)
{
tiles.Add(Game1.player.getTileLocation() + new Vector2(i, 0));
}
}
if (dir == 2)
{
for (int i = count; i > 0; i--)
{
tiles.Add(Game1.player.getTileLocation() + new Vector2(0, i));
}
}
if (dir == 3)
{
for (int i = count; i > 0; i--)
{
tiles.Add(Game1.player.getTileLocation() - new Vector2(i, 0));
}
}
if (dir == 0)
{
for (int i = count; i > 0; i--)
{
tiles.Add(Game1.player.getTileLocation() - new Vector2(0, i));
}
}
return tiles;
}
19
Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void AddMinerals(GameLocation l)
{
List<Vector2> spots = new List<Vector2>();
for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
{
Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null)
{
spots.Add(new Vector2(x, y));
}
}
}
int n = spots.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = spots[k];
spots[k] = spots[n];
spots[n] = value;
}
int mineralNo = (int)Math.Round(Game1.random.Next(Config.MineralPerThousandMin, Config.MineralPerThousandMax) / 1000f * spots.Count);
List<Vector2> mineralSpots = spots.Take(mineralNo).ToList();
foreach (Vector2 tile in mineralSpots)
{
double chance = Game1.random.NextDouble();
if (chance < 0.2 && !l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.ContainsKey("Treasure") && !l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.ContainsKey("Diggable"))
{
l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].TileIndex = 1299;
l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.Add("Treasure", new PropertyValue("Object " + SwimUtils.CheckForBuriedItem(Game1.player)));
l.map.GetLayer("Back").Tiles[(int)tile.X, (int)tile.Y].Properties.Add("Diggable", new PropertyValue("T"));
}
else if (chance < 0.4)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 751, "Stone", true, false, false, false)
{
MinutesUntilReady = 2
};
}
else if (chance < 0.5)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 290, "Stone", true, false, false, false)
{
MinutesUntilReady = 4
};
}
else if (chance < 0.55)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 764, "Stone", true, false, false, false)
{
MinutesUntilReady = 8
};
}
else if (chance < 0.56)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 765, "Stone", true, false, false, false)
{
MinutesUntilReady = 16
};
}
else if (chance < 0.65)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 80, "Stone", true, true, false, true);
}
else if (chance < 0.74)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 82, "Stone", true, true, false, true);
}
else if (chance < 0.83)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 84, "Stone", true, true, false, true);
}
else if (chance < 0.90)
{
l.overlayObjects[tile] = new StardewValley.Object(tile, 86, "Stone", true, true, false, true);
}
else
{
int[] gems = { 4,6,8,10,12,14,40 };
int whichGem = gems[Game1.random.Next(gems.Length)];
l.overlayObjects[tile] = new StardewValley.Object(tile, whichGem, "Stone", true, false, false, false)
{
MinutesUntilReady = 5
};
}
}
}
19
Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void AddFishies(GameLocation l, bool smol = true)
{
if (Config.AddFishies)
{
List<Vector2> spots = new List<Vector2>();
for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
{
Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
{
spots.Add(new Vector2(x, y));
}
}
}
if(spots.Count == 0)
{
Monitor.Log($"No spots for fishies in map {l.Name}", LogLevel.Warn);
return;
}
int n = spots.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = spots[k];
spots[k] = spots[n];
spots[n] = value;
}
if (smol)
{
int fishes = Game1.random.Next(Config.MinSmolFishies, Config.MaxSmolFishies);
for (int i = 0; i < fishes; i++)
{
int idx = Game1.random.Next(spots.Count);
l.characters.Add(new Fishie(new Vector2(spots[idx].X * Game1.tileSize, spots[idx].Y * Game1.tileSize)));
}
}
else
{
int bigFishes = (int)(Game1.random.Next(Config.BigFishiesPerThousandMin, Config.BigFishiesPerThousandMax) / 1000f * spots.Count);
for (int i = 0; i < bigFishes; i++)
{
int idx = Game1.random.Next(spots.Count);
l.characters.Add(new BigFishie(new Vector2(spots[idx].X * Game1.tileSize, spots[idx].Y * Game1.tileSize)));
}
}
}
}
19
Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void AddOceanForage(GameLocation l)
{
List<Vector2> spots = new List<Vector2>();
for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
{
Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
{
spots.Add(new Vector2(x, y));
}
}
}
int n = spots.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = spots[k];
spots[k] = spots[n];
spots[n] = value;
}
int forageNo = (int)(Game1.random.Next(Config.OceanForagePerThousandMin, Config.OceanForagePerThousandMax) / 1000f * spots.Count);
List<Vector2> forageSpots = spots.Take(forageNo).ToList();
foreach (Vector2 v in forageSpots)
{
double chance = Game1.random.NextDouble();
if (chance < 0.25)
{
l.overlayObjects[v] = new StardewValley.Object(v, 152, "Seaweed", true, true, false, true)
{
CanBeGrabbed = true
};
}
else if (chance < 0.4)
{
l.overlayObjects[v] = new StardewValley.Object(v, 153, "Green Algae", true, true, false, true)
{
CanBeGrabbed = true
};
}
else if (chance < 0.6)
{
l.overlayObjects[v] = new StardewValley.Object(v, 157, "White Algae", true, true, false, true)
{
CanBeGrabbed = true
};
}
else if (chance < 0.75)
{
l.overlayObjects[v] = new StardewValley.Object(v, 372, "Clam", true, true, false, true)
{
CanBeGrabbed = true
};
}
else if (chance < 0.85)
{
l.overlayObjects[v] = new StardewValley.Object(v, 393, "Coral", true, true, false, true)
{
CanBeGrabbed = true
};
}
else if (chance < 0.94)
{
l.overlayObjects[v] = new StardewValley.Object(v, 397, "Sea Urchin", true, true, false, true)
{
CanBeGrabbed = true
};
}
else if (chance < 0.97)
{
l.overlayObjects[v] = new StardewValley.Object(v, 394, "Rainbow Shell", true, true, false, true)
{
CanBeGrabbed = true
};
}
else
{
l.overlayObjects[v] = new StardewValley.Object(v, 392, "Nautilus Shell", true, true, false, true)
{
CanBeGrabbed = true
};
}
}
}
19
Source : SkullBoss.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
protected override void updateAnimation(GameTime time)
{
if (base.focusedOnFarmers || this.withinPlayerThreshold(20) || this.seenPlayer)
{
this.Sprite.Animate(time, 0, 4, 80f);
this.shakeTimer -= time.ElapsedGameTime.Milliseconds;
if (this.shakeTimer < 0)
{
base.currentLocation.temporarySprites.Add(new TemporaryAnimatedSprite("Maps\\springobjects", Game1.getSourceRectForStandardTileSheet(Game1.objectSpriteSheet, 103, width, height), this.position + new Vector2(0f, -32f), false, 0.1f, new Color(255, 50, 255) * 0.8f)
{
scale = 4f
});
this.shakeTimer = 50;
}
this.previousPositions.Add(base.Position);
if (this.previousPositions.Count > 8)
{
this.previousPositions.RemoveAt(0);
}
}
base.resetAnimationSpeed();
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private void GameLoop_DayStarted(object sender, StardewModdingAPI.Events.DayStartedEventArgs e)
{
if (!config.EnableMod || coinDataDict.Count == 0)
return;
coinLocationDict.Clear();
foreach (GameLocation gl in Game1.locations)
{
if (gl.IsOutdoors && Game1.random.NextDouble() < config.MapHasCoinsChance)
{
int coins = Game1.random.Next(config.MinCoinsPerMap, config.MaxCoinsPerMap + 1 + (int)Math.Round(Game1.player.LuckLevel * config.LuckFactor));
if (coins == 0)
continue;
List<Vector2> diggableTiles = new List<Vector2>();
for (int x = 0; x < gl.map.GetLayer("Back").LayerWidth; x++)
{
for (int y = 0; y < gl.map.GetLayer("Back").LayerHeight; y++)
{
if (gl.doesTileHaveProperty(x, y, "Diggable", "Back") != null && !gl.isTileOccupied(new Vector2(x, y), "", false) && gl.isTilePreplacedable(new Location(x, y), Game1.viewport))
diggableTiles.Add(new Vector2(x, y));
}
}
if (diggableTiles.Count == 0)
continue;
Monitor.Log($"Adding coins to {gl.Name}");
if (!coinLocationDict.ContainsKey(gl.Name))
{
coinLocationDict.Add(gl.Name, new Dictionary<Vector2, string>());
}
for(int i = 0; i < coins; i++)
{
double whichRarity = Game1.random.NextDouble() * totalRarities;
float rarities = 0;
foreach (var coin in coinDataDict.Values)
{
rarities += coin.rarity;
if(whichRarity < rarities)
{
int idx = Game1.random.Next(diggableTiles.Count);
coinLocationDict[gl.Name][diggableTiles[idx]] = coin.id;
Monitor.Log($"Added coin {coin.id} to {gl.Name} at {diggableTiles[idx]}");
diggableTiles.RemoveAt(idx);
break;
}
}
if (diggableTiles.Count == 0)
break;
}
}
}
}
19
Source : Utils.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
internal static List<Vector2> GetSurroundingTiles(Vector2 spot, int radius, bool skipCenter = false)
{
List<Vector2> spots = new List<Vector2>();
int diam = radius * 2 + 1;
for (int x = 0; x < diam; x++)
{
for (int y = 0; y < diam; y++)
{
if (!skipCenter || x != radius || y != radius)
spots.Add(new Vector2((int)spot.X - radius + x, (int)spot.Y - radius + y));
}
}
return spots;
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private static bool recursiveTryToCreateLadderDown(MineShaft location, Vector2 centerTile, string sound, int maxIterations)
{
int iterations = 0;
Queue<Vector2> positionsToCheck = new Queue<Vector2>();
positionsToCheck.Enqueue(centerTile);
List<Vector2> closedList = new List<Vector2>();
while (iterations < maxIterations && positionsToCheck.Count > 0)
{
Vector2 currentPoint = positionsToCheck.Dequeue();
closedList.Add(currentPoint);
if (!location.isTileOccupied(currentPoint, "ignoreMe", false) && location.isTileOnClearAndSolidGround(currentPoint) && location.isTileOccupiedByFarmer(currentPoint) == null && location.doesTileHaveProperty((int)currentPoint.X, (int)currentPoint.Y, "Type", "Back") != null && location.doesTileHaveProperty((int)currentPoint.X, (int)currentPoint.Y, "Type", "Back").Equals("Stone"))
{
location.playSound("hoeHit", NetAudio.SoundContext.Default);
location.createLadderDown((int)currentPoint.X, (int)currentPoint.Y, true);
return true;
}
foreach (Vector2 v in Utility.DirectionsTileVectors)
{
if (!closedList.Contains(currentPoint + v))
{
positionsToCheck.Enqueue(currentPoint + v);
}
}
iterations++;
}
return false;
}
19
Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void AddCrabs(GameLocation l)
{
if (Config.AddCrabs)
{
List<Vector2> spots = new List<Vector2>();
for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
{
Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
{
spots.Add(new Vector2(x, y));
}
}
}
int n = spots.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = spots[k];
spots[k] = spots[n];
spots[n] = value;
}
int crabs = (int)(Game1.random.Next(Config.CrabsPerThousandMin, Config.CrabsPerThousandMax) / 1000f * spots.Count);
for (int i = 0; i < crabs; i++)
{
int idx = Game1.random.Next(spots.Count);
l.characters.Add(new SeaCrab(new Vector2(spots[idx].X * Game1.tileSize, spots[idx].Y * Game1.tileSize)));
}
}
}
19
Source : SwimMaps.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void AddOceanTreasure(GameLocation l)
{
List<Vector2> spots = new List<Vector2>();
for (int x = 0; x < l.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < l.map.Layers[0].LayerHeight; y++)
{
Tile tile = l.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (tile != null && l.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && l.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null && !l.overlayObjects.ContainsKey(new Vector2(x, y)))
{
spots.Add(new Vector2(x, y));
}
}
}
int n = spots.Count;
while (n > 1)
{
n--;
int k = Game1.random.Next(n + 1);
var value = spots[k];
spots[k] = spots[n];
spots[n] = value;
}
int treasureNo = (int)(Game1.random.Next(Config.MinOceanChests, Config.MaxOceanChests));
List<Vector2> treasureSpots = new List<Vector2>(spots).Take(treasureNo).ToList();
foreach (Vector2 v in treasureSpots)
{
List<Item> treasures = new List<Item>();
float chance = 1f;
while (Game1.random.NextDouble() <= (double)chance)
{
chance *= 0.4f;
if (Game1.random.NextDouble() < 0.5)
{
treasures.Add(new StardewValley.Object(774, 2 + ((Game1.random.NextDouble() < 0.25) ? 2 : 0), false, -1, 0));
}
switch (Game1.random.Next(4))
{
case 0:
if (Game1.random.NextDouble() < 0.03)
{
treasures.Add(new StardewValley.Object(386, Game1.random.Next(1, 3), false, -1, 0));
}
else
{
List<int> possibles = new List<int>();
possibles.Add(384);
if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
{
possibles.Add(380);
}
if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
{
possibles.Add(378);
}
if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
{
possibles.Add(388);
}
if (possibles.Count == 0 || Game1.random.NextDouble() < 0.6)
{
possibles.Add(390);
}
possibles.Add(382);
treasures.Add(new StardewValley.Object(possibles.ElementAt(Game1.random.Next(possibles.Count)), Game1.random.Next(2, 7) * ((Game1.random.NextDouble() < 0.05 + (double)Game1.player.luckLevel.Value * 0.015) ? 2 : 1), false, -1, 0));
if (Game1.random.NextDouble() < 0.05 + (double)Game1.player.LuckLevel * 0.03)
{
treasures.Last<Item>().Stack *= 2;
}
}
break;
case 1:
if (Game1.random.NextDouble() < 0.1)
{
treasures.Add(new StardewValley.Object(687, 1, false, -1, 0));
}
else if (Game1.random.NextDouble() < 0.25 && Game1.player.craftingRecipes.ContainsKey("Wild Bait"))
{
treasures.Add(new StardewValley.Object(774, 5 + ((Game1.random.NextDouble() < 0.25) ? 5 : 0), false, -1, 0));
}
else
{
treasures.Add(new StardewValley.Object(685, 10, false, -1, 0));
}
break;
case 2:
if (Game1.random.NextDouble() < 0.1 && Game1.netWorldState.Value.LostBooksFound.Value < 21 && Game1.player.hasOrWillReceiveMail("lostBookFound"))
{
treasures.Add(new StardewValley.Object(102, 1, false, -1, 0));
}
else if (Game1.player.archaeologyFound.Count() > 0)
{
if (Game1.random.NextDouble() < 0.25)
{
treasures.Add(new StardewValley.Object(Game1.random.Next(585, 588), 1, false, -1, 0));
}
else if (Game1.random.NextDouble() < 0.5)
{
treasures.Add(new StardewValley.Object(Game1.random.Next(103, 120), 1, false, -1, 0));
}
else
{
treasures.Add(new StardewValley.Object(535, 1, false, -1, 0));
}
}
else
{
treasures.Add(new StardewValley.Object(382, Game1.random.Next(1, 3), false, -1, 0));
}
break;
case 3:
switch (Game1.random.Next(3))
{
case 0:
switch (Game1.random.Next(3))
{
case 0:
treasures.Add(new StardewValley.Object(537 + ((Game1.random.NextDouble() < 0.4) ? Game1.random.Next(-2, 0) : 0), Game1.random.Next(1, 4), false, -1, 0));
break;
case 1:
treasures.Add(new StardewValley.Object(536 + ((Game1.random.NextDouble() < 0.4) ? -1 : 0), Game1.random.Next(1, 4), false, -1, 0));
break;
case 2:
treasures.Add(new StardewValley.Object(535, Game1.random.Next(1, 4), false, -1, 0));
break;
}
if (Game1.random.NextDouble() < 0.05 + (double)Game1.player.LuckLevel * 0.03)
{
treasures.Last<Item>().Stack *= 2;
}
break;
case 1:
switch (Game1.random.Next(4))
{
case 0:
treasures.Add(new StardewValley.Object(382, Game1.random.Next(1, 4), false, -1, 0));
break;
case 1:
treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 82 : ((Game1.random.NextDouble() < 0.5) ? 64 : 60), Game1.random.Next(1, 3), false, -1, 0));
break;
case 2:
treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 84 : ((Game1.random.NextDouble() < 0.5) ? 70 : 62), Game1.random.Next(1, 3), false, -1, 0));
break;
case 3:
treasures.Add(new StardewValley.Object((Game1.random.NextDouble() < 0.3) ? 86 : ((Game1.random.NextDouble() < 0.5) ? 66 : 68), Game1.random.Next(1, 3), false, -1, 0));
break;
}
if (Game1.random.NextDouble() < 0.05)
{
treasures.Add(new StardewValley.Object(72, 1, false, -1, 0));
}
if (Game1.random.NextDouble() < 0.05)
{
treasures.Last<Item>().Stack *= 2;
}
break;
case 2:
if (Game1.player.FishingLevel < 2)
{
treasures.Add(new StardewValley.Object(770, Game1.random.Next(1, 4), false, -1, 0));
}
else
{
float luckModifier = (1f + (float)Game1.player.DailyLuck);
if (Game1.random.NextDouble() < 0.05 * (double)luckModifier && !Game1.player.specialItems.Contains(14))
{
treasures.Add(new MeleeWeapon(14)
{
specialItem = true
});
}
if (Game1.random.NextDouble() < 0.05 * (double)luckModifier && !Game1.player.specialItems.Contains(51))
{
treasures.Add(new MeleeWeapon(51)
{
specialItem = true
});
}
if (Game1.random.NextDouble() < 0.07 * (double)luckModifier)
{
switch (Game1.random.Next(3))
{
case 0:
treasures.Add(new Ring(516 + ((Game1.random.NextDouble() < (double)((float)Game1.player.LuckLevel / 11f)) ? 1 : 0)));
break;
case 1:
treasures.Add(new Ring(518 + ((Game1.random.NextDouble() < (double)((float)Game1.player.LuckLevel / 11f)) ? 1 : 0)));
break;
case 2:
treasures.Add(new Ring(Game1.random.Next(529, 535)));
break;
}
}
if (Game1.random.NextDouble() < 0.02 * (double)luckModifier)
{
treasures.Add(new StardewValley.Object(166, 1, false, -1, 0));
}
if (Game1.random.NextDouble() < 0.001 * (double)luckModifier)
{
treasures.Add(new StardewValley.Object(74, 1, false, -1, 0));
}
if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
{
treasures.Add(new StardewValley.Object(127, 1, false, -1, 0));
}
if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
{
treasures.Add(new StardewValley.Object(126, 1, false, -1, 0));
}
if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
{
treasures.Add(new Ring(527));
}
if (Game1.random.NextDouble() < 0.01 * (double)luckModifier)
{
treasures.Add(new Boots(Game1.random.Next(504, 514)));
}
if (treasures.Count == 1)
{
treasures.Add(new StardewValley.Object(72, 1, false, -1, 0));
}
}
break;
}
break;
}
}
if (treasures.Count == 0)
{
treasures.Add(new StardewValley.Object(685, Game1.random.Next(1, 4) * 5, false, -1, 0));
}
if (treasures.Count > 0)
{
Color tint = Color.White;
l.overlayObjects[v] = new Chest(Game1.random.Next(0, 1000), new List<Item>() { treasures[ModEntry.myRand.Value.Next(treasures.Count)] }, v, false, 0)
{
Tint = tint
};
}
}
}
19
Source : Utils.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public static void AddSecrets(MineShaft shaft)
{
if (config.OverrideTreasureRooms && (helper.Reflection.GetField<NetBool>(shaft, "netIsTreasureRoom").GetValue().Value || (shaft.mineLevel < 121 && shaft.mineLevel % 20 == 0) || shaft.mineLevel == 10 || shaft.mineLevel == 50 || shaft.mineLevel == 70 || shaft.mineLevel == 90 || shaft.mineLevel == 110))
{
monitor.Log($"is treasure room");
return;
}
List <Vector2> clearSpots = new List<Vector2>();
List<Vector2> clearCenters = new List<Vector2>();
List<Vector2> superClearCenters = new List<Vector2>();
Vector2 tileBeneathLadder = helper.Reflection.GetField<NetVector2>(shaft, "netTileBeneathLadder").GetValue();
monitor.Log($"tileBeneathLadder: {tileBeneathLadder}");
for (int x = 0; x < shaft.map.Layers[0].LayerWidth; x++)
{
for (int y = 0; y < shaft.map.Layers[0].LayerHeight; y++)
{
Tile build = shaft.map.GetLayer("Buildings").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if(build != null)
{
if(build.TileIndex == 115)
{
tileBeneathLadder = new Vector2(x, y + 1);
monitor.Log($"made tileBeneathLadder: {tileBeneathLadder}");
}
continue;
}
if (x == tileBeneathLadder.X && y == tileBeneathLadder.Y)
continue;
Tile tile = shaft.map.GetLayer("Back").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size);
if (tile != null && (tile.TileIndex / 16 > 7 || tile.TileIndex % 16 < 9) && shaft.map.GetLayer("Front").PickTile(new Location(x, y) * Game1.tileSize, Game1.viewport.Size) == null)
{
clearSpots.Add(new Vector2(x, y));
}
}
}
monitor.Log($"clearSpots contains tileBeneathLadder: {clearSpots.Contains(tileBeneathLadder)}");
foreach (Vector2 spot in clearSpots)
{
int clear = GetTileClearance(shaft, spot, clearSpots);
if(clear > 0)
{
clearCenters.Add(spot);
}
if(clear > 1)
{
superClearCenters.Add(spot);
}
}
monitor.Log($"got {clearSpots.Count} clear spots in {shaft.Name}");
monitor.Log($"got {clearCenters.Count} clear centers in {shaft.Name}");
monitor.Log($"got {superClearCenters.Count} super clear centers in {shaft.Name}");
monitor.Log($"adding underground_secrets tilesheet");
TileSheet mine = shaft.map.TileSheets[0];
helper.Reflection.GetField<Size>(mine, "m_sheetSize").SetValue(new Size(16, 18));
shaft.map.AddTileSheet(new TileSheet(ModEntry.tileSheetId, shaft.map, ModEntry.tileSheetPath, new Size(16,18), new Size(16,16)));
shaft.map.LoadTileSheets(Game1.mapDisplayDevice);
TilePuzzles.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
LightPuzzles.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
OfferingPuzzles.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
Altars.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
RiddlePuzzles.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
Traps.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
if(shaft.mineLevel > 120)
CollapsingFloors.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
MushroomTrees.Start(shaft, ref superClearCenters, ref clearCenters, ref clearSpots);
}
19
Source : ObjLoader.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
int FindOrAddObjVertex(ref string faceParamater, ref Vector3 vertex, ref Vector2 texCoord, ref Vector3 normal)
{
int index;
if (objFaceToMeshIndicie.TryGetValue(faceParamater, out index)) {
return index;
} else {
verticesMesh.Add(vertex);
uvsMesh.Add(texCoord);
normalsMesh.Add(normal);
index = verticesMesh.Count - 1;
objFaceToMeshIndicie[faceParamater]=index;
return index;
}
}
19
Source : ObjLoader.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
Mesh Parse(Resource resource, GameObject appendToGameObject)
{
using (StreamReader textReader = new StreamReader(resource))
{
int i1, i2, i3, i4;
string line;
while ((line = textReader.ReadLine()) != null)
{
line = line.Trim(trimCharacters);
line = line.Replace(" ", " ");
string[] parameters = line.Split(splitCharacters);
switch (parameters[0])
{
case "p": // Point
break;
case "v": // Vertex
var v = Vector3.Zero;
Parse(ref parameters[1], ref v.X);
Parse(ref parameters[2], ref v.Y);
Parse(ref parameters[3], ref v.Z);
verticesObj.Add(v);
break;
case "vt": // TexCoord
gotUvs = true;
var vt = Vector2.Zero;
Parse(ref parameters[1], ref vt.X);
Parse(ref parameters[2], ref vt.Y);
uvsObj.Add(vt);
break;
case "vn": // Normal
gotNormal = true;
var vn = Vector3.Zero;
Parse(ref parameters[1], ref vn.X);
Parse(ref parameters[2], ref vn.Y);
Parse(ref parameters[3], ref vn.Z);
normalsObj.Add(vn);
break;
case "f":
switch (parameters.Length)
{
case 4:
i1 = ParseFaceParameter(parameters[1]);
i2 = ParseFaceParameter(parameters[2]);
i3 = ParseFaceParameter(parameters[3]);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i2);
triangleIndiciesMesh.Add(i3);
break;
case 5:
i1 = ParseFaceParameter(parameters[1]);
i2 = ParseFaceParameter(parameters[2]);
i3 = ParseFaceParameter(parameters[3]);
i4 = ParseFaceParameter(parameters[4]);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i2);
triangleIndiciesMesh.Add(i3);
triangleIndiciesMesh.Add(i1);
triangleIndiciesMesh.Add(i3);
triangleIndiciesMesh.Add(i4);
break;
}
break;
case "mtllib":
if (Resource.ResourceInFolderExists(resource, parameters[1]))
{
materialLibrary = new MaterialLibrary(Resource.GetResourceInFolder(resource, parameters[1]));
}
break;
case "usemtl":
if (materialLibrary!=null) lastMaterial = materialLibrary.GetMat(parameters[1]);
break;
}
}
textReader.Close();
}
if(appendToGameObject!=null) return EndObjPart(appendToGameObject);
Debug.Info("Loaded " + resource.originalPath + " vertices:" + verticesMesh.Count + " faces:" + triangleIndiciesMesh.Count / 3);
return EndMesh();
}
19
Source : AirarManager.cs
with BSD 3-Clause "New" or "Revised" License
from airar-dev
with BSD 3-Clause "New" or "Revised" License
from airar-dev
public float[] CalculateMarkerImageVertex(GameObject cube)
{
List<Vector2> vertexList = new List<Vector2>();
Vector3[] vertices = cube.GetComponent<MeshFilter>().mesh.vertices;
Vector2[] result = new Vector2[vertices.Length];
for (int i = 0; i < vertices.Length; ++i)
{
result[i] = Camera.main.WorldToScreenPoint(cube.transform.TransformPoint(vertices[i]));
vertexList.Add(result[i]);
}
// Actual Device Size
int screenHeight = Screen.height;
// Use mesh bottom vertices
// 14(LU), 13(RU), 12(RD), 15(LD)
Vector2 LU = new Vector2();
Vector2 RU = new Vector2();
Vector2 RD = new Vector2();
Vector2 LD = new Vector2();
for (int i = 0; i < vertexList.Count; i++)
{
if (i >= 12 && i <= 15)
{
LU = vertexList[14];
RU = vertexList[13];
RD = vertexList[12];
LD = vertexList[15];
}
}
float[] srcPosition = new float[8];
srcPosition[0] = LU.x;
srcPosition[1] = screenHeight - LU.y;
srcPosition[2] = RU.x;
srcPosition[3] = screenHeight - RU.y;
srcPosition[4] = RD.x;
srcPosition[5] = screenHeight - RD.y;
srcPosition[6] = LD.x;
srcPosition[7] = screenHeight - LD.y;
return srcPosition;
}
19
Source : NodeEditorAction.cs
with MIT License
from aksyr
with MIT License
from aksyr
public void Controls() {
wantsMouseMove = true;
Event e = Event.current;
switch (e.type) {
case EventType.MouseMove:
break;
case EventType.ScrollWheel:
float oldZoom = zoom;
if (e.delta.y > 0) zoom += 0.1f * zoom;
else zoom -= 0.1f * zoom;
if (NodeEditorPreferences.GetSettings().zoomToMouse) panOffset += (1 - oldZoom / zoom) * (WindowToGridPosition(e.mousePosition) + panOffset);
break;
case EventType.MouseDrag:
if (e.button == 0) {
if (IsDraggingPort) {
if (IsHoveringPort && draggedPort.CanConnectTo(hoveredPort)) {
if (!draggedPort.IsConnectedTo(hoveredPort)) {
draggedPortTarget = hoveredPort;
}
} else {
draggedPortTarget = null;
}
Repaint();
} else if (currentActivity == NodeActivity.HoldNode) {
RecalculateDragOffsets(e);
currentActivity = NodeActivity.DragNode;
Repaint();
}
if (currentActivity == NodeActivity.DragNode) {
// Holding ctrl inverts grid snap
bool gridSnap = NodeEditorPreferences.GetSettings().gridSnap;
if (e.control) gridSnap = !gridSnap;
Vector2 mousePos = WindowToGridPosition(e.mousePosition);
// Move selected nodes with offset
for (int i = 0; i < Selection.objects.Length; i++) {
if (Selection.objects[i] is XNode.Node) {
XNode.Node node = Selection.objects[i] as XNode.Node;
Vector2 initial = node.position;
node.position = mousePos + dragOffset[i];
if (gridSnap) {
node.position.x = (Mathf.Round((node.position.x + 8) / 16) * 16) - 8;
node.position.y = (Mathf.Round((node.position.y + 8) / 16) * 16) - 8;
}
// Offset portConnectionPoints instantly if a node is dragged so they aren't delayed by a frame.
Vector2 offset = node.position - initial;
if (offset.sqrMagnitude > 0) {
foreach (XNode.NodePort output in node.Outputs) {
Rect rect;
if (portConnectionPoints.TryGetValue(output, out rect)) {
rect.position += offset;
portConnectionPoints[output] = rect;
}
}
foreach (XNode.NodePort input in node.Inputs) {
Rect rect;
if (portConnectionPoints.TryGetValue(input, out rect)) {
rect.position += offset;
portConnectionPoints[input] = rect;
}
}
}
}
}
// Move selected reroutes with offset
for (int i = 0; i < selectedReroutes.Count; i++) {
Vector2 pos = mousePos + dragOffset[Selection.objects.Length + i];
if (gridSnap) {
pos.x = (Mathf.Round(pos.x / 16) * 16);
pos.y = (Mathf.Round(pos.y / 16) * 16);
}
selectedReroutes[i].SetPoint(pos);
}
Repaint();
} else if (currentActivity == NodeActivity.HoldGrid) {
currentActivity = NodeActivity.DragGrid;
preBoxSelection = Selection.objects;
preBoxSelectionReroute = selectedReroutes.ToArray();
dragBoxStart = WindowToGridPosition(e.mousePosition);
Repaint();
} else if (currentActivity == NodeActivity.DragGrid) {
Vector2 boxStartPos = GridToWindowPosition(dragBoxStart);
Vector2 boxSize = e.mousePosition - boxStartPos;
if (boxSize.x < 0) { boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x); }
if (boxSize.y < 0) { boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y); }
selectionBox = new Rect(boxStartPos, boxSize);
Repaint();
}
} else if (e.button == 1 || e.button == 2) {
panOffset += e.delta * zoom;
isPanning = true;
}
break;
case EventType.MouseDown:
Repaint();
if (e.button == 0) {
draggedOutputReroutes.Clear();
if (IsHoveringPort) {
hoveredPort.VerifyConnections();
if (hoveredPort.IsConnected)
{
if (e.alt)
{
draggedPort = hoveredPort;
}
else
{
XNode.Node node = hoveredPort.node;
XNode.NodePort output = hoveredPort.Connection;
int outputConnectionIndex = output.GetConnectionIndex(hoveredPort);
draggedOutputReroutes = output.GetReroutePoints(outputConnectionIndex);
hoveredPort.Disconnect(output);
draggedPort = output;
draggedPortTarget = hoveredPort;
if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node);
}
}
else
{
draggedPort = hoveredPort;
}
} else if (IsHoveringNode && IsHoveringreplacedle(hoveredNode)) {
// If mousedown on node header, select or deselect
if (!Selection.Contains(hoveredNode)) {
SelectNode(hoveredNode, e.control || e.shift);
if (!e.control && !e.shift) selectedReroutes.Clear();
} else if (e.control || e.shift) DeselectNode(hoveredNode);
// Cache double click state, but only act on it in MouseUp - Except ClickCount only works in mouseDown.
isDoubleClick = (e.clickCount == 2);
e.Use();
currentActivity = NodeActivity.HoldNode;
} else if (IsHoveringReroute) {
// If reroute isn't selected
if (!selectedReroutes.Contains(hoveredReroute)) {
// Add it
if (e.control || e.shift) selectedReroutes.Add(hoveredReroute);
// Select it
else {
selectedReroutes = new List<RerouteReference>() { hoveredReroute };
Selection.activeObject = null;
}
}
// Deselect
else if (e.control || e.shift) selectedReroutes.Remove(hoveredReroute);
e.Use();
currentActivity = NodeActivity.HoldNode;
}
// If mousedown on grid background, deselect all
else if (!IsHoveringNode) {
currentActivity = NodeActivity.HoldGrid;
if (!e.control && !e.shift) {
selectedReroutes.Clear();
Selection.activeObject = null;
}
}
}
break;
case EventType.MouseUp:
if (e.button == 0) {
//Port drag release
if (IsDraggingPort) {
//If connection is valid, save it
if (draggedPortTarget != null) {
XNode.Node node = draggedPortTarget.node;
if (graph.nodes.Count != 0) draggedPort.Connect(draggedPortTarget);
// ConnectionIndex can be -1 if the connection is removed instantly after creation
int connectionIndex = draggedPort.GetConnectionIndex(draggedPortTarget);
if (connectionIndex != -1) {
draggedPort.GetReroutePoints(connectionIndex).AddRange(draggedOutputReroutes);
if (NodeEditor.onUpdateNode != null) NodeEditor.onUpdateNode(node);
EditorUtility.SetDirty(graph);
}
}
//Release dragged connection
draggedPort = null;
draggedPortTarget = null;
EditorUtility.SetDirty(graph);
if (NodeEditorPreferences.GetSettings().autoSave) replacedetDatabase.Savereplacedets();
} else if (currentActivity == NodeActivity.DragNode) {
IEnumerable<XNode.Node> nodes = Selection.objects.Where(x => x is XNode.Node).Select(x => x as XNode.Node);
foreach (XNode.Node node in nodes) EditorUtility.SetDirty(node);
if (NodeEditorPreferences.GetSettings().autoSave) replacedetDatabase.Savereplacedets();
} else if (!IsHoveringNode) {
// If click outside node, release field focus
if (!isPanning) {
EditorGUI.FocusTextInControl(null);
EditorGUIUtility.editingTextField = false;
}
if (NodeEditorPreferences.GetSettings().autoSave) replacedetDatabase.Savereplacedets();
}
// If click node header, select it.
if (currentActivity == NodeActivity.HoldNode && !(e.control || e.shift)) {
selectedReroutes.Clear();
SelectNode(hoveredNode, false);
// Double click to center node
if (isDoubleClick) {
Vector2 nodeDimension = nodeSizes.ContainsKey(hoveredNode) ? nodeSizes[hoveredNode] / 2 : Vector2.zero;
panOffset = -hoveredNode.position - nodeDimension;
}
}
// If click reroute, select it.
if (IsHoveringReroute && !(e.control || e.shift)) {
selectedReroutes = new List<RerouteReference>() { hoveredReroute };
Selection.activeObject = null;
}
Repaint();
currentActivity = NodeActivity.Idle;
} else if (e.button == 1 || e.button == 2) {
if (!isPanning) {
if (IsDraggingPort) {
draggedOutputReroutes.Add(WindowToGridPosition(e.mousePosition));
} else if (currentActivity == NodeActivity.DragNode && Selection.activeObject == null && selectedReroutes.Count == 1) {
selectedReroutes[0].InsertPoint(selectedReroutes[0].GetPoint());
selectedReroutes[0] = new RerouteReference(selectedReroutes[0].port, selectedReroutes[0].connectionIndex, selectedReroutes[0].pointIndex + 1);
} else if (IsHoveringReroute) {
ShowRerouteContextMenu(hoveredReroute);
} else if (IsHoveringPort) {
ShowPortContextMenu(hoveredPort);
} else if (IsHoveringNode && IsHoveringreplacedle(hoveredNode)) {
if (!Selection.Contains(hoveredNode)) SelectNode(hoveredNode, false);
GenericMenu menu = new GenericMenu();
NodeEditor.GetEditor(hoveredNode, this).AddContextMenuItems(menu);
menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
e.Use(); // Fixes copy/paste context menu appearing in Unity 5.6.6f2 - doesn't occur in 2018.3.2f1 Probably needs to be used in other places.
} else if (!IsHoveringNode) {
GenericMenu menu = new GenericMenu();
graphEditor.AddContextMenuItems(menu);
menu.DropDown(new Rect(Event.current.mousePosition, Vector2.zero));
}
}
isPanning = false;
}
// Reset DoubleClick
isDoubleClick = false;
break;
case EventType.KeyDown:
if (EditorGUIUtility.editingTextField) break;
else if (e.keyCode == KeyCode.F) Home();
if (IsMac()) {
if (e.keyCode == KeyCode.Return) RenameSelectedNode();
} else {
if (e.keyCode == KeyCode.F2) RenameSelectedNode();
}
break;
case EventType.ValidateCommand:
case EventType.ExecuteCommand:
if (e.commandName == "SoftDelete") {
if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes();
e.Use();
} else if (IsMac() && e.commandName == "Delete") {
if (e.type == EventType.ExecuteCommand) RemoveSelectedNodes();
e.Use();
} else if (e.commandName == "Duplicate") {
if (e.type == EventType.ExecuteCommand) DuplicateSelectedNodes();
e.Use();
}
Repaint();
break;
case EventType.Ignore:
// If release mouse outside window
if (e.rawType == EventType.MouseUp && currentActivity == NodeActivity.DragGrid) {
Repaint();
currentActivity = NodeActivity.Idle;
}
break;
}
}
19
Source : NodeEditorAction.cs
with MIT License
from aksyr
with MIT License
from aksyr
public void DrawDraggedConnection() {
if (IsDraggingPort) {
Color col = NodeEditorPreferences.GetTypeColor(draggedPort.ValueType);
col.a = draggedPortTarget != null ? 1.0f : 0.6f;
Rect fromRect;
if (!_portConnectionPoints.TryGetValue(draggedPort, out fromRect)) return;
List<Vector2> gridPoints = new List<Vector2>();
gridPoints.Add(fromRect.center);
for (int i = 0; i < draggedOutputReroutes.Count; i++) {
gridPoints.Add(draggedOutputReroutes[i]);
}
if (draggedPortTarget != null) gridPoints.Add(portConnectionPoints[draggedPortTarget].center);
else gridPoints.Add(WindowToGridPosition(Event.current.mousePosition));
if(draggedPort.IsInput)
{
gridPoints.Reverse();
}
DrawNoodle(col, gridPoints);
Color bgcol = Color.black;
Color frcol = col;
bgcol.a = 0.6f;
frcol.a = 0.6f;
// Loop through reroute points again and draw the points
for (int i = 0; i < draggedOutputReroutes.Count; i++) {
// Draw reroute point at position
Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16));
rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8);
rect = GridToWindowRect(rect);
NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol);
}
}
}
19
Source : NodeEditorAction.cs
with MIT License
from aksyr
with MIT License
from aksyr
public void DrawDraggedConnection() {
if (IsDraggingPort) {
Color col = NodeEditorPreferences.GetTypeColor(draggedPort.ValueType);
col.a = draggedPortTarget != null ? 1.0f : 0.6f;
Rect fromRect;
if (!_portConnectionPoints.TryGetValue(draggedPort, out fromRect)) return;
List<Vector2> gridPoints = new List<Vector2>();
gridPoints.Add(fromRect.center);
for (int i = 0; i < draggedOutputReroutes.Count; i++) {
gridPoints.Add(draggedOutputReroutes[i]);
}
if (draggedPortTarget != null) gridPoints.Add(portConnectionPoints[draggedPortTarget].center);
else gridPoints.Add(WindowToGridPosition(Event.current.mousePosition));
if(draggedPort.IsInput)
{
gridPoints.Reverse();
}
DrawNoodle(col, gridPoints);
Color bgcol = Color.black;
Color frcol = col;
bgcol.a = 0.6f;
frcol.a = 0.6f;
// Loop through reroute points again and draw the points
for (int i = 0; i < draggedOutputReroutes.Count; i++) {
// Draw reroute point at position
Rect rect = new Rect(draggedOutputReroutes[i], new Vector2(16, 16));
rect.position = new Vector2(rect.position.x - 8, rect.position.y - 8);
rect = GridToWindowRect(rect);
NodeEditorGUILayout.DrawPortHandle(rect, bgcol, frcol);
}
}
}
19
Source : NodeEditorGUI.cs
with MIT License
from aksyr
with MIT License
from aksyr
public void DrawConnections() {
Vector2 mousePos = Event.current.mousePosition;
List<RerouteReference> selection = preBoxSelectionReroute != null ? new List<RerouteReference>(preBoxSelectionReroute) : new List<RerouteReference>();
hoveredReroute = new RerouteReference();
Color col = GUI.color;
foreach (XNode.Node node in graph.nodes) {
//If a null node is found, return. This can happen if the nodes replacedociated script is deleted. It is currently not possible in Unity to delete a null replacedet.
if (node == null) continue;
// Draw full connections and output > reroute
foreach (XNode.NodePort output in node.Outputs) {
//Needs cleanup. Null checks are ugly
Rect fromRect;
if (!_portConnectionPoints.TryGetValue(output, out fromRect)) continue;
Color connectionColor = graphEditor.GetPortColor(output);
for (int k = 0; k < output.ConnectionCount; k++) {
XNode.NodePort input = output.GetConnection(k);
// Error handling
if (input == null) continue; //If a script has been updated and the port doesn't exist, it is removed and null is returned. If this happens, return.
if (!input.IsConnectedTo(output)) input.Connect(output);
Rect toRect;
if (!_portConnectionPoints.TryGetValue(input, out toRect)) continue;
List<Vector2> reroutePoints = output.GetReroutePoints(k);
List<Vector2> gridPoints = new List<Vector2>();
gridPoints.Add(fromRect.center);
gridPoints.AddRange(reroutePoints);
gridPoints.Add(toRect.center);
DrawNoodle(connectionColor, gridPoints);
// Loop through reroute points again and draw the points
for (int i = 0; i < reroutePoints.Count; i++) {
RerouteReference rerouteRef = new RerouteReference(output, k, i);
// Draw reroute point at position
Rect rect = new Rect(reroutePoints[i], new Vector2(12, 12));
rect.position = new Vector2(rect.position.x - 6, rect.position.y - 6);
rect = GridToWindowRect(rect);
// Draw selected reroute points with an outline
if (selectedReroutes.Contains(rerouteRef)) {
GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
GUI.DrawTexture(rect, NodeEditorResources.dotOuter);
}
GUI.color = connectionColor;
GUI.DrawTexture(rect, NodeEditorResources.dot);
if (rect.Overlaps(selectionBox)) selection.Add(rerouteRef);
if (rect.Contains(mousePos)) hoveredReroute = rerouteRef;
}
}
}
}
GUI.color = col;
if (Event.current.type != EventType.Layout && currentActivity == NodeActivity.DragGrid) selectedReroutes = selection;
}
19
Source : CuttingTools.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public static bool Cut(World world, Vector2 start, Vector2 end)
{
List<Fixture> fixtures = new List<Fixture>();
List<Vector2> entryPoints = new List<Vector2>();
List<Vector2> exitPoints = new List<Vector2>();
//We don't support cutting when the start or end is inside a shape.
if (world.TestPoint(start) != null || world.TestPoint(end) != null)
return false;
//Get the entry points
world.RayCast((f, p, n, fr) =>
{
fixtures.Add(f);
entryPoints.Add(p);
return 1;
}, start, end);
//Reverse the ray to get the exitpoints
world.RayCast((f, p, n, fr) =>
{
exitPoints.Add(p);
return 1;
}, end, start);
//We only have a single point. We need at least 2
if (entryPoints.Count + exitPoints.Count < 2)
return false;
for (int i = 0; i < fixtures.Count; i++)
{
// can't cut circles or edges yet !
if (fixtures[i].Shape.ShapeType != ShapeType.Polygon)
continue;
if (fixtures[i].Body.BodyType != BodyType.Static)
{
//Split the shape up into two shapes
Vertices first;
Vertices second;
SplitShape(fixtures[i], entryPoints[i], exitPoints[i], out first, out second);
//Delete the original shape and create two new. Retain the properties of the body.
if (first.CheckPolygon() == PolygonError.NoError)
{
Body firstFixture = BodyFactory.CreatePolygon(world, first, fixtures[i].Shape.Density, fixtures[i].Body.Position);
firstFixture.Rotation = fixtures[i].Body.Rotation;
firstFixture.LinearVelocity = fixtures[i].Body.LinearVelocity;
firstFixture.AngularVelocity = fixtures[i].Body.AngularVelocity;
firstFixture.BodyType = BodyType.Dynamic;
}
if (second.CheckPolygon() == PolygonError.NoError)
{
Body secondFixture = BodyFactory.CreatePolygon(world, second, fixtures[i].Shape.Density, fixtures[i].Body.Position);
secondFixture.Rotation = fixtures[i].Body.Rotation;
secondFixture.LinearVelocity = fixtures[i].Body.LinearVelocity;
secondFixture.AngularVelocity = fixtures[i].Body.AngularVelocity;
secondFixture.BodyType = BodyType.Dynamic;
}
world.RemoveBody(fixtures[i].Body);
}
}
return true;
}
19
Source : TextureConverter.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public List<Vertices> DetectVertices()
{
#region Check TextureConverter setup.
if (_data == null)
throw new Exception("'_data' can't be null. You have to use SetTextureData(uint[] data, int width) before calling this method.");
if (_data.Length < 4)
throw new Exception("'_data' length can't be less then 4. Your texture must be at least 2 x 2 pixels in size. " +
"You have to use SetTextureData(uint[] data, int width) before calling this method.");
if (_width < 2)
throw new Exception("'_width' can't be less then 2. Your texture must be at least 2 x 2 pixels in size. " +
"You have to use SetTextureData(uint[] data, int width) before calling this method.");
if (_data.Length % _width != 0)
throw new Exception("'_width' has an invalid value. You have to use SetTextureData(uint[] data, int width) before calling this method.");
#endregion
List<Vertices> detectedPolygons = new List<Vertices>();
Vector2? holeEntrance = null;
Vector2? polygonEntrance = null;
List<Vector2> blackList = new List<Vector2>();
bool searchOn;
do
{
Vertices polygon;
if (detectedPolygons.Count == 0)
{
// First preplaced / single polygon
polygon = new Vertices(CreateSimplePolygon(Vector2.Zero, Vector2.Zero));
if (polygon.Count > 2)
polygonEntrance = GetTopMostVertex(polygon);
}
else if (polygonEntrance.HasValue)
{
// Multi preplaced / multiple polygons
polygon = new Vertices(CreateSimplePolygon(polygonEntrance.Value, new Vector2(polygonEntrance.Value.X - 1f, polygonEntrance.Value.Y)));
}
else
break;
searchOn = false;
if (polygon.Count > 2)
{
if (_holeDetection)
{
do
{
holeEntrance = SearchHoleEntrance(polygon, holeEntrance);
if (holeEntrance.HasValue)
{
if (!blackList.Contains(holeEntrance.Value))
{
blackList.Add(holeEntrance.Value);
Vertices holePolygon = CreateSimplePolygon(holeEntrance.Value,
new Vector2(holeEntrance.Value.X + 1, holeEntrance.Value.Y));
if (holePolygon != null && holePolygon.Count > 2)
{
switch (_polygonDetectionType)
{
case VerticesDetectionType.Integrated:
// Add first hole polygon vertex to close the hole polygon.
holePolygon.Add(holePolygon[0]);
int vertex1Index, vertex2Index;
if (SplitPolygonEdge(polygon, holeEntrance.Value, out vertex1Index, out vertex2Index))
polygon.InsertRange(vertex2Index, holePolygon);
break;
case VerticesDetectionType.Separated:
if (polygon.Holes == null)
polygon.Holes = new List<Vertices>();
polygon.Holes.Add(holePolygon);
break;
}
}
}
else
break;
}
else
break;
}
while (true);
}
detectedPolygons.Add(polygon);
}
if (_multipartDetection || polygon.Count <= 2)
{
if (SearchNextHullEntrance(detectedPolygons, polygonEntrance.Value, out polygonEntrance))
searchOn = true;
}
}
while (searchOn);
if (detectedPolygons == null || (detectedPolygons != null && detectedPolygons.Count == 0))
throw new Exception("Couldn't detect any vertices.");
// Post processing.
if (PolygonDetectionType == VerticesDetectionType.Separated) // Only when VerticesDetectionType.Separated? -> Recheck.
ApplyTriangulationCompatibleWinding(ref detectedPolygons);
if (_transform != Matrix.Idenreplacedy)
ApplyTransform(ref detectedPolygons);
return detectedPolygons;
}
19
Source : Path.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void Add(Vector2 point)
{
ControlPoints.Add(point);
_deltaT = 1f / (ControlPoints.Count - 1);
}
19
Source : GravityController.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public void AddPoint(Vector2 point)
{
Points.Add(point);
}
19
Source : ElevatedTerrainWithSidesStrategy.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private void CreateBaseMesh(UnityTile tile)
{
//TODO use arrays instead of lists
_newVertexList.Clear();
_newNormalList.Clear();
_newUvList.Clear();
_newTriangleList.Clear();
var _sampleCount = _elevationOptions.modificationOptions.sampleCount;
for (float y = 0; y < _sampleCount; y++)
{
var yrat = y / (_sampleCount - 1);
for (float x = 0; x < _sampleCount; x++)
{
var xrat = x / (_sampleCount - 1);
var xx = Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, xrat);
var yy = Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, yrat);
_newVertexList.Add(new Vector3(
(float)(xx - tile.Rect.Center.x) * tile.TileScale,
0,
(float)(yy - tile.Rect.Center.y) * tile.TileScale));
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newUvList.Add(new Vector2(x * 1f / (_sampleCount - 1), 1 - (y * 1f / (_sampleCount - 1))));
}
}
int vertA, vertB, vertC;
for (int y = 0; y < _sampleCount - 1; y++)
{
for (int x = 0; x < _sampleCount - 1; x++)
{
vertA = (y * _sampleCount) + x;
vertB = (y * _sampleCount) + x + _sampleCount + 1;
vertC = (y * _sampleCount) + x + _sampleCount;
_newTriangleList.Add(vertA);
_newTriangleList.Add(vertB);
_newTriangleList.Add(vertC);
vertA = (y * _sampleCount) + x;
vertB = (y * _sampleCount) + x + 1;
vertC = (y * _sampleCount) + x + _sampleCount + 1;
_newTriangleList.Add(vertA);
_newTriangleList.Add(vertB);
_newTriangleList.Add(vertC);
}
}
var sideVertBase = _newVertexList.Count;
var lastRow = (_sampleCount - 1) * _sampleCount;
var baseTriList = new List<int>();
for (int x = 0; x < _sampleCount; x++)
{
//side wall
//024
//135
_newVertexList.Add(_newVertexList[x]);
_newVertexList.Add(new Vector3(
_newVertexList[x].x,
-_elevationOptions.sideWallOptions.wallHeight,
_newVertexList[x].z));
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Forward);
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Forward);
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));
//---
_newVertexList.Add(_newVertexList[x * _sampleCount]);
_newVertexList.Add(new Vector3(
_newVertexList[x * _sampleCount].x,
-_elevationOptions.sideWallOptions.wallHeight,
_newVertexList[x * _sampleCount].z));
_newNormalList.Add(Vector3.left);
_newNormalList.Add(Vector3.left);
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));
//---
_newVertexList.Add(_newVertexList[(x + 1) * _sampleCount - 1]);
_newVertexList.Add(new Vector3(
_newVertexList[(x + 1) * _sampleCount - 1].x,
-_elevationOptions.sideWallOptions.wallHeight,
_newVertexList[(x + 1) * _sampleCount - 1].z));
_newNormalList.Add(Vector3.right);
_newNormalList.Add(Vector3.right);
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));
//---
_newVertexList.Add(_newVertexList[lastRow + x]);
_newVertexList.Add(new Vector3(
_newVertexList[lastRow + x].x,
-_elevationOptions.sideWallOptions.wallHeight,
_newVertexList[lastRow + x].z));
_newNormalList.Add(Vector3.back);
_newNormalList.Add(Vector3.back);
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 1));
_newUvList.Add(new Vector2(_newUvList[x * _sampleCount].y, 0));
if (x > 0)
{
baseTriList.Add(sideVertBase + 8 * x);
baseTriList.Add(sideVertBase + 8 * x - 8);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1);
baseTriList.Add(sideVertBase + 8 * x);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1);
baseTriList.Add(sideVertBase + 8 * x + 1);
//---
baseTriList.Add(sideVertBase + 8 * x + 2);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 2);
baseTriList.Add(sideVertBase + 8 * x - 8 + 2);
baseTriList.Add(sideVertBase + 8 * x + 2);
baseTriList.Add(sideVertBase + 8 * x + 1 + 2);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 2);
//---
baseTriList.Add(sideVertBase + 8 * x + 4);
baseTriList.Add(sideVertBase + 8 * x - 8 + 4);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 4);
baseTriList.Add(sideVertBase + 8 * x + 4);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 4);
baseTriList.Add(sideVertBase + 8 * x + 1 + 4);
//---
baseTriList.Add(sideVertBase + 8 * x + 6);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 6);
baseTriList.Add(sideVertBase + 8 * x - 8 + 6);
baseTriList.Add(sideVertBase + 8 * x + 6);
baseTriList.Add(sideVertBase + 8 * x + 1 + 6);
baseTriList.Add(sideVertBase + 8 * x - 8 + 1 + 6);
}
}
var mesh = tile.MeshFilter.mesh;
mesh.SetVertices(_newVertexList);
mesh.SetNormals(_newNormalList);
mesh.SetUVs(0, _newUvList);
mesh.subMeshCount = 2;
mesh.SetTriangles(_newTriangleList, 0);
mesh.SetTriangles(baseTriList, 1);
}
19
Source : LowPolyTerrainStrategy.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private void CreateBaseMesh(UnityTile tile)
{
//TODO use arrays instead of lists
_newVertexList.Clear();
_newNormalList.Clear();
_newUvList.Clear();
_newTriangleList.Clear();
var cap = (_elevationOptions.modificationOptions.sampleCount - 1);
for (float y = 0; y < cap; y++)
{
for (float x = 0; x < cap; x++)
{
var x1 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, x / cap) - tile.Rect.Center.x);
var y1 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, y / cap) - tile.Rect.Center.y);
var x2 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, (x + 1) / cap) - tile.Rect.Center.x);
var y2 = tile.TileScale * (float)(Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, (y + 1) / cap) - tile.Rect.Center.y);
var triStart = _newVertexList.Count;
_newVertexList.Add(new Vector3(x1, 0, y1));
_newVertexList.Add(new Vector3(x2, 0, y1));
_newVertexList.Add(new Vector3(x1, 0, y2));
//--
_newVertexList.Add(new Vector3(x2, 0, y1));
_newVertexList.Add(new Vector3(x2, 0, y2));
_newVertexList.Add(new Vector3(x1, 0, y2));
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
//--
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newUvList.Add(new Vector2(x / cap, 1 - y / cap));
_newUvList.Add(new Vector2((x + 1) / cap, 1 - y / cap));
_newUvList.Add(new Vector2(x / cap, 1 - (y + 1) / cap));
//--
_newUvList.Add(new Vector2((x + 1) / cap, 1 - y / cap));
_newUvList.Add(new Vector2((x + 1) / cap, 1 - (y + 1) / cap));
_newUvList.Add(new Vector2(x / cap, 1 - (y + 1) / cap));
_newTriangleList.Add(triStart);
_newTriangleList.Add(triStart + 1);
_newTriangleList.Add(triStart + 2);
//--
_newTriangleList.Add(triStart + 3);
_newTriangleList.Add(triStart + 4);
_newTriangleList.Add(triStart + 5);
}
}
var mesh = tile.MeshFilter.sharedMesh;
mesh.indexFormat = IndexFormat.UInt32;
mesh.SetVertices(_newVertexList);
mesh.SetNormals(_newNormalList);
mesh.SetUVs(0, _newUvList);
mesh.SetTriangles(_newTriangleList, 0);
mesh.RecalculateBounds();
}
19
Source : ChamferHeightModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private void Sides(VectorFeatureUnity feature, MeshData meshData, float hf, int originalVertexCount)
{
float d = 0f;
Vector3 v1;
Vector3 v2 = Mapbox.Unity.Constants.Math.Vector3Zero;
int ind = 0;
var wallTri = new List<int>();
var wallUv = new List<Vector2>();
meshData.Vertices.Add(new Vector3(meshData.Vertices[originalVertexCount - 1].x, meshData.Vertices[originalVertexCount - 1].y - hf, meshData.Vertices[originalVertexCount - 1].z));
meshData.Tangents.Add(meshData.Tangents[originalVertexCount - 1]);
wallUv.Add(new Vector2(0, -hf));
meshData.Normals.Add(meshData.Normals[originalVertexCount - 1]);
for (int i = 0; i < meshData.Edges.Count; i += 2)
{
v1 = meshData.Vertices[meshData.Edges[i]];
v2 = meshData.Vertices[meshData.Edges[i + 1]];
ind = meshData.Vertices.Count;
meshData.Vertices.Add(v1);
meshData.Vertices.Add(v2);
meshData.Vertices.Add(new Vector3(v1.x, v1.y - hf, v1.z));
meshData.Vertices.Add(new Vector3(v2.x, v2.y - hf, v2.z));
meshData.Normals.Add(meshData.Normals[meshData.Edges[i]]);
meshData.Normals.Add(meshData.Normals[meshData.Edges[i + 1]]);
meshData.Normals.Add(meshData.Normals[meshData.Edges[i]]);
meshData.Normals.Add(meshData.Normals[meshData.Edges[i + 1]]);
meshData.Tangents.Add(v2 - v1.normalized);
meshData.Tangents.Add(v2 - v1.normalized);
meshData.Tangents.Add(v2 - v1.normalized);
meshData.Tangents.Add(v2 - v1.normalized);
d = (v2 - v1).magnitude;
wallUv.Add(new Vector2(0, 0));
wallUv.Add(new Vector2(d, 0));
wallUv.Add(new Vector2(0, -hf));
wallUv.Add(new Vector2(d, -hf));
wallTri.Add(ind);
wallTri.Add(ind + 1);
wallTri.Add(ind + 2);
wallTri.Add(ind + 1);
wallTri.Add(ind + 3);
wallTri.Add(ind + 2);
}
meshData.Triangles.Add(wallTri);
meshData.UV[0].AddRange(wallUv);
}
19
Source : ChamferHeightModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
public void Chamfer(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
{
if (md.Vertices.Count == 0 || feature.Points.Count < 1)
return;
List<Vector3> newVertices = new List<Vector3>();
List<Vector2> newUV = new List<Vector2>();
md.Normals.Clear();
md.Edges.Clear();
md.Tangents.Clear();
for (int t = 0; t < md.Triangles[0].Count; t++)
{
md.Triangles[0][t] *= 3;
}
var next = 0; var current = 0; var prev = 0;
Vector3 v1, v2, n1, n2, pij1, pij2, pjk1, pjk2;
Vector3 poi, close1, close2;
var start = 0;
for (int i = 0; i < feature.Points.Count; i++)
{
var count = feature.Points[i].Count;
var cst = newVertices.Count;
for (int j = 0; j < count; j++)
{
if (j == count - 1)
{
newVertices.Add(newVertices[cst]);
newVertices.Add(newVertices[cst + 1]);
newVertices.Add(newVertices[cst + 2]);
newUV.Add(newUV[cst]);
newUV.Add(newUV[cst + 1]);
newUV.Add(newUV[cst + 2]);
md.Normals.Add(md.Normals[cst]);
md.Normals.Add(md.Normals[cst + 1]);
md.Normals.Add(md.Normals[cst + 2]);
md.Tangents.Add(md.Tangents[cst]);
md.Tangents.Add(md.Tangents[cst + 1]);
md.Tangents.Add(md.Tangents[cst + 2]);
continue;
}
current = start + j;
if (j > 0)
next = start + j - 1;
else
next = start + j - 1 + count - 1; //another -1 as last item equals first
prev = start + j + 1;
v1 = new Vector3(
md.Vertices[current].x - md.Vertices[next].x, 0,
md.Vertices[current].z - md.Vertices[next].z);
v1.Normalize();
v1 *= -_offset;
n1 = new Vector3(-v1.z, 0, v1.x);
pij1 = new Vector3(
(float)(md.Vertices[next].x + n1.x), 0,
(float)(md.Vertices[next].z + n1.z));
pij2 = new Vector3(
(float)(md.Vertices[current].x + n1.x), 0,
(float)(md.Vertices[current].z + n1.z));
v2 = new Vector3(
md.Vertices[prev].x - md.Vertices[current].x, 0,
md.Vertices[prev].z - md.Vertices[current].z);
v2.Normalize();
v2 *= -_offset;
n2 = new Vector3(-v2.z, 0, v2.x);
pjk1 = new Vector3(
(float)(md.Vertices[current].x + n2.x), 0,
(float)(md.Vertices[current].z + n2.z));
pjk2 = new Vector3(
(float)(md.Vertices[prev].x + n2.x), 0,
(float)(md.Vertices[prev].z + n2.z));
// See where the shifted lines ij and jk intersect.
bool lines_intersect, segments_intersect;
FindIntersection(pij1, pij2, pjk1, pjk2,
out lines_intersect, out segments_intersect,
out poi, out close1, out close2);
var d = Vector3.Distance(poi, pij2);
if (d > 10 * _offset)
{
poi = new Vector3((md.Vertices[current].x + (poi - (-v1 - v2)).normalized.x), 0,
(md.Vertices[current].z + (poi - (-v1 - v2)).normalized.z));
}
newVertices.Add(new Vector3(poi.x, poi.y + _offset + md.Vertices[current].y, poi.z));
newVertices.Add(md.Vertices[current] + v1);
newVertices.Add(md.Vertices[current] - v2);
md.Normals.Add(Constants.Math.Vector3Up);
md.Normals.Add(-n1);
md.Normals.Add(-n2);
md.Tangents.Add(v1 - v2);
md.Tangents.Add(v1 - v2);
md.Tangents.Add(v1 - v2);
newUV.Add(md.UV[0][current]);
newUV.Add(md.UV[0][current]);
newUV.Add(md.UV[0][current]);
md.Triangles[0].Add(3 * current);
md.Triangles[0].Add(3 * current + 1);
md.Triangles[0].Add(3 * current + 2);
md.Edges.Add(3 * current + 2);
md.Edges.Add(3 * current + 1);
md.Triangles[0].Add(3 * prev);
md.Triangles[0].Add(3 * current + 2);
md.Triangles[0].Add(3 * prev + 1);
md.Triangles[0].Add(3 * current);
md.Triangles[0].Add(3 * current + 2);
md.Triangles[0].Add(3 * prev);
md.Edges.Add(3 * prev + 1);
md.Edges.Add(3 * current + 2);
}
start += count;
}
md.Vertices = newVertices;
md.UV[0] = newUV;
}
19
Source : HeightModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
protected virtual void GenerateWallMesh(MeshData md)
{
md.Vertices.Capacity = _counter + md.Edges.Count * 2;
float d = 0f;
Vector3 v1;
Vector3 v2;
int ind = 0;
Vector3 wallDir;
if (_options.extrusionGeometryType != ExtrusionGeometryType.RoofOnly)
{
_counter = md.Edges.Count;
var wallTri = new List<int>(_counter * 3);
var wallUv = new List<Vector2>(_counter * 2);
Vector3 norm = Constants.Math.Vector3Zero;
md.Vertices.Capacity = md.Vertices.Count + _counter * 2;
md.Normals.Capacity = md.Normals.Count + _counter * 2;
for (int i = 0; i < _counter; i += 2)
{
v1 = md.Vertices[md.Edges[i]];
v2 = md.Vertices[md.Edges[i + 1]];
ind = md.Vertices.Count;
md.Vertices.Add(v1);
md.Vertices.Add(v2);
md.Vertices.Add(new Vector3(v1.x, v1.y - height, v1.z));
md.Vertices.Add(new Vector3(v2.x, v2.y - height, v2.z));
d = (v2 - v1).magnitude;
norm = Vector3.Normalize(Vector3.Cross(v2 - v1, md.Vertices[ind + 2] - v1));
md.Normals.Add(norm);
md.Normals.Add(norm);
md.Normals.Add(norm);
md.Normals.Add(norm);
wallDir = (v2 - v1).normalized;
md.Tangents.Add(wallDir);
md.Tangents.Add(wallDir);
md.Tangents.Add(wallDir);
md.Tangents.Add(wallDir);
wallUv.Add(new Vector2(0, 0));
wallUv.Add(new Vector2(d, 0));
wallUv.Add(new Vector2(0, -height));
wallUv.Add(new Vector2(d, -height));
wallTri.Add(ind);
wallTri.Add(ind + 1);
wallTri.Add(ind + 2);
wallTri.Add(ind + 1);
wallTri.Add(ind + 3);
wallTri.Add(ind + 2);
}
// TODO: Do we really need this?
if (_separateSubmesh)
{
md.Triangles.Add(wallTri);
}
else
{
md.Triangles.Capacity = md.Triangles.Count + wallTri.Count;
md.Triangles[0].AddRange(wallTri);
}
md.UV[0].AddRange(wallUv);
}
}
19
Source : LineMeshModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private void AddCurrentVertex(Vector3 vertexPosition, float dist, Vector3 normal, MeshData md, float endLeft = 0, float endRight = 0)
{
var triIndexStart = md.Vertices.Count;
var extrude = normal;
if (endLeft != 0)
{
extrude -= (normal.Perpendicular() * endLeft);
}
var vert = vertexPosition + extrude * _scaledWidth;
_vertexList.Add(vert);
_normalList.Add(Constants.Math.Vector3Up);
_uvList.Add(new Vector2(1, dist));
_tangentList.Add(normal.Perpendicular() * -1);
_index3 = triIndexStart + _vertexList.Count - 1;
if (_index1 >= triIndexStart && _index2 >= triIndexStart)
{
_triangleList.Add(_index1);
_triangleList.Add(_index3);
_triangleList.Add(_index2);
md.Edges.Add(triIndexStart + _vertexList.Count - 1);
md.Edges.Add(triIndexStart + _vertexList.Count - 3);
}
_index1 = _index2;
_index2 = _index3;
extrude = normal * -1;
if (endRight != 0)
{
extrude -= normal.Perpendicular() * endRight;
}
_vertexList.Add(vertexPosition + extrude * _scaledWidth);
_normalList.Add(Constants.Math.Vector3Up);
_uvList.Add(new Vector2(0, dist));
_tangentList.Add(normal.Perpendicular() * -1);
_index3 = triIndexStart + _vertexList.Count - 1;
if (_index1 >= triIndexStart && _index2 >= triIndexStart)
{
_triangleList.Add(_index1);
_triangleList.Add(_index2);
_triangleList.Add(_index3);
md.Edges.Add(triIndexStart + _vertexList.Count - 3);
md.Edges.Add(triIndexStart + _vertexList.Count - 1);
}
_index1 = _index2;
_index2 = _index3;
}
19
Source : UvModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
{
if (md.Vertices.Count == 0 || feature == null || feature.Points.Count < 1)
{
return;
}
_uv.Clear();
_mdVertexCount = md.Vertices.Count;
_size = md.TileRect.Size;
if (_options.texturingType != UvMapType.Atlas && _options.texturingType != UvMapType.AtlasWithColorPalette)
{
for (int i = 0; i < _mdVertexCount; i++)
{
_vert = md.Vertices[i];
if (_options.style == StyleTypes.Satellite)
{
var fromBottomLeft = new Vector2((float)(((_vert.x + md.PositionInTile.x) / tile.TileScale + _size.x / 2) / _size.x),
(float)(((_vert.z + md.PositionInTile.z) / tile.TileScale + _size.x / 2) / _size.x));
_uv.Add(fromBottomLeft);
}
else if (_options.texturingType == UvMapType.Tiled)
{
_uv.Add(new Vector2(_vert.x, _vert.z));
}
}
}
else if (_options.texturingType == UvMapType.Atlas || _options.texturingType == UvMapType.AtlasWithColorPalette)
{
_currentFacade = _options.atlasInfo.Roofs[UnityEngine.Random.Range(0, _options.atlasInfo.Roofs.Count)];
minx = float.MaxValue;
miny = float.MaxValue;
maxx = float.MinValue;
maxy = float.MinValue;
_textureUvCoordinates = new Vector2[_mdVertexCount];
_textureDirection = Quaternion.FromToRotation((md.Vertices[0] - md.Vertices[1]), Mapbox.Unity.Constants.Math.Vector3Right);
_textureUvCoordinates[0] = new Vector2(0, 0);
_firstVert = md.Vertices[0];
for (int i = 1; i < _mdVertexCount; i++)
{
_vert = md.Vertices[i];
_vertexRelativePos = _vert - _firstVert;
_vertexRelativePos = _textureDirection * _vertexRelativePos;
_textureUvCoordinates[i] = new Vector2(_vertexRelativePos.x, _vertexRelativePos.z);
if (_vertexRelativePos.x < minx)
minx = _vertexRelativePos.x;
if (_vertexRelativePos.x > maxx)
maxx = _vertexRelativePos.x;
if (_vertexRelativePos.z < miny)
miny = _vertexRelativePos.z;
if (_vertexRelativePos.z > maxy)
maxy = _vertexRelativePos.z;
}
var width = maxx - minx;
var height = maxy - miny;
for (int i = 0; i < _mdVertexCount; i++)
{
_uv.Add(new Vector2(
(((_textureUvCoordinates[i].x - minx) / width) * _currentFacade.TextureRect.width) + _currentFacade.TextureRect.x,
(((_textureUvCoordinates[i].y - miny) / height) * _currentFacade.TextureRect.height) + _currentFacade.TextureRect.y));
}
}
md.UV[0].AddRange(_uv);
}
19
Source : LineMeshModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private void AddPieSliceVertex(Vector3 vertexPosition, float dist, Vector3 normal, bool lineTurnsLeft, MeshData md)
{
var triIndexStart = md.Vertices.Count;
var extrude = normal * (lineTurnsLeft ? -1 : 1);
_vertexList.Add(vertexPosition + extrude * _scaledWidth);
_normalList.Add(Constants.Math.Vector3Up);
_uvList.Add(new Vector2(1, dist));
_tangentList.Add(normal.Perpendicular() * -1);
_index3 = triIndexStart + _vertexList.Count - 1;
if (_index1 >= 0 && _index2 >= 0)
{
_triangleList.Add(_index1);
_triangleList.Add(_index3);
_triangleList.Add(_index2);
if (!lineTurnsLeft)
{
md.Edges.Add(_index3);
md.Edges.Add(_index1);
}
else
{
md.Edges.Add(_index2);
md.Edges.Add(_index3);
}
}
if (lineTurnsLeft)
{
_index2 = _index3;
}
else
{
_index1 = _index3;
}
}
19
Source : ElevatedTerrainStrategy.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
private MeshDataArray CreateBaseMesh(UnityTile tile, int sampleCount)
{
//TODO use arrays instead of lists
_newVertexList.Clear();
_newNormalList.Clear();
_newUvList.Clear();
_newTriangleList.Clear();
for (float y = 0; y < sampleCount; y++)
{
var yrat = y / (sampleCount - 1);
for (float x = 0; x < sampleCount; x++)
{
var xrat = x / (sampleCount - 1);
var xx = Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, xrat);
var yy = Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, yrat);
_newVertexList.Add(new Vector3(
(float) (xx - tile.Rect.Center.x) * tile.TileScale,
0,
(float) (yy - tile.Rect.Center.y) * tile.TileScale));
_newNormalList.Add(Mapbox.Unity.Constants.Math.Vector3Up);
_newUvList.Add(new Vector2(x * 1f / (sampleCount - 1), 1 - (y * 1f / (sampleCount - 1))));
}
}
int vertA, vertB, vertC;
for (int y = 0; y < sampleCount - 1; y++)
{
for (int x = 0; x < sampleCount - 1; x++)
{
vertA = (y * sampleCount) + x;
vertB = (y * sampleCount) + x + sampleCount + 1;
vertC = (y * sampleCount) + x + sampleCount;
_newTriangleList.Add(vertA);
_newTriangleList.Add(vertB);
_newTriangleList.Add(vertC);
vertA = (y * sampleCount) + x;
vertB = (y * sampleCount) + x + 1;
vertC = (y * sampleCount) + x + sampleCount + 1;
_newTriangleList.Add(vertA);
_newTriangleList.Add(vertB);
_newTriangleList.Add(vertC);
}
}
var mesh = new MeshDataArray();
mesh.Vertices = _newVertexList.ToArray();
mesh.Normals = _newNormalList.ToArray();
mesh.Uvs = _newUvList.ToArray();
mesh.Triangles = _newTriangleList.ToArray();
return mesh;
}
19
Source : FlatSphereTerrainStrategy.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
void GenerateTerrainMesh(UnityTile tile)
{
var verts = new List<Vector3>();
var _sampleCount = _elevationOptions.modificationOptions.sampleCount;
var _radius = _elevationOptions.modificationOptions.earthRadius;
for (float x = 0; x < _sampleCount; x++)
{
for (float y = 0; y < _sampleCount; y++)
{
var xx = Mathf.Lerp((float)tile.Rect.Min.x, ((float)tile.Rect.Min.x + (float)tile.Rect.Size.x),
x / (_sampleCount - 1));
var yy = Mathf.Lerp((float)tile.Rect.Max.y, ((float)tile.Rect.Max.y + (float)tile.Rect.Size.y),
y / (_sampleCount - 1));
var ll = Conversions.MetersToLatLon(new Vector2d(xx, yy));
var lareplacedude = (float)(Mathf.Deg2Rad * ll.x);
var longitude = (float)(Mathf.Deg2Rad * ll.y);
float xPos = (_radius) * Mathf.Cos(lareplacedude) * Mathf.Cos(longitude);
float zPos = (_radius) * Mathf.Cos(lareplacedude) * Mathf.Sin(longitude);
float yPos = (_radius) * Mathf.Sin(lareplacedude);
var pp = new Vector3(xPos, yPos, zPos);
verts.Add(pp);
}
}
var trilist = new List<int>();
for (int y = 0; y < _sampleCount - 1; y++)
{
for (int x = 0; x < _sampleCount - 1; x++)
{
trilist.Add((y * _sampleCount) + x);
trilist.Add((y * _sampleCount) + x + _sampleCount + 1);
trilist.Add((y * _sampleCount) + x + _sampleCount);
trilist.Add((y * _sampleCount) + x);
trilist.Add((y * _sampleCount) + x + 1);
trilist.Add((y * _sampleCount) + x + _sampleCount + 1);
}
}
var uvlist = new List<Vector2>();
var step = 1f / (_sampleCount - 1);
for (int i = 0; i < _sampleCount; i++)
{
for (int j = 0; j < _sampleCount; j++)
{
uvlist.Add(new Vector2(i * step, (j * step)));
}
}
tile.MeshFilter.sharedMesh.SetVertices(verts);
tile.MeshFilter.sharedMesh.SetTriangles(trilist, 0);
tile.MeshFilter.sharedMesh.SetUVs(0, uvlist);
tile.MeshFilter.sharedMesh.RecalculateBounds();
tile.MeshFilter.sharedMesh.RecalculateNormals();
tile.transform.localPosition = Mapbox.Unity.Constants.Math.Vector3Zero;
}
19
Source : ChamferHeightModifier.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
public void Chamfer(VectorFeatureUnity feature, MeshData md, UnityTile tile = null)
{
if (md.Vertices.Count == 0 || feature.Points.Count < 1)
return;
List<Vector3> newVertices = new List<Vector3>();
List<Vector2> newUV = new List<Vector2>();
md.Normals.Clear();
md.Edges.Clear();
md.Tangents.Clear();
for (int t = 0; t < md.Triangles[0].Count; t++)
{
md.Triangles[0][t] *= 3;
}
var next = 0; var current = 0; var prev = 0;
Vector3 v1, v2, n1, n2, pij1, pij2, pjk1, pjk2;
Vector3 poi, close1, close2;
var start = 0;
for (int i = 0; i < feature.Points.Count; i++)
{
var count = feature.Points[i].Count;
var cst = newVertices.Count;
for (int j = 0; j < count; j++)
{
if (j == count - 1)
{
newVertices.Add(newVertices[cst]);
newVertices.Add(newVertices[cst + 1]);
newVertices.Add(newVertices[cst + 2]);
newUV.Add(newUV[cst]);
newUV.Add(newUV[cst + 1]);
newUV.Add(newUV[cst + 2]);
md.Normals.Add(md.Normals[cst]);
md.Normals.Add(md.Normals[cst + 1]);
md.Normals.Add(md.Normals[cst + 2]);
md.Tangents.Add(md.Tangents[cst]);
md.Tangents.Add(md.Tangents[cst + 1]);
md.Tangents.Add(md.Tangents[cst + 2]);
continue;
}
current = start + j;
if (j > 0)
next = start + j - 1;
else
next = start + j - 1 + count - 1; //another -1 as last item equals first
prev = start + j + 1;
v1 = new Vector3(
md.Vertices[current].x - md.Vertices[next].x, 0,
md.Vertices[current].z - md.Vertices[next].z);
v1.Normalize();
v1 *= -_offset;
n1 = new Vector3(-v1.z, 0, v1.x);
pij1 = new Vector3(
(float)(md.Vertices[next].x + n1.x), 0,
(float)(md.Vertices[next].z + n1.z));
pij2 = new Vector3(
(float)(md.Vertices[current].x + n1.x), 0,
(float)(md.Vertices[current].z + n1.z));
v2 = new Vector3(
md.Vertices[prev].x - md.Vertices[current].x, 0,
md.Vertices[prev].z - md.Vertices[current].z);
v2.Normalize();
v2 *= -_offset;
n2 = new Vector3(-v2.z, 0, v2.x);
pjk1 = new Vector3(
(float)(md.Vertices[current].x + n2.x), 0,
(float)(md.Vertices[current].z + n2.z));
pjk2 = new Vector3(
(float)(md.Vertices[prev].x + n2.x), 0,
(float)(md.Vertices[prev].z + n2.z));
// See where the shifted lines ij and jk intersect.
bool lines_intersect, segments_intersect;
FindIntersection(pij1, pij2, pjk1, pjk2,
out lines_intersect, out segments_intersect,
out poi, out close1, out close2);
var d = Vector3.Distance(poi, pij2);
if (d > 10 * _offset)
{
poi = new Vector3((md.Vertices[current].x + (poi - (-v1 - v2)).normalized.x), 0,
(md.Vertices[current].z + (poi - (-v1 - v2)).normalized.z));
}
newVertices.Add(new Vector3(poi.x, poi.y + _offset + md.Vertices[current].y, poi.z));
newVertices.Add(md.Vertices[current] + v1);
newVertices.Add(md.Vertices[current] - v2);
md.Normals.Add(Constants.Math.Vector3Up);
md.Normals.Add(-n1);
md.Normals.Add(-n2);
md.Tangents.Add(v1 - v2);
md.Tangents.Add(v1 - v2);
md.Tangents.Add(v1 - v2);
newUV.Add(md.UV[0][current]);
newUV.Add(md.UV[0][current]);
newUV.Add(md.UV[0][current]);
md.Triangles[0].Add(3 * current);
md.Triangles[0].Add(3 * current + 1);
md.Triangles[0].Add(3 * current + 2);
md.Edges.Add(3 * current + 2);
md.Edges.Add(3 * current + 1);
md.Triangles[0].Add(3 * prev);
md.Triangles[0].Add(3 * current + 2);
md.Triangles[0].Add(3 * prev + 1);
md.Triangles[0].Add(3 * current);
md.Triangles[0].Add(3 * current + 2);
md.Triangles[0].Add(3 * prev);
md.Edges.Add(3 * prev + 1);
md.Edges.Add(3 * current + 2);
}
start += count;
}
md.Vertices = newVertices;
md.UV[0] = newUV;
}
19
Source : TestGraph.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
void TestCurve()
{
DataGraph.GraphtList.Clear();
dataGraph.curves.Clear();
List<Vector2> data = new List<Vector2>();
data.Add(Vector2.zero);
dataGraph.AddDataSeries(data, Color.red, "HelloCurve");
}
19
Source : DataGraph.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
public void AddPointToExistingSeries(int curveID, Vector2 vect)
{
if (!pauseDataAppending)
{
curves[curveID].GetCurveDataBuffer().Add(vect);
}
}
19
Source : GraphSetter.cs
with GNU General Public License v3.0
from AlexandreDoucet
with GNU General Public License v3.0
from AlexandreDoucet
void CreateCurve()
{
List<Vector2> data = new List<Vector2>();
data.Add(Vector2.zero);
curveID = dataGraph.AddDataSeries(data, Color.red, "PowerCurve");
}
19
Source : MeshSplitter.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
private void Add( Vector3 v, Vector2 uv )
{
var index = Add( v );
if ( index >= m_uvs.Count ) {
Debug.replacedert( index == m_uvs.Count,
$"Vertex index = {index}, UV count = {m_uvs.Count}" );
m_uvs.Add( uv );
}
}
See More Examples