public override void PreEffect(CityGenerator block) { int x = block.mx; int y = block.my; blocksAround = new CityGenerator[4]; if (x - 1 >= 0) { blocksAround[0] = GameManager.GetBlock(x - 1, y); } if (y - 1 >= 0) { blocksAround[1] = GameManager.GetBlock(x, y - 1); } if (y + 1 < GameManager.height * 2) { blocksAround[2] = GameManager.GetBlock(x, y + 1); } if (x + 1 < GameManager.width * 2) { blocksAround[3] = GameManager.GetBlock(x + 1, y); } MainEffect(block); }
public static Models.Production.Patient New() { #pragma warning disable IDE0042 // Deconstruct variable declaration var name = NameGenerator.Random(); var city = CityGenerator.Random(); #pragma warning restore IDE0042 // Deconstruct variable declaration var patient = new Models.Production.Patient { ContactPerson = new Models.Production.ContactPerson { Name = $"{name.FirstName} {name.LastName}", Email = $"{name.FirstName}.{name.LastName}@generatedpatient.com", TelephoneNumber = $"{city.AreCode}/{s_random.Next(10, 9999999)}" }, DateOfBirth = BirthdayGenerator.RandomBirthday().ToString("s"), BedNumber = $"Bed {s_random.Next(1, 3)}", RoomNumber = $"Room {s_random.Next(1000, 999)}", WardName = WardGenerator.Random(), Gender = Models.Production.Gender.Undefined, ExternalPatientNumber = $"{name.FirstName.Substring(0, 1)}{name.LastName.Substring(0, 1)}_{s_random.Next(10000, 99999)}", ContactAddress = new Models.Production.ContactAddress { NameLine1 = $"{name.FirstName} {name.LastName}", Addressline1 = "Generated Patient Street 1", State = city.State, City = city.Name, Postalcode = city.Cip, Country = city.Country } }; return(patient); }
public static float getCommercialDistrictsMinimumDistance(CityGenerator generator) { float result = float.MaxValue; List <District> commercialDistricts = new List <District>(); foreach (District district in generator.districtsMap) { if (district.type == DistrictType.COMMERCIAL) { commercialDistricts.Add(district); } } foreach (District district in commercialDistricts) { foreach (District comDistrict in commercialDistricts) { if (district == comDistrict) { continue; } float distance = district.getDistanceTo(comDistrict, generator.roadNetwork); if (distance < result) { result = distance; } } } return(result); }
public void BuildCityTestInvalidWidthHeight() { City.City c = CityGenerator.BuildCity(0, 0, 921993); Assert.Equal(4, c.Height); Assert.Equal(4, c.Width); }
void Awake() { cityGenerator = GameObject.FindGameObjectWithTag("GameController").GetComponent <CityGenerator>(); ValidBorderMaterial = (Material)Object.Instantiate(Resources.Load("Materials/District Border")); InvalidBorderMaterial = (Material)Object.Instantiate(Resources.Load("Materials/District Border")); NormalBackgroundMaterial = (Material)Object.Instantiate(Resources.Load("Materials/District Background")); MinimumBackgroundMaterial = (Material)Object.Instantiate(Resources.Load("Materials/Striped District Background")); _lockedBackgroundMaterial = (Material)Object.Instantiate(Resources.Load("Materials/District Background")); BackgroundMaterial = MinimumBackgroundMaterial; PartyColor = evenBackgroundColor; NormalBackgroundMaterial.SetColor("_Color", CurrentColor); MinimumBackgroundMaterial.SetColor("_StripeColor", CurrentColor); MinimumBackgroundMaterial.SetColor("_NonStripeColor", GlazeColor); LockedBackgroundMaterial.SetColor("_Color", CurrentLockedColor); ValidBorderMaterial.SetColor("_Color", normalBorderColor); InvalidBorderMaterial.SetColor("_Color", normalBorderColor); CurrentMajority = Constituent.Party.None; }
// Use this for initialization void Start() { int width = GameManager.width; int height = GameManager.height; GameManager.Blocks = new CityGenerator[width * height * 2 * 2]; int i = 0; for (float x = -width; x < width; x++) { for (float y = -height; y < height; y++) { GameObject CityObject = Instantiate <GameObject> (CityBlock); CityObject.transform.SetParent(transform); CityObject.transform.localPosition = new Vector3(2f * x, 0f, 2f * y); CityGenerator CG = CityObject.GetComponent <CityGenerator> (); //City Design 1st Num is Spread //CG.TowerHealth = 45f*Mathf.Abs(((1f-(Mathf.Abs(x)/width))+(1f-(Mathf.Abs(y)/height)))/4f); CG.TowerHealth = 2f * Mathf.Abs(((1f - ((Mathf.Abs(x) + 1) / width)) + (1f - ((Mathf.Abs(y) + 1) / height))) / 4f); CG.GenerateCity((int)x + (int)width, (int)y + (int)height); GameManager.Blocks[i] = CG; i++; } } }
public override void PreEffect(CityGenerator block) { if (block.CBD.Pop < amount) { block.CBD.SetPopData(amount); } }
public int length; // = 5000; // Global max length for each road generated public void GenerateRoadNetwork(OrientedPoint startingSeed, int iter, int length, int interval) { // Reference to parent CityGenerator parent = gameObject.GetComponentInParent <CityGenerator>(); _interval = parent.interval; _offset = parent.offset; _length = parent.length; _iter = parent.length; ctr = _iter; // Create and initialize new lookup matrix (chunks) roadPoints = new List <OrientedPoint> [500, 500]; for (int x = 0; x < roadPoints.GetLength(0); x++) { for (int z = 0; z < roadPoints.GetLength(1); z++) { roadPoints[x, z] = new List <OrientedPoint>(); } } // Clear the queue before new generation starts seeds.Clear(); // Function structure GameObject mainRoad = new GameObject("Main Road"); mainRoad.AddComponent <Road>().transform.parent = this.transform; Road road = mainRoad.GetComponent <Road>(); // Generate the first road from the starting point road.GenerateRoad(startingSeed, length, true, false); // Extract seeds from the road and add to queue AddCandidatesToQueue(road.path, interval); while (seeds.Count != 0 && iter > 0) { OrientedPoint roadSeed = seeds.Dequeue(); GameObject leftRoad = GenerateChildRoad(); GameObject rightRoad = GenerateChildRoad(); // Generate the subroads with alternating major flag // Flip the major flag for the next road bool major = !roadSeed.major; Road left = leftRoad.GetComponent <Road>(); Road right = rightRoad.GetComponent <Road>(); // Generate roads in either direction from seed GenerateRoads(left, right, roadSeed, interval, major); iter--; ctr--; } }
void Awake() { _lockedConstituents = new HashSet <Constituent>(); cityGenerator = GetComponent <CityGenerator>(); audioManager = GameObject.FindGameObjectWithTag("AudioManager").GetComponent <AudioManager>(); UndoStack = new Stack <Move>(); OriginalDistricts = new Dictionary <Constituent, District>(); }
public void Start() { terrainDataThreadInfoQueue = new ConcurrentQueue <MapThreadInfo <TileData> >(); terrainGenerator = GameObject.Find("Level").GetComponent <TerrainGenerator>(); caveBuilder = GameObject.Find("Level").GetComponent <CaveBuilder>(); cityGenerator = GameObject.Find("CityPoints").GetComponent <CityGenerator>(); decorationGenerator = GameObject.Find("Decorations").GetComponent <DecorationGenerator>(); }
void Start() { fighterBody = GetComponent <Rigidbody>(); agentStatus = GetComponent <AgentStatus>(); fighterWeaponFire = GetComponentInChildren <FighterWeaponFire>(); gameManager = GameObject.Find("GameManager"); cityGenerator = gameManager.GetComponent <CityGenerator>(); SetModel(fighterCaptureBehavior, CaptureArtifact); }
public static float getSegmentSlope(Crossroad cr0, Crossroad cr1, CityGenerator cityGenerator) { float startHeight = cityGenerator.getPointHeight(cr0.x, cr0.y); float endHeight = cityGenerator.getPointHeight(cr1.x, cr1.y); float segmentLength = (float)Math.Sqrt(Math.Pow(Math.Abs(cr0.x - cr1.x), 2) + Math.Pow(Math.Abs(cr0.y - cr1.y), 2)); float slope = (float)(Math.Atan(Math.Abs(startHeight - endHeight) / segmentLength) * (180.0f / Math.PI)); return(float.IsNaN(slope) ? 0.0f : slope); }
// Use this for initialization void Awake() { moveManager = GetComponent<MoveManager>(); cityGenerator = GetComponent<CityGenerator>(); lockedConstituents = new Dictionary<Constituent, int>(); firstPlayer = Utils.ChooseRandom(new List<Player> { Player.Red, Player.Blue }); }
public void BuildCityTestSeed1() { City.City c = CityGenerator.BuildCity(30, 30, 921993); #region expected string expected = "##############################\r\nOO#OOOO#.OOO#OOO#OOOO#O.#OO#OO\r\nOO#SOOO#O**O#O*O#OO*O#OO#OO#OO\r\nOO###OO#O**O#P*O##O*O#########\r\nOOOO#OO#O**O#O*SO#.*OO#OO#OO#O\r\nO**O#PO#O*OH#OOOO#OOO.#OO#OO#O\r\nP**O#OO#O*O##OO#####OO########\r\nO**O#OO#O*O#OOO#OOO#OOO#OOO#OO\r\nOO.O#..#OOO#O*O#O*O#OOO#OOO#OO\r\nOO###.O#OO##S*O#O*O##OO#######\r\nOO#OPOO#OO#OO*O#O*OO#.OOO#OOO#\r\nOO#OO.O#OO#O*OO#OOOO#O*OO#OOO#\r\nOO###OO####.*O####OO#.*O##..##\r\nOOOO#OO.O#OO*O#OO#OO#O*O#OOO#S\r\nO**.#O*O.#HOOO#OH#OO#OOO#OO.#O\r\n.**.#.*.##OO###OO#OO##########\r\nO**O#O*O#O..#OOOO#OOO.#OOO#OO#\r\nOOOO#OPO#OOO#OOOO#OOHO#OOO#OO#\r\nOO#######OO##OO###OO####OO####\r\nOO#OOO#OOOO#OOO#.OOO#OS#OOO#OO\r\nOO#OOO#OOSO#OOO#OOOO#OO#.*.#OO\r\nO.#OO####OO#OO####OO####O*O#OO\r\n.O#OO#OO#.O#HO#OO#OHOO#OO*O#OO\r\nOO#O.#OO#OO#HO#OO#OO.O#OOHO#OO\r\nOO####OO####OO#.O#OO#####OO###\r\nOO.O#O.OO#O.OO#OO#OO#OOO#OOO#O\r\nO**O#O**O#OOOO#OO#OO#O*O#OOO#P\r\nO**O#O**O#OO######OO#.*O##OO##\r\nO**O#O**O#OO#OO#OOOO#O*OO#OOO#\r\nOOOO#OOOS#OO#OO#OOOS#O.OO#OO.#\r\n##############################"; #endregion Assert.Equal(expected, c.ToString()); }
public void CreateTrees() { cities = GetComponent <CityGenerator>(); for (int i = 0; i < amount; i++) { Vector3 randomPos = GetRandomSurfacePosition(); CreateTree(randomPos); } }
// Use this for initialization void Awake() { turnManager = GameObject.FindGameObjectWithTag("GameController").GetComponent <TurnManager>(); turnManager.firstPlayer = TurnManager.Player.Red; moveManager = GameObject.FindGameObjectWithTag("GameController").GetComponent <MoveManager>(); cityGenerator = GameObject.FindGameObjectWithTag("GameController").GetComponent <CityGenerator>(); inputManager = GameObject.FindGameObjectWithTag("GameController").GetComponent <InputManager>(); allowedMoves = new List <Constituent>(); }
public void BuildCityTestSeed2() { City.City c = CityGenerator.BuildCity(30, 30, 1712016); #region expected string expected = "##############################\r\nPO#OO#O.O#OO#OO#SOO#O.#OO#OOO.\r\nOO#OO#OOO#HO#OS#.*O#OH#OO#OPPH\r\nOP#OO########OO#O*O#######OO##\r\nOO#OOO.#OO#OSOO#O*OO#OO#OO.O#O\r\nOO#OOOO#OO#OOOO#OOOO#OO#OOOO#O\r\nOO###O.#####OO####OO#OO###OO##\r\nOOOO#OOO#O.#OO#PO#.O#OOOO#OO#.\r\nOOOO#OOO#OO#.O#OO#OO#OO*O#O.#O\r\n.O##########OO#OO#####O*O#####\r\nOO#OOO#OO.#OOO#OOO#OO#O*OO#O.#\r\nOO#.OO#OOO#OOO#.OO#OO#HOOO#.O#\r\nOO#OH##########SO#####.O######\r\nOO#OO#OO#OOO#OOOO#OO#POO#OOO#O\r\nOO#OO#OO#O*O#O**O#OO#OO.#O*O#O\r\nOO#######O*O#O**O#OO##OO#O*O##\r\nOOO#OO.#OO*O#O**O#OOO#OO#O*O#O\r\nOOO#.OO#.OOO#.**O#O*.#OO#O*O#O\r\nOO########OO#O**O#O*O#OO#O*O##\r\n.O#O.#OOO#O.#O**O#O*O#OO#.*OO#\r\nOO#OO#OOO#.O#O*OO#O.O#.O#OO.O#\r\nOS####OO##OO#O*O##OO#####..###\r\nS.OO#...#OOO#O*O#OOO#OO#S.O#OO\r\nO**O#O*O#OOO#OOO#O*O#OO#O*O#OO\r\n.**O#O*.#SO##OO##O*O#O.#O*O###\r\nO**O#S*O#.O#O.O#OO*O#OO#O*O.#O\r\nO*OO#OOO#OO#O*O#H*OO#OO#PO.O#O\r\nO*O##OO##PO#O*O#.*O#######OO##\r\nP*O#OOO#O.S#O*O#O*O#OO#OH#..#O\r\nOOO#OOO#OOO#O.O#OOO#OO#OO#PO#O\r\n##############################"; #endregion Assert.Equal(expected, c.ToString()); }
public override void MainEffect(CityGenerator block) { block.CBD.IncreasePopulation(bigmod); foreach (CityGenerator blocks in blocksAround) { if (blocks != null) { blocks.CBD.IncreasePopulation(mod); } } }
public override void OnInspectorGUI() { base.OnInspectorGUI(); CityGenerator cityGenerator = (CityGenerator)target; if (GUILayout.Button("Generate City Prefab")) { cityGenerator.GenerateCity(); } }
public void TriggerEffect(CityGenerator block) { if (!firstTrigger) { MainEffect(block); } else { FirstTrigger(block); } }
public override void OnInspectorGUI() { CityGenerator generator = (CityGenerator)target; // Show default inspector property editor DrawDefaultInspector(); if (GUILayout.Button("Generate")) { generator.Regenerate(); } }
public override List<Atom> Produce(CityGenerator generator) { List<Atom> production = new List<Atom>(); float x = Creator != null ? Creator.Node.X : 0f; float z = Creator != null ? Creator.Node.Y : 0f; Rule rule = generator.RuleAtCoordinates(new Vector3(x, 0f, z)); List<RoadAtom> roads = rule.SpawnRoads(this, generator); foreach (RoadAtom road in roads) production.Add(road); return production; }
public override void OnInspectorGUI() { CityGenerator cityGen = (CityGenerator)target; if (DrawDefaultInspector()) { } if (GUILayout.Button("Generate")) { cityGen.GenerateCity(); } }
private void Start() { mapGenerator = GetComponent <MapGenerator>(); treeGenerator = GetComponent <TreeGenerator>(); cityGenerator = GetComponent <CityGenerator>(); maxViews = detailLevels[detailLevels.Length - 1].visibilityThreshold; chunkSize = mapGenerator.mapChunkSize - 1; chunksVisible = Mathf.RoundToInt(maxViews / chunkSize); UpdateVisibleChunks(); }
public float[,] GenerateTerrain(int seed, GameObject inTerrainObject, CityGenerator generator) { if (inTerrainObject != null) { terrainObject = inTerrainObject; } if (terrainObject == null) { terrainObject = new GameObject("Terrain"); } float[,] terrainMap = new float[dimension, dimension]; Random.InitState(seed); int permutationTableSize = (dimension + 1) * (dimension + 1); permutationTable = new int[permutationTableSize]; for (int i = 0; i < permutationTableSize; i++) { permutationTable[i] = ((int)(Random.value * Mathf.Pow(2, 30))); } List <float> amplitudes = new List <float>(); List <float[, ]> noises = new List <float[, ]>(); for (int i = 0; i < noisesConfigurations.Count; i++) { noises.Add(generateNoise(noisesConfigurations[i].frequency)); amplitudes.Add(noisesConfigurations[i].amplitude); } float totalAmplitude = 0.0f; for (int i = 0; i < noises.Count; i++) { totalAmplitude += amplitudes[i]; } for (int x = 0; x < dimension; x++) { for (int y = 0; y < dimension; y++) { float r = 0.0f; for (int i = 0; i < noises.Count; i++) { r += noises[i][x, y] * amplitudes[i]; } r = r / totalAmplitude; // Normalize sum of noises r = MathHelper.quintic(MathHelper.quintic(r)); // Apply non-linear filter terrainMap[x, y] = r; } } meshGenerator.GenerateMesh(terrainObject, terrainMap, generator.meshDimension); return(terrainMap); }
static void Main(string[] args) { MyMqttClient mqttClient = new MyMqttClient(); var generator = new CityGenerator(); generator.LoadFile().Wait(); foreach (City city in generator.GetAllLithuanianCities()) { var device = new Device(mqttClient, city.id.ToString(), _preDeviceName + city.name.ToString()); Task.Run(device.StartWorkAsync); } }
public override List<RoadAtom> SpawnRoads(BranchAtom currentAtom, CityGenerator gen) { List<RoadAtom> production = new List<RoadAtom>(); if (currentAtom.Creator != null) { // Determine the vector from the creator atom's position and the current node's position, and split the // result into two groups: // - the vector is more aligned with the radius vector from the origin to the current node // - the vector is more aligned with the tangent of the circle which the radius vector defines Vector3 radiusVector = currentAtom.Node.position - gen.transform.position; Vector3 fromCreator = currentAtom.Node.position - currentAtom.Creator.Node.position; Vector3 tangent = Quaternion.Euler(0f, -90f, 0f) * radiusVector; Vector3 left = (Quaternion.Euler(0f, -90f, 0f) * fromCreator).normalized; Vector3 straight = fromCreator.normalized; Vector3 right = (Quaternion.Euler(0f, 90f, 0f) * fromCreator).normalized; // Get the angle between the radius vector and the vector from the creator to the current node // (Note: Vector3.Angle returns a value from 0f to 180f) float angle = Vector3.Angle(radiusVector, fromCreator); if (angle < 45f || angle > 135f) { // The incoming orientation is more aligned with the radius vector left = AlignVector(left, tangent); straight = AlignVector(straight, radiusVector); right = AlignVector(right, tangent); } else { // The incoming orientation is more aligned with the tangent left = AlignVector(left, radiusVector); straight = AlignVector(straight, tangent); right = AlignVector(right, radiusVector); } // For now, spawn roads in all three directions // TODO: Temporary production.Add(new RoadAtom(left, currentAtom.Node, Rule.Type.Radial)); production.Add(new RoadAtom(straight, currentAtom.Node, Rule.Type.Radial)); production.Add(new RoadAtom(right, currentAtom.Node, Rule.Type.Radial)); } else { // There's no creator (which means this is the axiom node), so we'll create roads shooting in all directions // TODO: Temporary production.Add(new RoadAtom(Vector3.forward, currentAtom.Node, Rule.Type.Radial)); production.Add(new RoadAtom(Vector3.back, currentAtom.Node, Rule.Type.Radial)); production.Add(new RoadAtom(Vector3.left, currentAtom.Node, Rule.Type.Radial)); production.Add(new RoadAtom(Vector3.right, currentAtom.Node, Rule.Type.Radial)); } return production; }
public override void OnInspectorGUI() { CityGenerator cityGenerator = (CityGenerator)target; base.OnInspectorGUI(); if (GUILayout.Button("Create Cities")) { cityGenerator.CreateCities(); } if (GUILayout.Button("Remove Cities")) { cityGenerator.RemoveCities(); } }
public override void OnInspectorGUI() { CityGenerator cityGen = (CityGenerator)target; DrawDefaultInspector(); if (GUILayout.Button("Re-Generate City")) { cityGen.GenerateCity(cityGen.citySizeX, cityGen.citySizeZ); } if (GUILayout.Button("Clear City")) { cityGen.ClearCity(); } }
/// <summary> /// Calculates the length of the road for the given atom, taking its position and environment into account. This /// method is invoked by each <see cref="RoadAtom"/> during its production, in order to find out its length. /// </summary> /// <returns>The road length.</returns> /// <param name="currentAtom">Current atom.</param> /// <param name="gen">City generator.</param> public virtual float CalculateRoadLength(RoadAtom currentAtom, CityGenerator gen) { // Calculate how much the population density influences road length (the less population, the longer the road) float populationLengthFactor = 1f - gen.DensityAt(currentAtom.Node.position); // Calculate how much the slope of the road influences its length (the steeper, the shorter) float elevationLengthFactor = Mathf.Abs(gen.ElevationAt(currentAtom.Node.position) - gen.ElevationAt(currentAtom.Node.position + currentAtom.Forward)); elevationLengthFactor = 1f - Mathf.Clamp01(gen.slopeExaggeration * elevationLengthFactor); // Multiply them to get the final length factor. Basically the elevation factor should only influence the // population factor when the road is very steep, in other cases it should be close to 1. float lengthFactor = populationLengthFactor * elevationLengthFactor; // Calculate the road length return gen.minimumRoadLength + lengthFactor * (gen.maximumRoadLength - gen.minimumRoadLength); }
public string Get() { var cityGenerator = new CityGenerator(); if (!cityGenerator.Generate()) { return("Error"); } var factoryGenerator = new FactoryGenerator(); if (!factoryGenerator.Generate()) { return("Error"); } var utilityGenerator = new UtilityGenerator(); if (!utilityGenerator.Generate()) { return("Error"); } var regionGenerator = new RegionGenerator(); if (!regionGenerator.Generate()) { return("Error"); } var containerGenerator = new ContainerGenerator(); if (!containerGenerator.Generate()) { return("Error"); } var tripGenerator = new TripGenerator(); if (!tripGenerator.Generate()) { return("Error"); } return("Success"); }
public static float getCityRadius(List <District> districtsList, CityGenerator generator) { float result = 0.0f; foreach (District district in districtsList) { foreach (DistrictCell cell in district.cells) { float distance = Vector2.Distance(new Vector2(cell.x + 0.5f, cell.y + 0.5f), generator.cityCenter); if (distance > result) { result = distance; } } } return(result); }
// Use this for initialization void Start() { turnManager = GameObject.FindGameObjectWithTag("GameController").GetComponent <TurnManager>(); cityGenerator = GameObject.FindGameObjectWithTag("GameController").GetComponent <CityGenerator>(); currentTurnUIManager = GetComponentInChildren <CurrentTurnUIManager>(); endTurnUIManager = GetComponentInChildren <EndTurnUIManager>(); audioManager = GameObject.FindGameObjectWithTag("AudioManager").GetComponent <AudioManager>(); //color the text based on whose turn it is var currentBackgroundColor = GetBackgroundColorForPlayer(turnManager.CurrentPlayer); foreach (var panel in backgroundPanels) { panel.color = currentBackgroundColor; } }
public override List<RoadAtom> SpawnRoads(BranchAtom currentAtom, CityGenerator gen) { List<RoadAtom> production = new List<RoadAtom>(); if (currentAtom.Creator != null) { // Get the orientation of the "parent" road (the one we're continuing in this production) MapNode toNode = currentAtom.Node; MapNode fromNode = currentAtom.Node.edges[0].FromNode; Vector3 parentDirection = (toNode.position - fromNode.position).normalized; // Get the elevation at the current point float currentElevation = gen.ElevationAt(currentAtom.Node.position); // Create three roads: left, right and straight with regard to the "parent" road's direction float[] angles = new float[] { -90f, 0f, 90f }; foreach (float angle in angles) { // Rotate the direction vector to get the direction we'll probe in Vector3 roadDirection = Quaternion.Euler(0f, angle, 0f) * parentDirection; // Probe elevations around the given direction and get the direction of the road which is least steep roadDirection = LeastSteepDirection(currentAtom.Node.position, roadDirection, currentElevation, gen); // Create a new RoadAtom with the given road direction RoadAtom roadAtom = new RoadAtom(roadDirection, currentAtom.Node, Rule.Type.Rectangular); // Add it to the production production.Add(roadAtom); } } else { // This is the axiom, just spawn roads in all directions production.Add(new RoadAtom(Vector3.forward, currentAtom.Node, Rule.Type.Rectangular)); production.Add(new RoadAtom(Vector3.back, currentAtom.Node, Rule.Type.Rectangular)); production.Add(new RoadAtom(Vector3.left, currentAtom.Node, Rule.Type.Rectangular)); production.Add(new RoadAtom(Vector3.right, currentAtom.Node, Rule.Type.Rectangular)); } return production; }
/// <summary> /// Returns the direction of the least steep road among all probed roads. /// </summary> /// <returns>The direction of the road.</returns> /// <param name="position">Position.</param> /// <param name="roadDirection">Road direction.</param> /// <param name="currentElevation">Current elevation.</param> /// <param name="gen">City generator.</param> protected Vector3 LeastSteepDirection(Vector3 position, Vector3 roadDirection, float currentElevation, CityGenerator gen) { // Probe elevations around the given direction KeyValuePair<Vector3, float>[] elevationPairs = ProbeFloat(position, roadDirection, gen, ElevationProber); // Find the location which has a minimum elevation difference relative to the current node's position KeyValuePair<Vector3, float> minimumPair; float minimumElevationDelta = float.MaxValue; foreach (KeyValuePair<Vector3, float> elevationPair in elevationPairs) { if (Mathf.Abs(currentElevation - elevationPair.Value) < minimumElevationDelta) { minimumElevationDelta = Mathf.Abs(currentElevation - elevationPair.Value); minimumPair = elevationPair; } } // We have the end location of the least steep road, now make it into a direction return (minimumPair.Key - position).normalized; }
/// <summary> /// Spawns the roads for the given branch atom. Each branch atom invokes this method during its production in order /// to calculate the roads which will be spawned from it. /// </summary> /// <returns>The roads.</returns> /// <param name="currentAtom">Current atom.</param> /// <param name="gen">City generator.</param> public abstract List<RoadAtom> SpawnRoads(BranchAtom currentAtom, CityGenerator gen);
/// <summary> /// Probes the environment by spawning a <paramref name="numberOfProbes"/> probes at the given /// <paramref name="worldPosition"/> around the given <paramref name="direction"/>, using the given /// <paramref name="prober"/> delegate to query the wanted result from the environment at the given coordinates. The /// probing vectors are spawned around the given direction vector, such that /// floor(<paramref name="numberOfProbes"/>/2) vectors are spawned on the left and right sides of the direction /// vector, and one probe which is aligned with the direction vector. The angle between probing vectors is such that /// the angle between the leftmost (and rightmost) vector and the direction vector is exactly <paramref name="env"/> /// .maximumRoadDeviationDegrees. The length of each probe is <paramref name="env"/>.minimumRoadLength. /// </summary> /// <returns>The array of (Vector3, float) pairs representing the coordinate of each probe and the probed value, /// respectively.</returns> /// <param name="worldPosition">World position.</param> /// <param name="direction">Direction.</param> /// <param name="gen">City generator.</param> /// <param name="prober">Prober.</param> /// <param name="numberOfProbes">Number of probes.</param> protected KeyValuePair<Vector3, float>[] ProbeFloat(Vector3 worldPosition, Vector3 direction, CityGenerator gen, FloatProber prober, int numberOfProbes = NumberOfProbes) { KeyValuePair<Vector3, float>[] probedValues = new KeyValuePair<Vector3, float>[numberOfProbes]; float angleIncrement = gen.maximumRoadDeviationDegrees / (numberOfProbes / 2); for (int i = 0, angleIndex = - numberOfProbes / 2; i < numberOfProbes; i++, angleIndex++) { // Rotate the current probe relative to the given direction based on i and angleIncrement Vector3 probeDirection = Quaternion.AngleAxis(angleIndex * angleIncrement, Vector3.up) * direction.normalized; // Calculate the exact position of the probe // (We use env.minimumRoadLength as a good candidate for probe length, it might be made into a configurable // editor option at some point.) Vector3 probePosition = worldPosition + probeDirection * gen.minimumRoadLength; // Now probe probedValues[i] = new KeyValuePair<Vector3, float>(probePosition, prober(gen, probePosition)); } return probedValues; }
/// <summary> /// Runs a production on this instance. /// </summary> /// <returns> /// A list of atoms for the next L-system generation. /// </returns> public abstract List<Atom> Produce(CityGenerator generator);
void Awake() { cityGenerator = (target as GeneratorController).gameObject.GetComponent<CityGenerator>(); }
public override List<Atom> Produce(CityGenerator generator) { List<Atom> production = new List<Atom>(); // Create a new map node Rule rule = generator.RuleAtCoordinates(Node.position); MapNode spawn = new MapNode(Node.position + forward * rule.CalculateRoadLength(this, generator)); spawn.ruleType = ruleType; // Fetch the spawned node's neighbours List<MapNode> neighbours = generator.GetNeighbours(spawn, generator.neighboursSearchRadius); // Check if the node is close to one of its neighbours so that they can be merged into one node bool merged = false; Vector2 spawnPosition = spawn.PositionAsVector2; foreach (MapNode neighbour in neighbours) { // Convert coords to 2D, we don't want elevation messing around with our merging algorithm Vector2 neighbourPosition = neighbour.PositionAsVector2; // Check for proximity if (Vector2.Distance(spawnPosition, neighbourPosition) <= generator.nodeMergingMaximumDistance) { // The neighbour merges spawn = neighbour; // Stop iterating merged = true; break; } } // Create a map edge between the current map node and the spawn MapEdge spawnedEdge = new MapEdge(Node, spawn); if (!merged) { // Perform the intersection of the spawned node's edge against the neighbours' edges bool intersected = Intersect(spawn, spawnedEdge, neighbours); // Raycast to check for water RaycastHit hit; if (Physics.Raycast(spawn.position + Vector3.up * 1000f, Vector3.down, out hit)) { if (hit.collider.gameObject.tag == "Water") { // Spawned over water, remove the edge from the starting node Node.edges.Remove(spawnedEdge); // Skip this node return production; } // Set the Y coordinate of the spawned node to match the height where the raycast hit spawn.position.y = hit.point.y + 0.1f; } // Add the newly created map node to the environment generator.AddMapNode(spawn); // Continue producing only if there were no intersections if (!intersected) { // Summon a branch atom Atom branch = new BranchAtom(this); branch.Node = spawn; // Add the branch atom to the list of results and we're done production.Add(branch); } } return production; }
/// <summary> /// The prober that probes for population density at the given position. /// </summary> /// <returns>The population density at the given position.</returns> /// <param name="gen">City generator.</param> /// <param name="position">Position.</param> public static float DensityProber(CityGenerator gen, Vector3 position) { return gen.DensityAt(position); }
/// <summary> /// The prober that probes for elevation at the given position. /// </summary> /// <returns>The elevation at the given position.</returns> /// <param name="gen">City generator.</param> /// <param name="position">Position.</param> public static float ElevationProber(CityGenerator gen, Vector3 position) { return gen.ElevationAt(position); }
public void GenerateCity() { m_cityGenerator = new CityGenerator ((int)DateTime.Now.Ticks, TamBoard, TamBoard); m_cityGenerator.Build(); m_city = m_cityGenerator.getCity(); instantiatePrefabs(); generateIA(); instantiateCars(); colocateCamera(); }
// Use this for initialization void Start() { float verticalSize = Camera.main.orthographicSize * 2.0f; float horizontalSize = verticalSize * Screen.width / Screen.height; startPoint.x = -horizontalSize / 2; startPoint.y = -verticalSize / 2; blockSize.x = horizontalSize / (sizeX - 1); blockSize.y = verticalSize / (sizeY - 1); buildingSize = blockSize * 0.6f; generator = new CityGenerator (sizeX - 2, sizeY - 2); for (int i = 0; i < 500; i++) generator.GlueBuildings (); //var building = new CityBuilding (5,5); //building.points.Add (new Point(0,-1)); //building.points.Add (new Point(0,1)); //building.points.Add (new Point(-1,0)); //building.points.Add (new Point(1,0)); //AddBuilding(building); for (int x = 0; x < sizeX -2 ; x++) { for(int y = 0; y < sizeX - 2; y++){ CityBuilding building = generator.Grid[x,y]; if( building.X == x && building.Y == y){ AddBuilding(building); } } } }