public override void Generate(TileData data, StopToken stop) { //loading source if (stop != null && stop.stop) { return; } SplineSys src = data.ReadInletProduct(this); if (src == null) { return; } SplineSys copy = new SplineSys(src); if (copy.lines.Length == 0) { return; } var locality = TownGlobalObject.GetIndexAtCoord(data.area.Coord); copy.Clamp((Vector3)data.area.active.worldPos, (Vector3)data.area.active.worldSize); for (int i = 0; i < copy.lines.Length; i++) { for (int j = 0; j < copy.lines[i].segments.Length; j++) { var start = copy.lines[i].segments[j].start; var end = copy.lines[i].segments[j].end; start.pos -= (Vector3)data.area.active.worldPos; end.pos -= (Vector3)data.area.active.worldPos; } } if (stop != null && stop.stop) { return; } //adding to finalize if (enabled && copy.NodesCount > 0) { data.StoreOutput(this, typeof(MapSplineOutMark1), this, copy); data.MarkFinalize(Finalize, stop); } else { data.RemoveFinalize(Finalize); } }
// We Always do the checks. void Start() { // check some stuff DoChecks(); // Hard keep this WorldZero = new Vector2(ObjectToTrack.position.x, ObjectToTrack.position.z); WorldStart = ObjectToTrack.position; WorldHomeCoord = TownGlobalObject.GetIndexAtCoord(CoordForTileFromVec3(ObjectToTrack.position)); // WorldHomeCoord = new Coord(0); }
public override void Generate(TileData data, StopToken stop) { Coord locality = TownGlobalObject.GetIndexAtCoord(data.area.Coord); if (TownGlobalObject.townsData[locality] == null) { return; } //SplineSys src = data.ReadInletProduct(splineIn); SplineSys src = data.ReadInletProduct(this); // MatrixWorld heights = data.ReadInletProduct(heightIn); if (src == null) { return; } if (!enabled)// || heights == null) { data.StoreProduct(this, src); return; } if (stop != null && stop.stop) { return; } SplineSys dst = new SplineSys(src); // at this point cleanse. it should be clean. but clean anyway? dst.Clamp((Vector3)data.area.active.worldPos, (Vector3)data.area.active.worldSize); // WE only do main stage if (data.isDraft) { data.StoreProduct(this, dst); return; } if (dst.lines.Length == 0) { // null. there are no segments to add. // TownGlobalObject.GetSplineList(data.area.Coord); data.StoreProduct(this, dst); return; } // this is already completed processed by all threads /n/ times and marked as done in OnTileApplied() else if (TownGlobalObject.isSplinesMeshRenderedOnTile.ContainsKey(data.area.Coord)) { return; } //{ // // we already processed the tile. // data.StoreProduct(this, dst); // return; //} // these might not be linked but probably are??? foreach (var item in dst.lines) { var subdic = new Dictionary <Coord, List <Vector3> >(); var sublist = new List <SplineMesh.Spline>(); // track to ensure we have at a minimum two nodes... int nodesInThisSegmentGroup = 0; // use this rather than the monobehaviour TypedSpline typed = new TypedSpline(); // SplineMesh.Spline mysm = new SplineMesh.Spline(); // these should be linked - Hopefully this will pickup on a partially aborted WHILE for (int segmentindex = 0; segmentindex < item.segments.Length; segmentindex++) { // They will be in pairs by now. we need to do the logic to string them back together, here. Segment segmentToProcess = item.segments[segmentindex]; // nodesInThisSegmentGroup = AddNodeReturnIncrementedTotalCount(data, nodesInThisSegmentGroup, segmentToProcess, mysm); nodesInThisSegmentGroup = AddNodeToListReturnIncrementedTotalCount(nodesInThisSegmentGroup, segmentToProcess, typed.nodes); segmentindex++; } typed.chosenType = (int)chosenType; typed.tryToFloor = TryToFloor; //update a value if (TownGlobalObject.splinesNodesDataForTile.ContainsKey(data.area.Coord)) { TownGlobalObject.splinesNodesDataForTile[data.area.Coord].Add(typed); } else {// create a new one TownGlobalObject.GetSplineList(data.area.Coord).Add(typed); } //TownGlobalObject.splinesNodesDataForTile.AddOrUpdate(data.area.Coord, TownGlobalObject.GetSplineList(data.area.Coord), (key, current) => { current.Add(typed); return current; } ); // TownGlobalObject.GetSplineList(data.area.Coord).Add(typed); // here we would loop if the segmentindex has not been reached. // might have to watch for weird single node edge cases but oh well. Bridge. Come to it. } // We just store the original. // data.StoreProduct(this, src); // We store TRUNCATED copy. data.StoreProduct(this, dst); }
private void TryToFloor() { // list, right length List <float> testArr = new List <float>(); // Fill it with 500's for (int i = 0; i < spline.nodes.Count; i++) { testArr.Add(500f); } spline.enabled = false; int testcount = 0; int maxdepth = 5; Vector3 totalOffsetFromRoot = Vector3.zero; Transform newchild = transform.parent; for (int depth = 0; depth < maxdepth; depth++) { totalOffsetFromRoot = totalOffsetFromRoot + newchild.position; newchild = newchild.parent; if (newchild == mapMagicTransform) { break; } } totalOffsetFromRoot *= .5f; Coord tilecoord = CoordForTileFromVec3(totalOffsetFromRoot); var locality = TownGlobalObject.GetIndexAtCoord(tilecoord); // Vector3 townOffset = -(tilecoord.ToTileSizeVector3() - locality.ToTileSizeVector3()); for (int i = 0; i < spline.nodes.Count; i++) { var node = spline.nodes[i]; // Vector3 modulod = new Vector3((node.Position.x - (totalOffsetFromRoot.x * 0.5f)) % 1000, node.Position.y, (node.Position.z - (totalOffsetFromRoot.z * 0.5f)) % 1000); Vector3 modulod = new Vector3((node.Position.x - (totalOffsetFromRoot.x)) % 1000, node.Position.y, (node.Position.z - (totalOffsetFromRoot.z)) % 1000); Vector3 newpos = totalOffsetFromRoot + modulod; //Vector2 testpos = new Vector2( // newpos.x, // newpos.z ); Vector2 testpos = new Vector2( node.Position.x + totalOffsetFromRoot.x, node.Position.z + totalOffsetFromRoot.z); testArr[i] = GetTerrainPos(testpos.x, testpos.y).y; node.Position = node.Direction = new Vector3(node.Position.x, testArr[i], node.Position.z); testcount += 1; } // if (!spline.enabled) spline.enabled = true; if (testArr.Contains(0)) { // Last pop get nuclear if (attempts > MaxAttempts - 4) { // check every single node. for (int i = 0; i < spline.nodes.Count; i++) { var node = spline.nodes[i]; // move x closer if (Mathf.Abs(node.Position.x % 1) <= (checkVal)) { node.Position = new Vector3(Mathf.Round(node.Position.x), node.Position.y, node.Position.z); } // Move z closer if (Mathf.Abs(node.Position.z % 1) <= (checkVal)) { node.Position = new Vector3(node.Position.x, node.Position.y, Mathf.Round(node.Position.z)); } } checkVal *= 8; } if (attempts < MaxAttempts) { attempts += 1; Invoke(nameof(TryToFloor), 1); return; } else { Debug.LogFormat(gameObject, "Failed to floor splines {0} on countout", gameObject.name); return; } } }
// TODO we could just use this to level the final objects rather than the horror-story ray casts. // public float terrainHeight; //to get relative object height (since all of the terrain data is 0-1). //TODO: maybe move it to HeightData in "Height in meters" task // TODO we could limit the perframe activities mid-spawn // public int objsPerIteration = 500; public void Apply(Terrain terrain) { // unless there is no spline data if (splines == null || splines.Count == 0 || splines[0].lines.Length == 0) { return; } // By this point this should absolutely exist - int totalNumberOfListsOfSplineMeshSplines = splines.Count; // There is nothing in the list if (totalNumberOfListsOfSplineMeshSplines == 0) { return; } List <GameObject> thingsToActivate = new List <GameObject>(); Coord data_area_cood = terrain.transform.parent.localPosition.ToCoord() * 0.001f; Coord locality = TownGlobalObject.GetIndexAtCoord(data_area_cood); // SplinePowerExtended var DynamicHolder = TownHolder.Instance.MapMagicObjectReference.transform.Find(string.Format("Tile {0},{1}", data_area_cood.x, data_area_cood.z)); // Create splines holder var splineHolder = new GameObject { name = "SPLINE_FOR_" + string.Format("Tile_{0},{1}", data_area_cood.x, data_area_cood.z) }; splineHolder.transform.parent = DynamicHolder; splineHolder.transform.localPosition = new Vector3(); Coord tilecoord = splineHolder.transform.parent.GetComponent <TerrainTile>().coord; // We walk over the nodes assuming pairs? for (int i = 0; i < totalNumberOfListsOfSplineMeshSplines; i++) { SplineSys spline = splines[i]; var myarray = new List <SplineMesh.SplineNode>(); // No splines for us... if (spline.NodesCount == 0) { continue; } var global = new List <SplineNode>(); var positionalFactor = 1f; myarray = new List <SplineNode>(); SplineNode refnode = new SplineNode(Vector3.positiveInfinity, Vector3.positiveInfinity); SplineNode startnode = refnode; SplineNode endnode = refnode; Segment lastSegment = new Segment(); Segment thissegment = new Segment(); lastSegment.end.pos = thissegment.start.pos = Vector3.positiveInfinity; foreach (var road in spline.lines.Reverse()) { if (!splines[i].mergeSegments) { myarray = new List <SplineNode>(); } foreach (var current in road.segments) { // We need to check if the last segments end connects to the next segments start or RenderOutSplinesSoFar; thissegment = road.segments.Where(x => x.GetHashCode() == current.GetHashCode()).First(); thissegment.start.pos -= DynamicHolder.transform.localPosition; thissegment.end.pos -= DynamicHolder.transform.localPosition; if (splines[i].mergeSegments) { // Render out the segments if they are far apart (square root of 200) - have some data get parsed - and have been selected for merging if (Vector3.SqrMagnitude(lastSegment.end.pos - thissegment.start.pos) > 200f && myarray.Count > 1) { RenderOutSplinesSoFar(splineHolder, i, myarray); myarray = new List <SplineNode>(); } } lastSegment = thissegment; // setup bool fence for list. // add start if we didnt. bool startExists = global.Exists(element => element.Position == thissegment.start.pos * positionalFactor); if (!startExists) { startnode = new SplineMesh.SplineNode(thissegment.start.pos * positionalFactor, thissegment.start.pos * positionalFactor); myarray.Add(startnode); global.Add(startnode); } // and add end if we didnt. bool endExists = global.Exists(element => element.Position == thissegment.end.pos * positionalFactor); if (!endExists) { endnode = new SplineMesh.SplineNode(thissegment.end.pos * positionalFactor, thissegment.end.pos * positionalFactor); myarray.Add(endnode); global.Add(endnode); } } if (myarray.Count == 0) { continue; } if (myarray.Count == 1) { // give us two by hook or crook if (myarray.Contains(startnode)) { endnode = new SplineMesh.SplineNode(lastSegment.end.pos * positionalFactor, lastSegment.end.pos * positionalFactor); myarray.Add(endnode); } else { startnode = new SplineMesh.SplineNode(lastSegment.start.pos * positionalFactor, lastSegment.start.pos * positionalFactor); myarray.Add(startnode); } continue; } if ((myarray[1].Position - myarray[0].Position).sqrMagnitude == 0) { continue; } // Render out as just segment node pairs if (!splines[i].mergeSegments) { RenderOutSplinesSoFar(splineHolder, i, myarray); } } // Attempt to merge near pairs if (splines[i].mergeSegments) { RenderOutSplinesSoFar(splineHolder, i, myarray); } } }
private void RenderOutlet(TileData data, AOTABundle bundle, Dictionary <string, ulong> OutletFullList) { ulong matchingId; foreach (var splineSys in bundle.SplineSysBundle) { // Check the list is properly formatted. Could be removed... if you are confident. if (!OutletFullList.ContainsKey(splineSys.outletName)) { Debug.LogFormat("{0} {1} not found initialised in the {2}", nameof(matchingId), splineSys.outletName, nameof(OutletFullList)); continue; } else { // item.outletName // should match the entry in OutletFullList matchingId = OutletFullList[splineSys.outletName]; } if (splineSys.splineSys.lines.Length > 0) { //Debug.LogFormat("{6} has {7} lines at tile {8}, first line goes from {0},{1},{2} to {3},{4},{5} ", // splineSys.splineSys.lines[0].segments[0].start.pos.x, // splineSys.splineSys.lines[0].segments[0].start.pos.y, // splineSys.splineSys.lines[0].segments[0].start.pos.z, // splineSys.splineSys.lines[0].segments[0].end.pos.x, // splineSys.splineSys.lines[0].segments[0].end.pos.y, // splineSys.splineSys.lines[0].segments[0].end.pos.z, // splineSys.outletName, // splineSys.splineSys.lines.Length, // data.area.Coord // ); // now we know the Id. go populate it. foreach (var outlet in Outlets()) { if (outlet.Id == matchingId) { // splineSys.splineSys.Clamp((Vector3)data.area.full.worldPos, (Vector3)data.area.full.worldSize); data.StoreProduct(outlet, splineSys.splineSys); } } } // else // Debug.LogFormat("Outlet {0} has {1} lines", splineSys.outletName, splineSys.splineSys.lines.Length); } // We only render the objects in the last gasp. (Main Pass) //if (data.isDraft) //{ // return; //} foreach (var objectList in bundle.TransitionsListBundle) { if (RoadOnly) { continue; } if (OutletFullList.ContainsKey(objectList.outletName)) { // item.outletName // should match the entry in OutletFullList matchingId = OutletFullList[objectList.outletName]; } else { Debug.LogFormat("{0} {1} not found initialised in the {2}", nameof(matchingId), objectList.outletName, nameof(OutletFullList)); continue; } if (objectList.transitionsList.count > 0) { // now we know the Id. go populate it. foreach (var outlet in Outlets()) { if (outlet.Id == matchingId) { // Bodge the city size into the object // 0,0 is shared between the corner of 4 tiles. so expect at least 4 if (objectList.outletName == "centerOut") { var hinum = (double)Mathf.Max((TownGlobalObjectService.PatchCap + 10), (TownGlobalObject.bundles[data.area.Coord].town.Options.Patches)); var magic = (float)(1 / (hinum / (double)TownGlobalObject.bundles[data.area.Coord].town.Options.Patches)); objectList.transitionsList.arr[0].scale = new Vector3(magic, magic, magic); // Store the single case. for the absolute town center if (data.area.Coord == TownGlobalObject.GetIndexAtCoord(data.area.Coord)) { var location = Outlets().Where(x => x.Id == singlecenterOut.Id).First(); objectList.transitionsList.arr = objectList.transitionsList.arr.Truncated(objectList.transitionsList.count); data.StoreProduct( location, objectList.transitionsList); } } objectList.transitionsList.arr.Truncated(objectList.transitionsList.count); // foreach (var item in objectList.transitionsList.arr) // { // if (!data.area.active.Contains(item.pos)) continue; // } TransitionsList cleaner = new TransitionsList(); if (objectList.outletName == "gatehouseSplineOut") { Debug.Log(objectList.transitionsList.arr.Length + " gatehouseSplines on this tile"); } //for (int i = 0; i < objectList.transitionsList.arr.Length; i++) // { // if (data.area.active.Contains(objectList.transitionsList.arr[i].pos)) // { // cleaner.Add( objectList.transitionsList.arr[i]); // } // } data.StoreProduct(outlet, objectList.transitionsList); // data.StoreProduct(outlet, cleaner); } } } // else // Debug.LogFormat("Outlet {0} has {1} objects", objectList.outletName, objectList.transitionsList.count); } // Let's shove it all in the list. }
public override void Generate(TileData data, StopToken stop) { if (stop.stop || !enabled) { return; } // the only reason we could get here that I can figure is if you pinned so lets init things. if (!TownGlobalObject.InitialTownsGenerated) { Debug.Log("***** !TownGlobalObject.InitialTownsGenerated THIS IS BAD*****"); return; } Dictionary <string, ulong> OutletFullList; // = new Dictionary<string, ulong>(); InitNamedOutputsDicts(out OutletFullList); if (stop.stop) { return; } //// Town stuff /////////// ******** // This will ALLLLLways return something... it SHOULD be the town. Coord locality = TownGlobalObject.GetIndexAtCoord(data.area.Coord); if (!TownGlobalObject.bundles.ContainsKey(data.area.Coord)) // By this point !bundle.isBundled && !bundle.isTileDataInBundle - basically the bundle is a blank. { Debug.Log("***** !TownGlobalObject.bundles.ContainsKey(data.area.Coord) THIS IS BAD*****"); return; } // WE DID HIT THE BUNDLE bundle = TownGlobalObject.bundles[data.area.Coord]; if (locality == data.area.Coord && !bundle.isTileDataInBundle && !RoadOnly) { Debug.LogFormat("This is a town tile. Is the locality Town stored? {0}", TownGlobalObject.townsData.ContainsKey(locality)); } // Handle the WE HAVE THE TILE DATA ALREADY case if (bundle.isBundled && bundle.isTileDataInBundle) { //Debug.LogFormat( // "{0} is {1}, {2} is {3}, {4} is {5}, ", // "outlet GUID", // item.splineSys.GetType().GUID, // "name", // item.name, // nameof(item.outlet.Id), // item.outlet.id); // Write it to the outputs and exit. RenderOutlet(data, bundle, OutletFullList); return; } // The Unrendered case. Lets double check. else if (bundle.isBundled && !bundle.isTileDataInBundle) { RenderOutlet(data, bundle, OutletFullList); bundle.MarkIsTileDataInBundleTrue(); // bundle.isTileDataInBundle = true; return; } }
public void OnBeforeTileGenerateCheck(TerrainTile tile, TileData data) { if (!TownGlobalObject.InitialTownsGenerated) { Debug.Log("***** !TownGlobalObject.InitialTownsGenerated THIS IS BAD*****"); return; } // This will ALLLLLways return something... it SHOULD be the town. Coord locality = TownGlobalObject.GetIndexAtCoord(data.area.Coord); if (!TownGlobalObject.bundles.ContainsKey(data.area.Coord)) // By this point !bundle.isBundled && !bundle.isTileDataInBundle - basically the bundle is a blank. { // WE DID NOT HIT THE BUNDLE //Debug.LogFormat("bundle not found for tile {1}, town {0} during the {2} phase", locality, data.area.Coord, // (data.isDraft) ? "Draft" : "Main" // ); TownTileRenderer mrMaker = new TownTileRenderer(); // But the actual town should be stored at the "Locality" bundle = mrMaker.MakeATileBundleWithThisTown(data.area.Coord, false, true, locality); // by here all our splineSys and transition lists should be filled. // Bless it. bundle.MarkisBundledTrue(); bundle.MarkIsTileDataInBundleTrue(); TownGlobalObject.bundles[data.area.Coord] = bundle; } // WE DID HIT THE BUNDLE bundle = TownGlobalObject.bundles[data.area.Coord]; if (locality == data.area.Coord && !bundle.isTileDataInBundle) { Debug.LogFormat("This is a town tile. Is the locality Town stored? {0}", TownGlobalObject.townsData.ContainsKey(locality)); } // Handle the WE HAVE THE TILE DATA ALREADY case if (bundle.isBundled && bundle.isTileDataInBundle) { return; } // The Unrendered case. Lets double check. else if (bundle.isBundled && !bundle.isTileDataInBundle) { TownTileRenderer mrMaker = new TownTileRenderer(); bundle = mrMaker.MakeATileBundle(data.area.Coord, false, false); Debug.LogFormat("rewrite for UNRENDERED {0}, {1}, {2} during {3} phase and {4} and {5}", string.Format("{0}:{1}", bundle.town.mapOffset.x, bundle.town.mapOffset.y), bundle.town.name, bundle.name, (data.isDraft) ? "DRAFT" : "MAIN", (bundle.isBundled) ? " is bundled :)" : "is not bundled :(", (bundle.isTileDataInBundle) ? " Tile Data IS In Bundle :)" : "TILE DATA MISSING!!!!!!!!!!" ); // by here all our splineSys and transition lists should be filled. // Bless it. bundle.MarkisBundledTrue(); TownGlobalObject.bundles[data.area.Coord] = bundle; // var bundletest = TownGlobalObject.GetTownBundle(data.area.Coord); var bundletest = TownGlobalObject.bundles[data.area.Coord]; // if (bundle2test == bundletest) // { Debug.LogFormat( " FINAL TEST {0} is null = {1}, {2} is {3}, {4} .isBundled is {5}", string.Format("{0}:{1}", data.area.Coord.x, data.area.Coord.z), bundletest == null, nameof(bundletest), bundletest, nameof(bundletest), (bundletest.isBundled) ? " Tile Data IS In Bundle :)" : "TILE DATA MISSING!!!!!!!!!!" ); // RenderOutlet(data, bundle, OutletFullList); bundle.MarkIsTileDataInBundleTrue(); // bundle.isTileDataInBundle = true; return; // } } }
public static void OnTileAppliedRenderMeshSplines(TerrainTile tile, TileData data, StopToken stop) { /* * * IN THE NEXT SECTION WE HANDLE THE SPLINE MESH RENDERING * * */ //TODO: Just make a parent holder for all splines on a tile and delete THAT //for (int i = tile.transform.childCount - 1; i > 0; i--) //{ // if (tile.transform.GetChild(i).name.StartsWith("__SPLINE__")) // DestroyImmediate(tile.transform.GetChild(i).gameObject); //} // we only do this on Main pass and when we actually have made something to process. if (data.isDraft)// || !TownGlobalObject.splinesNodesDataForTile.ContainsKey(data.area.Coord)) { return; } // int numberOfSplineNodes = 0; if (!TownGlobalObject.splinesNodesDataForTile.ContainsKey(data.area.Coord)) { // this is not a mesh spline tile return; } // By this point this should absolutely exist - unless there is no spline data! int totalNumberOfListsOfSplineMeshSplines = TownGlobalObject.splinesNodesDataForTile[data.area.Coord].Count; // There is nothing in the list if (totalNumberOfListsOfSplineMeshSplines == 0) { return; } //public void Test(ConcurrentDictionary<string, int> dictionary) //{ // dictionary.AddOrUpdate("key", 1, (key, current) => current += 2); //} // TownHolder.Instance.SplineMeshWallMasterSpawner.SetActive(false); List <GameObject> thingsToActivate = new List <GameObject>(); Coord locality = TownGlobalObject.GetIndexAtCoord(data.area.Coord); // Coord offset = locality - data.area.Coord; Coord offset = data.area.Coord; // SplinePowerExtended var DynamicHolder = TownHolder.Instance.MapMagicObjectReference.transform.Find(string.Format("Tile {0},{1}", offset.x, offset.z)); // For like the 4th time we check this TODO: Make it part of the Town Instancing TownGlobalObject.townsData[locality].TownGameObject ??= new GameObject(TownGlobalObject.townsData[locality].name); //create or use the holder now it has the right name. var go = TownGlobalObject.townsData[locality].TownGameObject; // We walk over the nodes assuming pairs? for (int i = 0; i < totalNumberOfListsOfSplineMeshSplines; i++) { //SplineMesh.Spline(); TypedSpline newValue = TownGlobalObject.GetSplineList(data.area.Coord)[i]; // No splines for us... if (newValue.nodes.Count == 0) { continue; } if ((newValue.nodes[1].Position - newValue.nodes[0].Position).sqrMagnitude == 0) { continue; } // Transform child = null; // TODO make this an actual hash and shove it in a table // string hash = string.Format("{0}_{1}_{4}_{5}|{2}_{3}", startvec.x, startvec.y, startvec.z, endvec.x, endvec.y, endvec.z); // string fullhash = string.Format("{0}_{1}|{4}_{5}|{2}_{3}", startvec.x, startvec.y, startvec.z, endvec.x, endvec.y, endvec.z); string hash = string.Format("__SPLINE__{0}__{2}|{3}__{5}", newValue.nodes[0].Position.x, newValue.nodes[0].Position.y, newValue.nodes[0].Position.z, newValue.nodes[newValue.nodes.Count - 1].Position.x, newValue.nodes[newValue.nodes.Count - 1].Position.y, newValue.nodes[newValue.nodes.Count - 1].Position.z); // TODO replace this with a lookup SOOOOON //foreach (Transform children in DynamicHolder.parent) //{ // // if(child.IsNull()) // child ??= children.Find(hash); //} //// we already rendered this remove the gmeobject then and do it again.? //if (child !=null) // { // var code = child.GetComponent<SplineMesh.Spline>(); // bool wipeit = false; // for (int nodeat = 0; nodeat < code.nodes.Count; nodeat++) // { // var thisnode = code.nodes[nodeat]; // if (thisnode.Position.y == 0) // { // wipeit = true; // } // } // if (wipeit) // { // DestroyImmediate(child.gameObject); // } // else // { // continue; // } // } var newSpline = ((objectRendered)newValue.chosenType) switch { objectRendered.wall => GameObject.Instantiate(TownHolder.Instance.SplineMeshWallMasterSpawner, DynamicHolder, true), objectRendered.fence => GameObject.Instantiate(TownHolder.Instance.SplineMeshFenceMasterSpawner, DynamicHolder, true), objectRendered.gatehouse => GameObject.Instantiate(TownHolder.Instance.SplineMeshGatehouseMasterSpawner, DynamicHolder, true), _ => GameObject.Instantiate(TownHolder.Instance.SplineMeshWallMasterSpawner, DynamicHolder, true), }; newSpline.name = hash + ((objectRendered)newValue.chosenType).ToString(); newSpline.GetComponent <SplineMesh.Spline>().nodes = newValue.nodes; if (newValue.tryToFloor) { var scrp = newSpline.AddComponent <AlignNodesToTerrainOnEnable>(); // scrp.checkVal = 0.07f; } thingsToActivate.Add(newSpline); // mark it as finally processed. but only if we havent already. // if (!TownGlobalObject.isSplinesMeshRenderedOnTile.ContainsKey(data.area.Coord)) // TownGlobalObject.isSplinesMeshRenderedOnTile.Add(data.area.Coord, true); } // Activate them as a group. for (int i = 0; i < thingsToActivate.Count; i++) { thingsToActivate[i].SetActive(true); } }
public static string ReturnTownName(Coord coord) { Coord locality = TownGlobalObject.GetIndexAtCoord(coord); return(TownGlobalObject.townsData[locality].name); }
private void MakeCity(ref int XzSpread, string HomeTownName, ref int timesThru, int timeThru) { // The new Town Coord newlocality = new Coord(); // New random choices for the towns coords int newXmaybe = 0; int newZmaybe = 0; int NextValidRandomPatchAmountFromTGOSRange = RandomGen.Next(TownGlobalObjectService.PatchCap, TownGlobalObjectService.PatchFloor); // Get A valid amount for the patch choice int randomPatches = NextValidRandomPatchAmountFromTGOSRange; // For "Distance" comparison float closest = 0; if (timeThru >= TownGlobalObjectService.TownRequests.Count) { newXmaybe = (int)(GetRandomXZrangedInt() * 1) + (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); newZmaybe = (int)(GetRandomXZrangedInt() * 1) + (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); // Test if the hit is closer than we would like, if it is then we need to try again timesThru = 0; while (closest < MinimumDistance + ((RandomGen.FlipACoin()) ? 0 : 1)) { if (timesThru >= ExpandXZsAfterTries) { timesThru = 0; Debug.Log("**********BAILED ON COUNT OUT**************"); XzSpread++; // closest = MinimumDistance +1; // continue; } // ADDED +1! newXmaybe += (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); newZmaybe += (RandomGen.FlipACoin() ? (int)MinimumDistance : -(int)MinimumDistance); // wraps the modulo regardless of sign //newXmaybe = (newXmaybe < 0) ? newXmaybe = -(Mathf.Abs(newXmaybe) % XzSpread) : newXmaybe % XzSpread; //newZmaybe = (newZmaybe < 0) ? newZmaybe = -(Mathf.Abs(newZmaybe) % XzSpread) : newZmaybe % XzSpread; // find a random coord with a magnitude high enough newlocality = new Coord(newXmaybe, newZmaybe); // convert it to 1000* size and 500 Y Vector3 p1 = newlocality.ToTileSizeCeilVector3(); // Debug.LogFormat("{0}", p1); // get hits // Collider[] hitColliders = Physics.OverlapSphere(p1, (MinimumDistance * ratio) * 1000f, layerMask);//, LayerMask.NameToLayer("MAPGEN")); /// Collider[] hitColliders = Physics.OverlapSphere(p1, (MinimumDistance) * 500f, layerMask);//, LayerMask.NameToLayer("MAPGEN")); Coord closetTownFound = TownGlobalObject.GetClosest(newlocality, TownGlobalObject.townsData.Keys.ToList()); //Scale the result based on city size. allow for 1.41 within reason var tinyCityApproxPatchCount = 100; var scalar = (0.002f * CityRatioGrowthApproximationmultiplier * Mathf.Min(TownGlobalObject.townsData[closetTownFound].Patches.Count - tinyCityApproxPatchCount, 10)); closest = Coord.Distance( newlocality, TownGlobalObject.GetClosest( newlocality, TownGlobalObject.townsData.Keys.ToList() ) ) - scalar; //// if we didn't hit at all just place it otherwise check the lengths //if (hitColliders.Length == 0) //{ // // Just skip the next bit and place this directly. // closest = MinimumDistance + 1; // // Debug.LogFormat("{0} is okay as a placement", newlocality); // break; //} //foreach (var hitCollider in hitColliders) //{ // var distance = (p1 - hitCollider.gameObject.transform.position).sqrMagnitude * 0.001f; // if (distance < MinimumDistance) // { // closest = distance; // // Debug.LogFormat(hitCollider.gameObject, "{0} for {1} from {2} at {3}", closest, hitCollider.gameObject.name, "newlocality", p1); // } // // closest = (distance < MinimumDistance) ? distance : closest; //} //// closest = TownGlobalObject.GetClosestMagnitude (newlocality , placesWePlaced); timesThru++; } } else // i < TownGlobalObjectService.TownRequests.Count { //home North etc... newlocality = new Coord( (int)TownGlobalObjectService.TownRequests[timeThru].Coord.x, (int)TownGlobalObjectService.TownRequests[timeThru].Coord.y); // Hometon } TownTileRenderer mrnewlocalityMaker = new TownTileRenderer(); // 0 triggers a random int amount = 0; if (timeThru < TownGlobalObjectService.TownRequests.Count) { if (timeThru == 0) { amount += TownHolder.Instance.MinCitySpreadreq; } else { amount += TownGlobalObjectService.TownRequests[timeThru].PatchesInSize; } } // Fill it with Joy AOTABundle newlocalityBundle = mrnewlocalityMaker.MakeATileBundle(newlocality, true, false, amount); // Debug.Log(TownGlobalObjectService.WorldMultiplier); //Town.Town newlocalitylazyTown; ////Handle the homes case //if (i ==0 ) //{ // newlocalitylazyTown = TownGlobalObject.towns.GetOrAdd(newlocality, k => TownGlobalObject.MakeTown(k, k.x, k.z, 0, 60)); //} //else //{ // newlocalitylazyTown = TownGlobalObject.towns.GetOrAdd(newlocality, k => TownGlobalObject.MakeTown(k, k.x, k.z, 0, randomPatches)); //} // TownGlobalObject.townsData[locality] = TownGlobalObject.MakeTown(locality, locality.x, locality.z); // THIS CONTAINS THE TOWN DATA TownGlobalObject.townsData[newlocality] = newlocalityBundle.town; if (timeThru < TownGlobalObjectService.TownRequests.Count) { TownGlobalObject.townsData[newlocality].name = TownGlobalObjectService.TownRequests[timeThru].Name; newlocalityBundle.town.coord = new Coord( (int)TownGlobalObjectService.TownRequests[timeThru].Coord.x, (int)TownGlobalObjectService.TownRequests[timeThru].Coord.y); } //handle the home case. if (timeThru == 0 && newlocality == new Coord(0)) { TownGlobalObject.townsData[newlocality].name = HomeTownName; TownGlobalObject.homeTown = TownGlobalObject.townsData[newlocality]; } // Debug.Log(TownGlobalObject.townsData[newlocality].name); // Bless it. // TODO: ADD METHOD WERE WE CAN PASS A TOWN newlocalityBundle.MarkisBundledTrue(); newlocalityBundle.MarkIsTileDataInBundleTrue(); TownGlobalObject.bundles[newlocality] = newlocalityBundle; AOTABundle reffedBundle = TownGlobalObject.bundles[newlocality]; //Debug.LogFormat( // "INIT TEST: bundle found for tile {5} town {0}: {7} : {3} with {1} SplineSysBundles and {2} TransitionsListBundles and {4} and {6}", // string.Format("{0}:{1}", newlocality.x, newlocality.z), // reffedBundle.SplineSysBundle.Count(), // reffedBundle.TransitionsListBundle.Count(), // reffedBundle.name, // (reffedBundle.isBundled) ? " is bundled :)" : "is not bundled :(", // newlocality, // (reffedBundle.isTileDataInBundle) ? " Tile Data IS In Bundle :)" : "TILE DATA MISSING!!!!!!!!!!", // reffedBundle.town.name // ); // in here we could then span every X|Z and prerender every likely tile to have it's data float size = CityRatioGrowthApproximationmultiplier * reffedBundle.town.Patches.Count; // rendering 36 tiles by default at max per city int roughTileGuess = (int)Mathf.Max(MinTileRender, Mathf.Min(MaxTileRender, Mathf.Ceil(size * 0.004f))); //return the even above, we will split this in half and use that as out "theoretical middle"; roughTileGuess = (roughTileGuess % 2 == 1) ? roughTileGuess + 1 : roughTileGuess; // Debug.LogFormat("approximate city size is {0} for {2} so roughly a {1} tile square", size , roughTileGuess, reffedBundle.name); // back assign the bundle names from the town for consistency in the editor (manually named and generated cities) reffedBundle.name = reffedBundle.town.name; // assign the non manually assigned cases if (timeThru >= TownGlobalObjectService.TownRequests.Count) { reffedBundle.town.coord = reffedBundle.coord; } if (TownGlobalObject.townsData[reffedBundle.town.coord].TownGameObject == null) { TownGlobalObject.townsData[reffedBundle.town.coord].TownGameObject = new GameObject(reffedBundle.town.name); } //create or use the holder now it has the right name. var go = TownGlobalObject.townsData[reffedBundle.town.coord].TownGameObject; GameObject CityHolder = new GameObject("MAP GEN COLLION HOLDER"); CityHolder.transform.parent = go.transform; CityHolder.transform.localPosition = Vector3.zero; CityHolder.transform.position = new Vector3(newlocality.x * 1000, 400, newlocality.z * 1000); //GameObject CityHolder = Instantiate<GameObject>(Temp, Temp.transform.position, Quaternion.identity); //Debug.LogFormat(CityHolder, "newlocalityBundle is {0} with {1} cells at {2} closest is {3}", // TownGlobalObject.bundles[newlocality].name, // TownGlobalObject.bundles[newlocality].town.Patches.Count, // newlocality, // closest); // add something for every city. float halfsize = size * 0.01f; // Add an item for the HUD // var HUD = Instantiate(TownHolder.Instance.HUDPrefab,CityHolder.transform); // HUD.transform.localPosition = Vector3.zero; var collisionCube = new Cube(reffedBundle.name, TownMeshRendererUtils.GetVertices((int)size, (int)size, -halfsize, -halfsize), halfsize, null, CityHolder.transform, false, false); collisionCube.Transform.localPosition = Vector3.zero; // collisionCube.GameObject.layer = LayerMask.NameToLayer("MAPGEN"); BoxCollider col = collisionCube.GameObject.AddComponent <BoxCollider>(); col.size = new Vector3(size, halfsize, size); // Register our BoxCollider for Disabling later. TownGlobalObject.renderedBoxColliders.Add(col); TownMeshRendererOptions rendererOptions = TownGlobalObjectService.rendererOptions; TownOptions skeletonOptions = TownGlobalObject.bundles[newlocality].town.Options; skeletonOptions.IOC = false; skeletonOptions.Farm = false; skeletonOptions.Roads = false; skeletonOptions.Walls = false; skeletonOptions.CityDetail = false; //TownGlobalObject.MeshRenderer = new TownMeshRenderer ( // reffedBundle.town, // skeletonOptions, // rendererOptions); //// This does the fancy world map colored sections TownGlobalObject.MeshRenderer.GenerateOverlay(); // Debug.LogFormat("{0} {1} ", reffedBundle.name, reffedBundle.town.name); // This does the fancy city overlay over the world map colored sections RenderTownMeshes(ref reffedBundle); // TownGlobalObject.bundles[newlocality].isTileDataInBundle = true; // Destroy(CityHolder); // Assign it back? TownGlobalObject.SetBundle(newlocality, reffedBundle); // TownGlobalObject.bundles[newlocality] = reffedBundle; // UnityEngine.Assertions.Assert.IsTrue( TownGlobalObject.bundles.ContainsKey(newlocality)); // COULD HAVE LOOPED HERE }