Keeping logic within microservice boundaries
Deploy Promiscuity Auth API / deploy (push) Successful in 45s
Deploy Promiscuity Character API / deploy (push) Successful in 57s
Deploy Promiscuity Inventory API / deploy (push) Successful in 45s
Deploy Promiscuity Locations API / deploy (push) Successful in 58s
k8s smoke test / test (push) Successful in 8s
Deploy Promiscuity Auth API / deploy (push) Successful in 45s
Deploy Promiscuity Character API / deploy (push) Successful in 57s
Deploy Promiscuity Inventory API / deploy (push) Successful in 45s
Deploy Promiscuity Locations API / deploy (push) Successful in 58s
k8s smoke test / test (push) Successful in 8s
This commit is contained in:
@@ -60,6 +60,68 @@ public class LocationsController : ControllerBase
|
||||
return Ok(location);
|
||||
}
|
||||
|
||||
[HttpGet("biome-definitions")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> ListBiomeDefinitions()
|
||||
{
|
||||
var definitions = await _locations.GetBiomeDefinitionsAsync();
|
||||
return Ok(definitions);
|
||||
}
|
||||
|
||||
[HttpGet("biome-definitions/{biomeKey}")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> GetBiomeDefinition(string biomeKey)
|
||||
{
|
||||
var normalizedBiomeKey = NormalizeBiomeKey(biomeKey);
|
||||
if (string.IsNullOrWhiteSpace(normalizedBiomeKey))
|
||||
return BadRequest("biomeKey required");
|
||||
|
||||
var definition = await _locations.GetBiomeDefinitionAsync(normalizedBiomeKey);
|
||||
return definition is null ? NotFound() : Ok(definition);
|
||||
}
|
||||
|
||||
[HttpPost("internal/visible-window")]
|
||||
public async Task<IActionResult> GetVisibleWindow([FromBody] InternalVisibleLocationsRequest req)
|
||||
{
|
||||
var configuredKey = (_configuration["InternalApi:Key"] ?? _configuration["Jwt:Key"] ?? string.Empty).Trim();
|
||||
var requestKey = (Request.Headers["X-Internal-Api-Key"].FirstOrDefault() ?? string.Empty).Trim();
|
||||
if (string.IsNullOrWhiteSpace(configuredKey) || !string.Equals(configuredKey, requestKey, StringComparison.Ordinal))
|
||||
return Unauthorized();
|
||||
if (req.Radius < 0)
|
||||
return BadRequest("radius must be non-negative");
|
||||
|
||||
var result = await _locations.GetOrCreateVisibleLocationsAsync(req.X, req.Y, req.Radius);
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpPost("biome-definitions/{biomeKey}")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> CreateBiomeDefinition(string biomeKey, [FromBody] UpsertBiomeDefinitionRequest req)
|
||||
{
|
||||
var validationError = ValidateBiomeDefinitionRequest(biomeKey, req);
|
||||
if (validationError is not null)
|
||||
return validationError;
|
||||
|
||||
var definition = BuildBiomeDefinition(biomeKey, req);
|
||||
var created = await _locations.CreateBiomeDefinitionAsync(definition);
|
||||
if (!created)
|
||||
return Conflict("Biome definition already exists");
|
||||
|
||||
return Ok(definition);
|
||||
}
|
||||
|
||||
[HttpPut("biome-definitions/{biomeKey}")]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> UpsertBiomeDefinition(string biomeKey, [FromBody] UpsertBiomeDefinitionRequest req)
|
||||
{
|
||||
var validationError = ValidateBiomeDefinitionRequest(biomeKey, req);
|
||||
if (validationError is not null)
|
||||
return validationError;
|
||||
|
||||
var definition = await _locations.UpsertBiomeDefinitionAsync(biomeKey, req);
|
||||
return Ok(definition);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize(Roles = "SUPER")]
|
||||
public async Task<IActionResult> ListMine()
|
||||
@@ -254,4 +316,55 @@ public class LocationsController : ControllerBase
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private IActionResult? ValidateBiomeDefinitionRequest(string biomeKey, UpsertBiomeDefinitionRequest req)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(NormalizeBiomeKey(biomeKey)))
|
||||
return BadRequest("biomeKey required");
|
||||
if (req.ContinuationWeight < 0)
|
||||
return BadRequest("continuationWeight must be non-negative");
|
||||
if (req.TransitionWeights.Any(weight => string.IsNullOrWhiteSpace(weight.TargetBiomeKey)))
|
||||
return BadRequest("transitionWeights require targetBiomeKey");
|
||||
if (req.TransitionWeights.Any(weight => weight.Weight < 0))
|
||||
return BadRequest("transitionWeights weight must be non-negative");
|
||||
if (req.ObjectSpawnRules.Count == 0)
|
||||
return BadRequest("objectSpawnRules required");
|
||||
if (req.ObjectSpawnRules.Any(rule => rule.Weight < 0))
|
||||
return BadRequest("objectSpawnRules weight must be non-negative");
|
||||
if (req.ObjectSpawnRules.Any(rule => string.IsNullOrWhiteSpace(rule.ResultType)))
|
||||
return BadRequest("objectSpawnRules resultType required");
|
||||
if (req.ObjectSpawnRules.Any(rule =>
|
||||
string.Equals(rule.ResultType, "gatherable", StringComparison.OrdinalIgnoreCase) &&
|
||||
string.IsNullOrWhiteSpace(rule.ItemKey)))
|
||||
return BadRequest("gatherable objectSpawnRules require itemKey");
|
||||
return null;
|
||||
}
|
||||
|
||||
private static BiomeDefinition BuildBiomeDefinition(string biomeKey, UpsertBiomeDefinitionRequest req)
|
||||
{
|
||||
var normalizedBiomeKey = NormalizeBiomeKey(biomeKey);
|
||||
return new BiomeDefinition
|
||||
{
|
||||
BiomeKey = normalizedBiomeKey,
|
||||
ContinuationWeight = req.ContinuationWeight,
|
||||
TransitionWeights = req.TransitionWeights.Select(weight => new BiomeTransitionWeight
|
||||
{
|
||||
TargetBiomeKey = NormalizeBiomeKey(weight.TargetBiomeKey),
|
||||
Weight = weight.Weight
|
||||
}).ToList(),
|
||||
ObjectSpawnRules = req.ObjectSpawnRules.Select(rule => new BiomeObjectSpawnRule
|
||||
{
|
||||
ResultType = rule.ResultType.Trim().ToLowerInvariant(),
|
||||
ItemKey = string.IsNullOrWhiteSpace(rule.ItemKey) ? null : rule.ItemKey.Trim().ToLowerInvariant(),
|
||||
ObjectKey = string.IsNullOrWhiteSpace(rule.ObjectKey) ? null : rule.ObjectKey.Trim(),
|
||||
DisplayName = string.IsNullOrWhiteSpace(rule.DisplayName) ? null : rule.DisplayName.Trim(),
|
||||
RemainingQuantity = rule.RemainingQuantity,
|
||||
GatherQuantity = rule.GatherQuantity,
|
||||
Weight = rule.Weight
|
||||
}).ToList(),
|
||||
UpdatedUtc = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
private static string NormalizeBiomeKey(string biomeKey) => biomeKey.Trim().ToLowerInvariant();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
[BsonIgnoreExtraElements]
|
||||
public class BiomeDefinition
|
||||
{
|
||||
[BsonId]
|
||||
[BsonElement("biomeKey")]
|
||||
public string BiomeKey { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("continuationWeight")]
|
||||
public double ContinuationWeight { get; set; }
|
||||
|
||||
[BsonElement("transitionWeights")]
|
||||
public List<BiomeTransitionWeight> TransitionWeights { get; set; } = [];
|
||||
|
||||
[BsonElement("objectSpawnRules")]
|
||||
public List<BiomeObjectSpawnRule> ObjectSpawnRules { get; set; } = [];
|
||||
|
||||
[BsonElement("updatedUtc")]
|
||||
public DateTime UpdatedUtc { get; set; } = DateTime.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class BiomeObjectSpawnRule
|
||||
{
|
||||
[BsonElement("resultType")]
|
||||
public string ResultType { get; set; } = "none";
|
||||
|
||||
[BsonElement("itemKey")]
|
||||
[BsonIgnoreIfNull]
|
||||
public string? ItemKey { get; set; }
|
||||
|
||||
[BsonElement("objectKey")]
|
||||
[BsonIgnoreIfNull]
|
||||
public string? ObjectKey { get; set; }
|
||||
|
||||
[BsonElement("displayName")]
|
||||
[BsonIgnoreIfNull]
|
||||
public string? DisplayName { get; set; }
|
||||
|
||||
[BsonElement("remainingQuantity")]
|
||||
public int RemainingQuantity { get; set; }
|
||||
|
||||
[BsonElement("gatherQuantity")]
|
||||
public int GatherQuantity { get; set; } = 1;
|
||||
|
||||
[BsonElement("weight")]
|
||||
public double Weight { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using MongoDB.Bson.Serialization.Attributes;
|
||||
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class BiomeTransitionWeight
|
||||
{
|
||||
[BsonElement("targetBiomeKey")]
|
||||
public string TargetBiomeKey { get; set; } = string.Empty;
|
||||
|
||||
[BsonElement("weight")]
|
||||
public double Weight { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class InternalVisibleLocationsRequest
|
||||
{
|
||||
public int X { get; set; }
|
||||
|
||||
public int Y { get; set; }
|
||||
|
||||
public int Radius { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class UpsertBiomeDefinitionRequest
|
||||
{
|
||||
public double ContinuationWeight { get; set; }
|
||||
|
||||
public List<BiomeTransitionWeight> TransitionWeights { get; set; } = [];
|
||||
|
||||
public List<BiomeObjectSpawnRule> ObjectSpawnRules { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class VisibleLocationObjectResponse
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
public string ObjectType { get; set; } = string.Empty;
|
||||
|
||||
public string ObjectKey { get; set; } = string.Empty;
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public VisibleLocationObjectStateResponse State { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class VisibleLocationObjectStateResponse
|
||||
{
|
||||
public string ItemKey { get; set; } = string.Empty;
|
||||
|
||||
public int RemainingQuantity { get; set; }
|
||||
|
||||
public int GatherQuantity { get; set; } = 1;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class VisibleLocationResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public Coord Coord { get; set; } = new();
|
||||
|
||||
public string BiomeKey { get; set; } = "plains";
|
||||
|
||||
public VisibleLocationObjectResponse? LocationObject { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LocationsApi.Models;
|
||||
|
||||
public class VisibleLocationWindowResponse
|
||||
{
|
||||
public int GeneratedCount { get; set; }
|
||||
|
||||
public List<VisibleLocationResponse> Locations { get; set; } = [];
|
||||
}
|
||||
@@ -9,6 +9,7 @@ public class LocationStore
|
||||
private readonly IMongoCollection<Location> _col;
|
||||
private readonly IMongoCollection<BsonDocument> _rawCol;
|
||||
private readonly IMongoCollection<CharacterDocument> _characters;
|
||||
private readonly IMongoCollection<BiomeDefinition> _biomeDefinitions;
|
||||
private const string CoordIndexName = "coord_x_1_coord_y_1";
|
||||
|
||||
public LocationStore(IConfiguration cfg)
|
||||
@@ -22,6 +23,7 @@ public class LocationStore
|
||||
_col = db.GetCollection<Location>(collectionName);
|
||||
_rawCol = db.GetCollection<BsonDocument>(collectionName);
|
||||
_characters = db.GetCollection<CharacterDocument>("Characters");
|
||||
_biomeDefinitions = db.GetCollection<BiomeDefinition>("BiomeDefinitions");
|
||||
|
||||
EnsureCoordIndexes();
|
||||
|
||||
@@ -232,6 +234,61 @@ public class LocationStore
|
||||
await _col.UpdateOneAsync(filter, update);
|
||||
}
|
||||
|
||||
public async Task<VisibleLocationWindowResponse> GetOrCreateVisibleLocationsAsync(int x, int y, int radius)
|
||||
{
|
||||
var generatedCount = await EnsureVisibleLocationsExistAsync(x, y, radius);
|
||||
var locations = await GetVisibleLocationsAsync(x, y, radius, ensureMetadata: true);
|
||||
return new VisibleLocationWindowResponse
|
||||
{
|
||||
GeneratedCount = generatedCount,
|
||||
Locations = locations
|
||||
};
|
||||
}
|
||||
|
||||
public Task<List<BiomeDefinition>> GetBiomeDefinitionsAsync() =>
|
||||
_biomeDefinitions.Find(Builders<BiomeDefinition>.Filter.Empty)
|
||||
.SortBy(definition => definition.BiomeKey)
|
||||
.ToListAsync();
|
||||
|
||||
public async Task<BiomeDefinition?> GetBiomeDefinitionAsync(string biomeKey)
|
||||
{
|
||||
var normalizedBiomeKey = NormalizeBiomeKey(biomeKey);
|
||||
return await _biomeDefinitions.Find(definition => definition.BiomeKey == normalizedBiomeKey)
|
||||
.FirstOrDefaultAsync();
|
||||
}
|
||||
|
||||
public async Task<bool> CreateBiomeDefinitionAsync(BiomeDefinition definition)
|
||||
{
|
||||
definition.BiomeKey = NormalizeBiomeKey(definition.BiomeKey);
|
||||
definition.TransitionWeights = NormalizeTransitionWeights(definition.TransitionWeights);
|
||||
definition.ObjectSpawnRules = NormalizeObjectSpawnRules(definition.ObjectSpawnRules);
|
||||
definition.UpdatedUtc = DateTime.UtcNow;
|
||||
|
||||
var existing = await GetBiomeDefinitionAsync(definition.BiomeKey);
|
||||
if (existing is not null)
|
||||
return false;
|
||||
|
||||
await _biomeDefinitions.InsertOneAsync(definition);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<BiomeDefinition> UpsertBiomeDefinitionAsync(string biomeKey, UpsertBiomeDefinitionRequest request)
|
||||
{
|
||||
var normalizedBiomeKey = NormalizeBiomeKey(biomeKey);
|
||||
var definition = new BiomeDefinition
|
||||
{
|
||||
BiomeKey = normalizedBiomeKey,
|
||||
ContinuationWeight = request.ContinuationWeight,
|
||||
TransitionWeights = NormalizeTransitionWeights(request.TransitionWeights),
|
||||
ObjectSpawnRules = NormalizeObjectSpawnRules(request.ObjectSpawnRules),
|
||||
UpdatedUtc = DateTime.UtcNow
|
||||
};
|
||||
|
||||
var filter = Builders<BiomeDefinition>.Filter.Eq(existing => existing.BiomeKey, normalizedBiomeKey);
|
||||
await _biomeDefinitions.ReplaceOneAsync(filter, definition, new ReplaceOptions { IsUpsert = true });
|
||||
return definition;
|
||||
}
|
||||
|
||||
private void EnsureCoordIndexes()
|
||||
{
|
||||
var indexes = _rawCol.Indexes.List().ToList();
|
||||
@@ -271,6 +328,13 @@ public class LocationStore
|
||||
|
||||
private void EnsureOriginLocation()
|
||||
{
|
||||
var biomeDefinitions = LoadBiomeDefinitions();
|
||||
if (biomeDefinitions.Count == 0)
|
||||
return;
|
||||
|
||||
var originBiomeKey = biomeDefinitions.Any(definition => definition.BiomeKey == "plains")
|
||||
? "plains"
|
||||
: biomeDefinitions[0].BiomeKey;
|
||||
var filter = Builders<Location>.Filter.And(
|
||||
Builders<Location>.Filter.Eq(l => l.Coord.X, 0),
|
||||
Builders<Location>.Filter.Eq(l => l.Coord.Y, 0)
|
||||
@@ -283,8 +347,8 @@ public class LocationStore
|
||||
{
|
||||
Name = "Origin",
|
||||
Coord = new Coord { X = 0, Y = 0 },
|
||||
BiomeKey = DetermineBiomeKey(0, 0),
|
||||
LocationObject = CreateLocationObjectForBiome(DetermineBiomeKey(0, 0), 0, 0),
|
||||
BiomeKey = originBiomeKey,
|
||||
LocationObject = CreateLocationObjectForBiome(biomeDefinitions, originBiomeKey, 0, 0),
|
||||
LocationObjectResolved = true,
|
||||
CreatedUtc = DateTime.UtcNow
|
||||
};
|
||||
@@ -301,16 +365,97 @@ public class LocationStore
|
||||
|
||||
private static string NormalizeItemKey(string itemKey) => itemKey.Trim().ToLowerInvariant();
|
||||
|
||||
private async Task<List<VisibleLocationResponse>> GetVisibleLocationsAsync(int x, int y, int radius, bool ensureMetadata)
|
||||
{
|
||||
var minX = x - radius;
|
||||
var maxX = x + radius;
|
||||
var minY = y - radius;
|
||||
var maxY = y + radius;
|
||||
|
||||
var filter = Builders<Location>.Filter.And(
|
||||
Builders<Location>.Filter.Gte(location => location.Coord.X, minX),
|
||||
Builders<Location>.Filter.Lte(location => location.Coord.X, maxX),
|
||||
Builders<Location>.Filter.Gte(location => location.Coord.Y, minY),
|
||||
Builders<Location>.Filter.Lte(location => location.Coord.Y, maxY)
|
||||
);
|
||||
|
||||
var locations = await _col.Find(filter).ToListAsync();
|
||||
if (ensureMetadata)
|
||||
{
|
||||
for (var index = 0; index < locations.Count; index++)
|
||||
locations[index] = await EnsureLocationMetadataAsync(locations[index]);
|
||||
}
|
||||
|
||||
return locations.Select(MapVisibleLocation).ToList();
|
||||
}
|
||||
|
||||
private async Task<int> EnsureVisibleLocationsExistAsync(int x, int y, int radius)
|
||||
{
|
||||
var biomeDefinitions = await LoadBiomeDefinitionsAsync();
|
||||
var generatedCount = 0;
|
||||
|
||||
for (var currentX = x - radius; currentX <= x + radius; currentX++)
|
||||
{
|
||||
for (var currentY = y - radius; currentY <= y + radius; currentY++)
|
||||
{
|
||||
if (await EnsureLocationStateAsync(currentX, currentY, biomeDefinitions))
|
||||
generatedCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return generatedCount;
|
||||
}
|
||||
|
||||
private async Task<bool> EnsureLocationStateAsync(int x, int y, IReadOnlyList<BiomeDefinition> biomeDefinitions)
|
||||
{
|
||||
var filter = Builders<BsonDocument>.Filter.And(
|
||||
Builders<BsonDocument>.Filter.Eq("coord.x", x),
|
||||
Builders<BsonDocument>.Filter.Eq("coord.y", y)
|
||||
);
|
||||
|
||||
var existing = await _rawCol.Find(filter).FirstOrDefaultAsync();
|
||||
if (existing is not null)
|
||||
{
|
||||
var typedLocation = await _col.Find(location => location.Id == existing["_id"].AsObjectId.ToString()).FirstOrDefaultAsync();
|
||||
if (typedLocation is not null)
|
||||
await EnsureLocationMetadataAsync(typedLocation);
|
||||
return false;
|
||||
}
|
||||
|
||||
var biomeKey = await DetermineBiomeKeyAsync(x, y, biomeDefinitions);
|
||||
var locationObject = CreateLocationObjectForBiome(biomeDefinitions, biomeKey, x, y);
|
||||
BsonValue locationObjectValue = locationObject is null ? BsonNull.Value : locationObject.ToBsonDocument();
|
||||
var update = Builders<BsonDocument>.Update
|
||||
.SetOnInsert("_id", ObjectId.GenerateNewId())
|
||||
.SetOnInsert("name", DefaultLocationName(x, y))
|
||||
.SetOnInsert("coord", new BsonDocument { { "x", x }, { "y", y } })
|
||||
.SetOnInsert("biomeKey", biomeKey)
|
||||
.SetOnInsert("locationObject", locationObjectValue)
|
||||
.SetOnInsert("locationObjectResolved", true)
|
||||
.SetOnInsert("createdUtc", DateTime.UtcNow);
|
||||
|
||||
try
|
||||
{
|
||||
var result = await _rawCol.UpdateOneAsync(filter, update, new UpdateOptions { IsUpsert = true });
|
||||
return result.UpsertedId is not null;
|
||||
}
|
||||
catch (MongoWriteException ex) when (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Location> EnsureLocationMetadataAsync(Location location)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(location.BiomeKey) && location.LocationObjectResolved)
|
||||
return location;
|
||||
|
||||
var biomeDefinitions = await LoadBiomeDefinitionsAsync();
|
||||
var biomeKey = location.BiomeKey;
|
||||
if (string.IsNullOrWhiteSpace(biomeKey))
|
||||
biomeKey = DetermineBiomeKey(location.Coord.X, location.Coord.Y);
|
||||
biomeKey = await DetermineBiomeKeyAsync(location.Coord.X, location.Coord.Y, biomeDefinitions);
|
||||
|
||||
var migratedObject = TryMigrateLegacyResources(location) ?? CreateLocationObjectForBiome(biomeKey, location.Coord.X, location.Coord.Y);
|
||||
var migratedObject = TryMigrateLegacyResources(location) ?? CreateLocationObjectForBiome(biomeDefinitions, biomeKey, location.Coord.X, location.Coord.Y);
|
||||
var filter = Builders<Location>.Filter.And(
|
||||
Builders<Location>.Filter.Eq(l => l.Id, location.Id)
|
||||
);
|
||||
@@ -325,6 +470,38 @@ public class LocationStore
|
||||
return location;
|
||||
}
|
||||
|
||||
private static VisibleLocationResponse MapVisibleLocation(Location location)
|
||||
{
|
||||
return new VisibleLocationResponse
|
||||
{
|
||||
Id = location.Id,
|
||||
Name = location.Name,
|
||||
Coord = new Coord { X = location.Coord.X, Y = location.Coord.Y },
|
||||
BiomeKey = location.BiomeKey,
|
||||
LocationObject = MapVisibleLocationObject(location.LocationObject)
|
||||
};
|
||||
}
|
||||
|
||||
private static VisibleLocationObjectResponse? MapVisibleLocationObject(LocationObject? locationObject)
|
||||
{
|
||||
if (locationObject is null)
|
||||
return null;
|
||||
|
||||
return new VisibleLocationObjectResponse
|
||||
{
|
||||
Id = locationObject.ObjectId,
|
||||
ObjectType = locationObject.ObjectType,
|
||||
ObjectKey = locationObject.ObjectKey,
|
||||
Name = locationObject.Name,
|
||||
State = new VisibleLocationObjectStateResponse
|
||||
{
|
||||
ItemKey = locationObject.State.ItemKey,
|
||||
RemainingQuantity = locationObject.State.RemainingQuantity,
|
||||
GatherQuantity = locationObject.State.GatherQuantity
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static LocationObject? TryMigrateLegacyResources(Location location)
|
||||
{
|
||||
var legacyResource = location.Resources.FirstOrDefault(r => r.RemainingQuantity > 0);
|
||||
@@ -337,73 +514,105 @@ public class LocationStore
|
||||
legacyResource.GatherQuantity);
|
||||
}
|
||||
|
||||
private static string DetermineBiomeKey(int x, int y)
|
||||
private async Task<string> DetermineBiomeKeyAsync(int x, int y, IReadOnlyList<BiomeDefinition> biomeDefinitions)
|
||||
{
|
||||
if (x == 0 && y == 0)
|
||||
return "plains";
|
||||
return biomeDefinitions.Any(definition => definition.BiomeKey == "plains")
|
||||
? "plains"
|
||||
: biomeDefinitions[0].BiomeKey;
|
||||
|
||||
var regionX = FloorDiv(x, 4);
|
||||
var regionY = FloorDiv(y, 4);
|
||||
var roll = Math.Abs(HashCode.Combine(regionX, regionY, 7919)) % 100;
|
||||
if (roll < 35)
|
||||
return "plains";
|
||||
if (roll < 60)
|
||||
return "forest";
|
||||
if (roll < 80)
|
||||
return "rocky";
|
||||
if (roll < 92)
|
||||
return "wetlands";
|
||||
return "desert";
|
||||
}
|
||||
var neighbors = await LoadNeighborBiomeKeysAsync(x, y);
|
||||
var baseBiome = DetermineBaseBiomeKey(x, y);
|
||||
if (neighbors.Count == 0)
|
||||
return biomeDefinitions.Any(definition => definition.BiomeKey == baseBiome)
|
||||
? baseBiome
|
||||
: biomeDefinitions[0].BiomeKey;
|
||||
|
||||
private static LocationObject? CreateLocationObjectForBiome(string biomeKey, int x, int y)
|
||||
{
|
||||
var roll = Math.Abs(HashCode.Combine(x, y, 1543)) % 100;
|
||||
return biomeKey switch
|
||||
var dominantNeighbor = neighbors
|
||||
.GroupBy(key => key)
|
||||
.OrderByDescending(group => group.Count())
|
||||
.ThenBy(group => group.Key)
|
||||
.First().Key;
|
||||
|
||||
var bestBiome = baseBiome;
|
||||
var bestScore = double.NegativeInfinity;
|
||||
foreach (var candidate in biomeDefinitions)
|
||||
{
|
||||
"forest" => roll switch
|
||||
var score = candidate.BiomeKey == baseBiome ? 2.5 : 0.35;
|
||||
if (candidate.BiomeKey == dominantNeighbor)
|
||||
score += 1.8;
|
||||
|
||||
foreach (var neighbor in neighbors)
|
||||
{
|
||||
< 35 => null,
|
||||
< 80 => CreateGatherableObject("wood", 60, 3),
|
||||
< 95 => CreateGatherableObject("grass", 120, 10),
|
||||
_ => CreateGatherableObject("stone", 40, 2)
|
||||
},
|
||||
"rocky" => roll switch
|
||||
{
|
||||
< 60 => null,
|
||||
< 90 => CreateGatherableObject("stone", 40, 2),
|
||||
_ => CreateGatherableObject("wood", 60, 3)
|
||||
},
|
||||
"wetlands" => roll switch
|
||||
{
|
||||
< 40 => null,
|
||||
< 90 => CreateGatherableObject("grass", 120, 10),
|
||||
_ => CreateGatherableObject("wood", 60, 3)
|
||||
},
|
||||
"desert" => roll switch
|
||||
{
|
||||
< 70 => null,
|
||||
< 95 => CreateGatherableObject("stone", 40, 2),
|
||||
_ => CreateGatherableObject("wood", 60, 3)
|
||||
},
|
||||
_ => roll switch
|
||||
{
|
||||
< 50 => null,
|
||||
< 85 => CreateGatherableObject("grass", 120, 10),
|
||||
_ => CreateGatherableObject("wood", 60, 3)
|
||||
var neighborDefinition = biomeDefinitions.FirstOrDefault(definition => definition.BiomeKey == neighbor);
|
||||
if (neighborDefinition is null)
|
||||
continue;
|
||||
|
||||
if (candidate.BiomeKey == neighbor)
|
||||
{
|
||||
score += neighborDefinition.ContinuationWeight;
|
||||
continue;
|
||||
}
|
||||
|
||||
var transition = neighborDefinition.TransitionWeights
|
||||
.FirstOrDefault(weight => weight.TargetBiomeKey == candidate.BiomeKey);
|
||||
if (transition is not null)
|
||||
score += transition.Weight;
|
||||
}
|
||||
};
|
||||
|
||||
score += StableNoise(x, y, StableHash(candidate.BiomeKey)) * 0.25;
|
||||
if (score > bestScore)
|
||||
{
|
||||
bestScore = score;
|
||||
bestBiome = candidate.BiomeKey;
|
||||
}
|
||||
}
|
||||
|
||||
return bestBiome;
|
||||
}
|
||||
|
||||
private static LocationObject CreateGatherableObject(string itemKey, int remainingQuantity, int gatherQuantity)
|
||||
private static LocationObject? CreateLocationObjectForBiome(IReadOnlyList<BiomeDefinition> biomeDefinitions, string biomeKey, int x, int y)
|
||||
{
|
||||
var biome = biomeDefinitions.FirstOrDefault(definition => definition.BiomeKey == biomeKey)
|
||||
?? throw new InvalidOperationException($"Missing biome definition for '{biomeKey}'.");
|
||||
|
||||
var totalWeight = biome.ObjectSpawnRules.Sum(rule => rule.Weight);
|
||||
if (totalWeight <= 0)
|
||||
return null;
|
||||
|
||||
var roll = StableNoise(x, y, 401) * totalWeight;
|
||||
var cumulative = 0.0;
|
||||
foreach (var rule in biome.ObjectSpawnRules)
|
||||
{
|
||||
cumulative += rule.Weight;
|
||||
if (roll > cumulative)
|
||||
continue;
|
||||
|
||||
if (string.Equals(rule.ResultType, "none", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
if (!string.Equals(rule.ResultType, "gatherable", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(rule.ItemKey))
|
||||
return null;
|
||||
|
||||
return CreateGatherableObject(
|
||||
rule.ItemKey,
|
||||
Math.Max(0, rule.RemainingQuantity),
|
||||
Math.Max(1, rule.GatherQuantity),
|
||||
rule.ObjectKey,
|
||||
rule.DisplayName);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static LocationObject CreateGatherableObject(string itemKey, int remainingQuantity, int gatherQuantity, string? objectKey = null, string? displayName = null)
|
||||
{
|
||||
var normalizedItemKey = NormalizeItemKey(itemKey);
|
||||
return new LocationObject
|
||||
{
|
||||
ObjectId = Guid.NewGuid().ToString("N"),
|
||||
ObjectType = "gatherable",
|
||||
ObjectKey = $"{normalizedItemKey}_node",
|
||||
Name = HumanizeItemKey(normalizedItemKey),
|
||||
ObjectKey = string.IsNullOrWhiteSpace(objectKey) ? $"{normalizedItemKey}_node" : objectKey,
|
||||
Name = string.IsNullOrWhiteSpace(displayName) ? HumanizeItemKey(normalizedItemKey) : displayName,
|
||||
State = new LocationObjectState
|
||||
{
|
||||
ItemKey = normalizedItemKey,
|
||||
@@ -428,6 +637,110 @@ public class LocationStore
|
||||
return quotient;
|
||||
}
|
||||
|
||||
private async Task<List<string>> LoadNeighborBiomeKeysAsync(int x, int y)
|
||||
{
|
||||
var coords = new[] { (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1) };
|
||||
var filters = coords.Select(coord =>
|
||||
Builders<BsonDocument>.Filter.And(
|
||||
Builders<BsonDocument>.Filter.Eq("coord.x", coord.Item1),
|
||||
Builders<BsonDocument>.Filter.Eq("coord.y", coord.Item2)))
|
||||
.ToList();
|
||||
var filter = Builders<BsonDocument>.Filter.Or(filters);
|
||||
var neighbors = await _rawCol.Find(filter).ToListAsync();
|
||||
|
||||
return neighbors
|
||||
.Where(doc => doc.Contains("biomeKey"))
|
||||
.Select(doc => doc.GetValue("biomeKey", "").AsString)
|
||||
.Where(key => !string.IsNullOrWhiteSpace(key))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private List<BiomeDefinition> LoadBiomeDefinitions()
|
||||
{
|
||||
return _biomeDefinitions.Find(Builders<BiomeDefinition>.Filter.Empty)
|
||||
.SortBy(definition => definition.BiomeKey)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private async Task<List<BiomeDefinition>> LoadBiomeDefinitionsAsync()
|
||||
{
|
||||
var definitions = await _biomeDefinitions.Find(Builders<BiomeDefinition>.Filter.Empty)
|
||||
.SortBy(definition => definition.BiomeKey)
|
||||
.ToListAsync();
|
||||
if (definitions.Count == 0)
|
||||
throw new InvalidOperationException("No biome definitions exist in the BiomeDefinitions collection.");
|
||||
return definitions;
|
||||
}
|
||||
|
||||
private static string DetermineBaseBiomeKey(int x, int y)
|
||||
{
|
||||
var temperature = StableNoise(x, y, 101);
|
||||
var moisture = StableNoise(x, y, 202);
|
||||
var ruggedness = StableNoise(x, y, 303);
|
||||
|
||||
if (ruggedness > 0.74)
|
||||
return "rocky";
|
||||
if (moisture > 0.72 && temperature < 0.75)
|
||||
return "wetlands";
|
||||
if (moisture > 0.56)
|
||||
return "forest";
|
||||
if (moisture < 0.22 && temperature > 0.58)
|
||||
return "desert";
|
||||
return "plains";
|
||||
}
|
||||
|
||||
private static double StableNoise(int x, int y, int salt)
|
||||
{
|
||||
var value = Math.Sin((x * 12.9898) + (y * 78.233) + ((1729 + salt) * 0.1597)) * 43758.5453;
|
||||
return value - Math.Floor(value);
|
||||
}
|
||||
|
||||
private static int StableHash(string value)
|
||||
{
|
||||
unchecked
|
||||
{
|
||||
var hash = 17;
|
||||
foreach (var ch in value)
|
||||
hash = (hash * 31) + ch;
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
|
||||
private static string NormalizeBiomeKey(string biomeKey) => biomeKey.Trim().ToLowerInvariant();
|
||||
|
||||
private static List<BiomeTransitionWeight> NormalizeTransitionWeights(IEnumerable<BiomeTransitionWeight> transitionWeights)
|
||||
{
|
||||
return transitionWeights
|
||||
.Where(weight => !string.IsNullOrWhiteSpace(weight.TargetBiomeKey))
|
||||
.Select(weight => new BiomeTransitionWeight
|
||||
{
|
||||
TargetBiomeKey = NormalizeBiomeKey(weight.TargetBiomeKey),
|
||||
Weight = weight.Weight
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static List<BiomeObjectSpawnRule> NormalizeObjectSpawnRules(IEnumerable<BiomeObjectSpawnRule> objectSpawnRules)
|
||||
{
|
||||
return objectSpawnRules.Select(rule => new BiomeObjectSpawnRule
|
||||
{
|
||||
ResultType = string.IsNullOrWhiteSpace(rule.ResultType) ? "none" : rule.ResultType.Trim().ToLowerInvariant(),
|
||||
ItemKey = string.IsNullOrWhiteSpace(rule.ItemKey) ? null : NormalizeItemKey(rule.ItemKey),
|
||||
ObjectKey = string.IsNullOrWhiteSpace(rule.ObjectKey) ? null : rule.ObjectKey.Trim(),
|
||||
DisplayName = string.IsNullOrWhiteSpace(rule.DisplayName) ? null : rule.DisplayName.Trim(),
|
||||
RemainingQuantity = rule.RemainingQuantity,
|
||||
GatherQuantity = rule.GatherQuantity,
|
||||
Weight = rule.Weight
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static string DefaultLocationName(int x, int y)
|
||||
{
|
||||
if (x == 0 && y == 0)
|
||||
return "Origin";
|
||||
return $"Location {x},{y}";
|
||||
}
|
||||
|
||||
private static LocationObject CloneLocationObject(LocationObject source)
|
||||
{
|
||||
return new LocationObject
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
"Services": {
|
||||
"InventoryApiBaseUrl": "http://localhost:5003"
|
||||
},
|
||||
"InternalApi": {
|
||||
"Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5002" } } },
|
||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||
"Services": { "InventoryApiBaseUrl": "https://pinv.ranaze.com" },
|
||||
"InternalApi": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!" },
|
||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||
"AllowedHosts": "*"
|
||||
|
||||
Reference in New Issue
Block a user