private BlueprintManager LoadBlueprints() { var blueprintManager = new BlueprintManager(); XmlSerializer blueprintManagerSerializer = null; Object[] blueprintAssets = Resources.LoadAll(this.BlueprintAssetsFolder); foreach (var blueprintObjectAsset in blueprintAssets) { var blueprintAsset = blueprintObjectAsset as TextAsset; if (blueprintAsset != null) { var blueprintStream = new MemoryStream(blueprintAsset.bytes); // Load blueprints. BlueprintManager subBlueprintManager = null; if (Application.isEditor || this.UseXmlInBuild) { if (blueprintManagerSerializer == null) { blueprintManagerSerializer = new XmlSerializer(typeof(BlueprintManager)); } try { subBlueprintManager = (BlueprintManager)blueprintManagerSerializer.Deserialize(blueprintStream); } catch (XmlException e) { Debug.LogError( string.Format( "Exception deserializing blueprint xml '{0}': {1}", blueprintAsset.name, e.Message)); } } else { BinaryDeserializer binaryDeserializer = new BinaryDeserializer(blueprintStream); subBlueprintManager = binaryDeserializer.Deserialize <BlueprintManager>(); } if (subBlueprintManager != null) { blueprintManager.AddBlueprints(subBlueprintManager); } } else { Debug.LogError(string.Format("Blueprint asset is no text asset: {0}", blueprintObjectAsset.name)); } } // Resolve parents. BlueprintUtils.ResolveParents(blueprintManager, blueprintManager); return(blueprintManager); }
public static IEnumerable <CodeInstruction> ClickReform(IEnumerable <CodeInstruction> instructions) { CodeMatcher matcher = new CodeMatcher(instructions) .MatchForward(true, new CodeMatch(x => x.IsLdloc()), new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(BuildTool_Reform), nameof(BuildTool_Click.castGroundPos))) ) .Advance(1) .InsertAndAdvance(new CodeInstruction(OpCodes.Ldarg_0)) .InsertAndAdvance(Transpilers.EmitDelegate <Action <BuildTool_Reform> >(tool => { currentGridData.snapGrid = new Vector2(tool.brushSize, tool.brushSize); float longitude = 0; float latitude = 0; BlueprintUtils.GetLongitudeLatitudeRad(tool.castGroundPos.normalized, ref longitude, ref latitude); if (isLockedLongitude) { longitude = lockLongitude; } if (isLockedLatitude) { latitude = lockLatitude; } tool.castGroundPos = BlueprintUtils.GetDir(longitude, latitude) * tool.castGroundPos.magnitude; })); return(matcher.InstructionEnumeration()); }
public async Task SendBlueprint([Remainder] string blueprint) { Stopwatch sw = new Stopwatch(); sw.Start(); StringBuilder sb = new StringBuilder(); Blueprint bp = BlueprintUtils.GetBlueprint(blueprint); if (bp == null) { await ReplyAsync($"Blueprint `{blueprint}` not found."); return; } sb.Append($"Research Cost: {bp.Cost}\n"); sb.Append($"Workbench Level: {bp.Workbench}\n"); EmbedBuilder eb = new EmbedBuilder(); EmbedFooterBuilder fb = new EmbedFooterBuilder(); eb.WithTitle("Blueprint"); eb.AddField($"{bp.Name}", $"{sb}"); eb.WithThumbnailUrl(bp.Icon); eb.WithColor(PremiumUtils.SelectEmbedColour(Context.User)); fb.WithText(PremiumUtils.SelectFooterEmbedText(Context.User, sw));; fb.WithIconUrl(Context.User.GetAvatarUrl()); eb.WithFooter(fb); await ReplyAsync("", false, eb.Build()); }
private static Vector2 GetMinLongLat(List <int> objectIds, BuildTool_BlueprintCopy copy) { float minLat = 10; float minLong = 10; float objLat = 0; float objLong = 0; foreach (int objectId in objectIds) { if (objectId > 0) { ref EntityData data = ref copy.factory.entityPool[objectId]; if (data.id == objectId) { BlueprintUtils.GetLongitudeLatitudeRad(data.pos.normalized, ref objLong, ref objLat); if (objLong < minLong) { minLong = objLong; } if (objLat < minLat) { minLat = objLat; } } }
public static BlueprintData GenerateBlueprint(List <int> objectIds, out Vector3 position) { position = Vector3.zero; if (GameMain.mainPlayer?.controller == null) { return(BlueprintData.CreateNew()); } if (GameMain.localPlanet == null) { return(BlueprintData.CreateNew()); } BuildTool_BlueprintCopy copy = GameMain.mainPlayer.controller.actionBuild.blueprintCopyTool; using (UndoManager.IgnoreAllEvents.On()) { copy.InitTool(); copy.selectedObjIds.Clear(); foreach (int objectId in objectIds) { copy.selectedObjIds.Add(objectId); } copy.blueprint = BlueprintData.CreateNew(); copy.RefreshBlueprintData(); Vector2 minPos = GetMinLongLat(objectIds, copy); float radius = GameMain.localPlanet.realRadius; position = BlueprintUtils.GetDir(minPos.x, minPos.y) * radius; position = copy.actionBuild.planetAux.Snap(position, true); } return(copy.blueprint); }
public static bool GenerateBlueprintData(BuildTool_BlueprintCopy __instance, ref bool __result) { if (UndoManager.IgnoreAllEvents.Value) { return(true); } __instance.hasErrorInserterData = false; if (__instance.selectedObjIds.Count == 0 && reformSelection.Count == 0) { __instance.blueprint.ResetContentAsEmpty(); __result = false; return(false); } foreach (int objId in __instance.selectedObjIds) { if (!__instance.CheckInserterDataLegal(objId)) { __instance.hasErrorInserterData = true; break; } } CopyToTempArray(__instance); BlueprintUtils.GenerateBlueprintData(__instance.blueprint, __instance.planet, __instance.actionBuild.planetAux, __instance._tmp_selected_ids, __instance._tmp_selected_cnt, __instance.divideLineRad); __instance.blueprint.CheckBuildingData(); Array.Clear(__instance._tmp_selected_ids, 0, __instance._tmp_selected_ids.Length); __result = true; return(false); }
public void DebugAddship() { BlueprintNew bp = BlueprintUtils.ReadBlueprintFile( Application.persistentDataPath + "/" + BlueprintUtils.FormatBlueprintFilename(DebugBlueprintNew) ); InstantiateShip(DebugShipAssembler.transform, bp); }
public static BPGratBox[] SplitGratBox(BPGratBox box) { int areaCount = BlueprintUtils.GetAreaCount(box.y, box.w, currentGrid.segment); BPGratBox[] areas = new BPGratBox[areaCount]; SplitGratBoxInTropicAreas(box, areas, currentGrid.segment); return(areas); }
public static void DisplayPos(float latitude, float longitude, Color color) { #if DEBUG Vector3 pos = BlueprintUtils.GetDir(longitude, latitude); pos *= GameMain.localPlanet.realRadius + 0.4f; DisplayPos(pos, color); #endif }
public static bool IsOnEdgeOfGratBox(this BPGratBox box, float longitudeRad, float latitudeRad, int segmentCount) { float latPerGrid = BlueprintUtils.GetLatitudeRadPerGrid(segmentCount); float longPerGrid = BlueprintUtils.GetLongitudeRadPerGrid(latitudeRad, segmentCount); BPGratBox smallBox = new BPGratBox(box.x + longPerGrid, box.y + latPerGrid, box.z - longPerGrid, box.w - latPerGrid); return(!smallBox.InGratBox(longitudeRad, latitudeRad)); }
private async Task <Task> _client_Ready() { await _client.SetGameAsync($"{prefix}help | {_client.Guilds.Count} Servers"); await LoggingUtils.UpdateStats(732215647135727716); BlueprintUtils.allBlueprints = await BlueprintUtils.GetAllBlueprints(); return(Task.CompletedTask); }
public void DetermineSelectGratBox() { if (cursorValid) { float longitudeRad = BlueprintUtils.GetLongitudeRad(castGroundPosSnapped.normalized); float longitudeRad2 = BlueprintUtils.GetLongitudeRad(lastGroundPosSnapped.normalized); float latitudeRad = BlueprintUtils.GetLatitudeRad(castGroundPosSnapped.normalized); bool flag = latitudeRad >= 1.5707864f || latitudeRad <= -1.5707864f; float num = flag ? 0f : longitudeRad - longitudeRad2; num = Mathf.Repeat(num + 3.1415927f, 6.2831855f) - 3.1415927f; selectArcBox.endLongitudeRad = selectArcBox.endLongitudeRad + num; selectArcBox.endLatitudeRad = latitudeRad; selectGratBox = selectArcBox; selectGratBox.x = selectArcBox.x < selectArcBox.z ? selectArcBox.x : selectArcBox.z; selectGratBox.z = selectArcBox.x > selectArcBox.z ? selectArcBox.x : selectArcBox.z; if (selectArcBox.x < selectArcBox.z) { if (selectGratBox.z > selectGratBox.x + 6.2831855f - 1E-05f - 4E-06f) { selectGratBox.z = selectGratBox.x + 6.2831855f - 1E-05f - 4E-06f; } selectGratBox.z = Mathf.Repeat(selectGratBox.z + 3.1415927f, 6.2831855f) - 3.1415927f; } else { if (selectGratBox.x < selectGratBox.z - 6.2831855f + 1E-05f + 4E-06f) { selectGratBox.x = selectGratBox.z - 6.2831855f + 1E-05f + 4E-06f; } selectGratBox.x = Mathf.Repeat(selectGratBox.x + 3.1415927f, 6.2831855f) - 3.1415927f; } selectGratBox.y = selectArcBox.y < selectArcBox.w ? selectArcBox.y : selectArcBox.w; selectGratBox.w = selectArcBox.y > selectArcBox.w ? selectArcBox.y : selectArcBox.w; float longitude = BlueprintUtils.GetLongitudeRadPerGrid(Mathf.Abs(castGroundPosSnapped.y) < Mathf.Abs(startGroundPosSnapped.y) ? castGroundPosSnapped.normalized : startGroundPosSnapped.normalized) * 0.33f; selectGratBox.Extend(longitude, 0.002f); if (!flag) { lastGroundPosSnapped = castGroundPosSnapped; } } }
private void InitSelectGratBox() { BlueprintUtils.GetMinimumGratBox(startGroundPosSnapped.normalized, ref selectGratBox); selectArcBox = selectGratBox; if (selectArcBox.y >= 1.5707864f) { selectArcBox.y = selectArcBox.w = 1.5707964f; selectArcBox.z = selectArcBox.x + 628.31854f; } else if (selectArcBox.y <= -1.5707864f) { selectArcBox.y = selectArcBox.w = -1.5707964f; selectArcBox.z = selectArcBox.x + 628.31854f; } lastSelectGratBox = selectGratBox; }
private static void LoadBlueprints() { // Build hierarchical blueprint manager for resolving parents. hierarchicalBlueprintManager = new HierarchicalBlueprintManager(); var blueprintAssets = Resources.LoadAll(BlueprintsFolder, typeof(TextAsset)); foreach (var blueprintAsset in blueprintAssets) { var blueprintTextAsset = blueprintAsset as TextAsset; if (blueprintTextAsset != null) { var blueprintStream = new MemoryStream(blueprintTextAsset.bytes); // Load blueprints. var blueprintManagerSerializer = new XmlSerializer(typeof(BlueprintManager)); try { // Right now, only a single blueprint file is supported. This might change in the future. blueprintManager = (BlueprintManager)blueprintManagerSerializer.Deserialize(blueprintStream); blueprintFileName = Application.dataPath.Substring( 0, Application.dataPath.Length - "Assets".Length) + AssetDatabase.GetAssetPath(blueprintTextAsset); hierarchicalBlueprintManager.AddChild(blueprintManager); } catch (XmlException e) { EditorUtility.DisplayDialog( string.Format("Error reading blueprint file {0}", blueprintAsset.name), e.Message, "Close"); return; } } } // Resolve parents of all blueprints. BlueprintUtils.ResolveParents(hierarchicalBlueprintManager, hierarchicalBlueprintManager); // Load components. inspectorTypeTable = InspectorTypeTable.FindInspectorTypes(typeof(IEntityComponent)); }
public static void LockLatitude() { if (!isLockedLatitude) { Vector3 pos = GetGroundCastPos(); if (pos.Equals(Vector3.zero)) { return; } BlueprintUtils.GetLongitudeLatitudeRad(pos.normalized, ref lockLongitude, ref lockLatitude); isLockedLatitude = true; isLockedLongitude = false; } else { isLockedLatitude = false; } }
public static Vector3 SnapModifiedInternal(this PlanetGrid grid, Vector3 pos) { pos.Normalize(); float latitude = BlueprintUtils.GetLatitudeRad(pos); float longitude = BlueprintUtils.GetLongitudeRad(pos); float latitudeCount = latitude / 6.28318548202515f * grid.segment; float longitudeSegmentCount = PlanetGrid.DetermineLongitudeSegmentCount(Mathf.FloorToInt(Mathf.Max(0.0f, Mathf.Abs(latitudeCount) - 0.1f)), grid.segment); float longitudeCount = longitude / 6.283185f * longitudeSegmentCount; float snappedLatitude = SnapWithOffset(latitudeCount, currentGridData, 1); float snappedLongitude = SnapWithOffset(longitudeCount, currentGridData, 0); float latRad = snappedLatitude / grid.segment * 6.28318548202515f; float longRad = snappedLongitude / longitudeSegmentCount * 6.28318548202515f; return(BlueprintUtils.GetDir(longRad, latRad)); }
public static void RefreshReformPreviews(BlueprintData _blueprintData, PlanetData _planet, int _dotsCursor, IntVector4[] _tropicGratBoxConditionInfo, float _yaw, int _segmentCnt, Vector4[] array) { if (!BlueprintCopyExtension.isEnabled) { return; } if (UndoManager.IgnoreAllEvents.Value) { return; } int yawCount = Mathf.FloorToInt(_yaw / 90f); float yawX = yawCount == 1 || yawCount == 2 ? -1f : 1f; float yawY = yawCount == 2 || yawCount == 3 ? -1f : 1f; float latitudeRadPerGrid = BlueprintUtils.GetLatitudeRadPerGrid(_segmentCnt); List <ReformData> reforms = BlueprintPasteExtension.reformPreviews; int reformsLength = _blueprintData.reforms.Length; for (int i = 0; i < reformsLength; i++) { ReformData reformData = _blueprintData.reforms[i]; for (int j = 0; j < _dotsCursor; j++) { ReformData reformPreview = reforms[reformsLength * j + i]; Vector4 areaData = array[j + reformData.areaIndex]; BlueprintUtilsPatch2.MirrorArea(ref areaData, yawX, yawY); float radPerGrid = BlueprintUtils.GetLongitudeRadPerGrid(areaData.y, _segmentCnt); Vector2 vector4 = BlueprintUtils.TransitionWidthAndHeight(_yaw, reformData.localLongitude - 0.5f, reformData.localLatitude - 0.5f); float longitudeRad = areaData.x + vector4.x * radPerGrid * yawX; float finalLatitude = areaData.y + vector4.y * latitudeRadPerGrid * yawY; finalLatitude = Math.Abs(finalLatitude) > 1.5707964f ? 1.5707964f * Math.Sign(finalLatitude) : finalLatitude; reformPreview.latitude = finalLatitude; reformPreview.longitude = longitudeRad; } } }
public static void SetOffset() { if (currentGridData.shouldShap) { currentGridData.shouldShap = false; } else { if (GameMain.localPlanet.aux == null) { return; } Vector3 pos = GetGroundCastPos(); if (pos.Equals(Vector3.zero)) { return; } BlueprintUtils.GetLongitudeLatitudeRad(pos.normalized, ref lockLongitude, ref lockLatitude); currentGridData.shouldShap = true; GameMain.localPlanet.aux.CalculateOffset(pos, currentGridData); } }
public static int ComputeFlattenTerrainReform(PlanetFactory factory, List <Vector3> points, Vector3 center, float fade0 = 3f) { PlanetRawData data = factory.planet.data; tmpLevelChanges.Clear(); float realRadius = factory.planet.realRadius; ushort[] heightData = data.heightData; float heightDiff = (heightData[data.QueryIndex(center)] - factory.planet.realRadius * 100f + 20f) * 0.01f * 2f; heightDiff = Mathf.Min(9f, Mathf.Abs(heightDiff)); fade0 += heightDiff; float steps = realRadius * 3.1415927f / (factory.planet.precision * 2f); int extent = Mathf.CeilToInt(fade0 * 1.414f / steps * 1.5f + 0.5f); int cost = 0; foreach (Vector3 vpos in points) { float longitude = BlueprintUtils.GetLongitudeRad(vpos.normalized); float longCount = 2 * longitude / Mathf.PI; float angleDistance = Mathf.Abs(longCount - Mathf.Round(longCount)); if (angleDistance <= 0.04) { cost += ScanTerrainDetailed(data, realRadius, vpos, extent, fade0); } else { cost += ScanTerrain(data, realRadius, vpos, extent, fade0); } } return(cost); }
public static IEnumerable <CodeInstruction> PasteSnap(IEnumerable <CodeInstruction> instructions) { CodeMatcher matcher = new CodeMatcher(instructions) .MatchForward(true, new CodeMatch(x => x.IsLdloc()), new CodeMatch(OpCodes.Stfld, AccessTools.Field(typeof(BuildTool_BlueprintPaste), nameof(BuildTool_Click.castGroundPos))) ) .Advance(1) .InsertAndAdvance(new CodeInstruction(OpCodes.Ldarg_0)) .InsertAndAdvance(Transpilers.EmitDelegate <Action <BuildTool_BlueprintPaste> >(tool => { float x = tool.blueprint.dragBoxSize_x; float y = tool.blueprint.dragBoxSize_y; currentGridData.snapGrid = new Vector2(x, y); float longitude = 0; float latitude = 0; BlueprintUtils.GetLongitudeLatitudeRad(tool.castGroundPos.normalized, ref longitude, ref latitude); if (isLockedLongitude) { longitude = lockLongitude; } if (isLockedLatitude) { latitude = lockLatitude; } tool.castGroundPos = BlueprintUtils.GetDir(longitude, latitude) * tool.castGroundPos.magnitude; })); matcher.MatchForward(false, new CodeMatch(OpCodes.Callvirt, AccessTools.Method(typeof(PlanetAuxData), nameof(PlanetAuxData.Snap)))) .SetInstruction(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(GridSnappingPatches), nameof(SnapModified)))); return(matcher.InstructionEnumeration()); }
public static bool CreateBox(BuildTool_BlueprintCopy __instance) { __instance.curActiveAreaGratBoxCursor = 0; CopyToTempArray(__instance); CopyReforms(); BPGratBox gratbox = ReformBPUtils.GetBoundingRange(__instance.planet, __instance.actionBuild.planetAux, __instance._tmp_selected_ids, __instance._tmp_selected_cnt, tmpReformList, __instance.divideLineRad); if (__instance.selectedObjIds.Count > 0 || reformSelection.Count > 0) { float longitudeRadPerGrid = BlueprintUtils.GetLongitudeRadPerGrid(gratbox.startLatitudeRad, __instance.segment); float latitudeRadPerGrid = BlueprintUtils.GetLatitudeRadPerGrid(__instance.segment); float extend_lng_grid = Math.Max(3f - Mathf.RoundToInt(gratbox.width / longitudeRadPerGrid) / 2, 1f); float extend_lat_grid = Math.Max(3f - Mathf.RoundToInt(gratbox.height / latitudeRadPerGrid) / 2, 1f); gratbox = BlueprintUtils.GetExtendedGratBox(gratbox, extend_lng_grid, extend_lat_grid); __instance.curActiveAreaGratBoxCursor = BlueprintUtils.SplitGratBoxInTropicAreas(gratbox, __instance.tropicGratBoxRadRangeArr, __instance.displayGratBoxArr, __instance.segment); Array.Clear(__instance._tmp_selected_ids, 0, __instance._tmp_selected_ids.Length); } return(false); }
public static void CalculateOffset(this PlanetAuxData auxData, Vector3 pos, GridData gridData) { if (auxData.activeGridIndex >= auxData.customGrids.Count) { return; } PlanetGrid grid = auxData.customGrids[auxData.activeGridIndex]; pos.Normalize(); float latitude = BlueprintUtils.GetLatitudeRad(pos); float longitude = BlueprintUtils.GetLongitudeRad(pos); float latitudeCount = latitude / 6.28318548202515f * grid.segment; float longitudeSegmentCount = PlanetGrid.DetermineLongitudeSegmentCount(Mathf.FloorToInt(Mathf.Max(0.0f, Mathf.Abs(latitudeCount) - 0.1f)), grid.segment); float longtitudeCount = longitude / 6.283185f * longitudeSegmentCount; float offsetLat = Snap(latitudeCount) * 5f; float offsetLong = Snap(longtitudeCount) * 5f; gridData.snapOffset = new Vector2(offsetLong % gridData.snapGrid.x, offsetLat % gridData.snapGrid.y); }
public static void OnUpdate(BuildTool_BlueprintPaste __instance) { if (!BlueprintCopyExtension.isEnabled) { return; } if (reformPreviews.Count <= 0) { return; } if (__instance.cannotBuild) { return; } tickCounter++; if (tickCounter >= 30) { tickCounter = 0; Vector3 center = Vector3.zero; tmpPoints.Clear(); PlatformSystem platformSystem = __instance.factory.platformSystem; foreach (ReformData preview in reformPreviews) { ReformBPUtils.GetSegmentCount(preview.latitude, preview.longitude, out float latCount, out float longCount, out int segmentCount); longCount = Mathf.Repeat(longCount, segmentCount); int reformIndex = platformSystem.GetReformIndexForSegment(latCount, longCount); if (reformIndex < 0) { continue; } int type = platformSystem.GetReformType(reformIndex); if (platformSystem.IsTerrainReformed(type)) { continue; } Vector3 pos = BlueprintUtils.GetDir(preview.longitude, preview.latitude); pos *= GameMain.localPlanet.realRadius + 0.2f; tmpPoints.Add(pos); center += pos; } lastCost = ReformBPUtils.ComputeFlattenTerrainReform(__instance.factory, tmpPoints, center); } string message = ""; int playerFoundationCount = __instance.player.package.GetItemCount(PlatformSystem.REFORM_ID); if (playerFoundationCount < tmpPoints.Count) { message = Format("NotEnoughFoundationsMessage".Translate(), tmpPoints.Count - playerFoundationCount) + "\n"; } else { message = Format("FoundCountMessage".Translate(), tmpPoints.Count) + "\n"; } if (__instance.cursorValid && !VFInput.onGUIOperate) { if (lastCost > 0) { __instance.actionBuild.model.cursorText = $"{message}{"沙土消耗".Translate()} {lastCost} {"个沙土".Translate()}"; } else if (lastCost == 0) { __instance.actionBuild.model.cursorText = $"{message}"; } else { int num2 = -lastCost; __instance.actionBuild.model.cursorText = $"{message}{"沙土获得".Translate()} {num2} {"个沙土".Translate()}"; } } }
public static bool CalculatePositions(BuildTool_BlueprintPaste tool, List <ReformData> reforms, Color[] colors) { ReformBPUtils.currentGrid = tool.factory.planet.aux.mainGrid; PlanetData planet = tool.factory.planet; PlatformSystem platformSystem = tool.factory.platformSystem; Vector3 center = Vector3.zero; tmpPoints.Clear(); foreach (ReformData preview in reforms) { ReformBPUtils.GetSegmentCount(preview.latitude, preview.longitude, out float latCount, out float longCount, out int segmentCount); longCount = Mathf.Repeat(longCount, segmentCount); int reformIndex = platformSystem.GetReformIndexForSegment(latCount, longCount); if (reformIndex < 0) { continue; } int type = platformSystem.GetReformType(reformIndex); if (platformSystem.IsTerrainReformed(type)) { continue; } Vector3 pos = BlueprintUtils.GetDir(preview.longitude, preview.latitude); pos *= planet.realRadius + 0.2f; tmpPoints.Add(pos); center += pos; } int cost = ReformBPUtils.ComputeFlattenTerrainReform(tool.factory, tmpPoints, center); if (NebulaModAPI.IsMultiplayerActive) { IMultiplayerSession session = NebulaModAPI.MultiplayerSession; if (!session.Factories.IsIncomingRequest.Value && !CheckItems(tool, cost, tmpPoints.Count)) { return(false); } if (session.LocalPlayer.IsHost) { int planetId = session.Factories.EventFactory?.planetId ?? GameMain.localPlanet?.id ?? -1; session.Network.SendPacketToStar(new ReformPasteEventPacket(planetId, reforms, colors, session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? session.LocalPlayer.Id : session.Factories.PacketAuthor), GameMain.galaxy.PlanetById(planetId).star.id); } //If client builds, he need to first send request to the host and wait for reply if (!session.LocalPlayer.IsHost && !session.Factories.IsIncomingRequest.Value) { session.Network.SendPacket(new ReformPasteEventPacket(GameMain.localPlanet?.id ?? -1, reforms, colors, session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? session.LocalPlayer.Id : session.Factories.PacketAuthor)); return(true); } } else { if (!CheckItems(tool, cost, tmpPoints.Count)) { return(false); } } if (colors != null && colors.Length > 0) { ApplyColors(tool, colors); } ReformBPUtils.FlattenTerrainReform(tool.factory, tmpPoints, center); VFAudio.Create("reform-terrain", null, center, true, 4); foreach (ReformData preview in reforms) { ReformBPUtils.GetSegmentCount(preview.latitude, preview.longitude, out float latCount, out float longCount, out int segmentCount); longCount = Mathf.Repeat(longCount, segmentCount); int reformIndex = platformSystem.GetReformIndexForSegment(latCount, longCount); if (reformIndex < 0) { continue; } int reformType = platformSystem.GetReformType(reformIndex); int reformColor = platformSystem.GetReformColor(reformIndex); if (reformType == preview.type && reformColor == preview.color) { continue; } platformSystem.SetReformType(reformIndex, preview.type); platformSystem.SetReformColor(reformIndex, preview.color); } return(true); }
private static float GetDivideLine(PlanetFactory factory, PlayerAction_Build actionBuild, List <int> objectIds) { if (objectIds.Count == 0) { return(-Mathf.PI); } _divideline_marks ??= new bool[1001]; Array.Clear(_divideline_marks, 0, 1001); int segment = 200; if (factory.planet.aux.activeGrid != null) { segment = factory.planet.aux.activeGrid.segment; } const double divisor = 2 * Mathf.PI / 1000; foreach (int objId in objectIds) { if (actionBuild.noneTool.GetPrefabDesc(objId) != null) { Vector3 position = actionBuild.noneTool.GetObjectPose(objId).position.normalized; float latitudeRad = Mathf.Asin(position.y); float longitudeRad = Mathf.Atan2(position.x, -position.z); int longitudeSegmentCount = BlueprintUtils.GetLongitudeSegmentCount(latitudeRad, segment); int latGrid = Mathf.CeilToInt((Mathf.CeilToInt((float)segment / longitudeSegmentCount) - 1) * 0.5f); int longGrid = (int)Math.Round((longitudeRad + Mathf.PI) / divisor); for (int i = -latGrid; i <= latGrid; i++) { int index = (int)Mathf.Repeat(longGrid + i, 1000f); _divideline_marks[index] = true; } } } int gridx1 = -1; int gridy1 = -1; int gridx2 = -1; int grixy2 = -1; int gridPos2 = 0; for (int j = 0; j < 1001; j++) { if (_divideline_marks[j]) { if (gridx2 == -1) { gridx2 = j; gridx1 = j; gridy1 = j; } else { int num11 = j - gridx2; if (num11 > gridPos2) { grixy2 = gridx2; gridPos2 = num11; } gridx2 = j; gridy1 = j; } } } int gridPos1 = gridx1 + 1000 - gridy1; if (gridPos1 > gridPos2) { int gridPos = gridy1 + gridPos1 / 2; return(Mathf.Repeat((float)(gridPos * divisor), 2 * Mathf.PI) - Mathf.PI); } gridPos2 = grixy2 + gridPos2 / 2; return((float)(gridPos2 * divisor - Mathf.PI)); }
public static void SwitchDelete(PlanetFactory factory, List <int> objectIds) { if (objectIds.Count <= 0) { return; } if (NebulaModAPI.IsMultiplayerActive) { IMultiplayerSession session = NebulaModAPI.MultiplayerSession; int planetId = session.Factories.TargetPlanet != NebulaModAPI.PLANET_NONE ? session.Factories.TargetPlanet : factory.planet?.id ?? -1; if (session.LocalPlayer.IsHost || !session.Factories.IsIncomingRequest.Value) { session.Network.SendPacket(new FastRemoveRequestPacket(planetId, objectIds.ToArray(), Array.Empty <int>(), session.Factories.PacketAuthor == NebulaModAPI.AUTHOR_NONE ? session.LocalPlayer.Id : session.Factories.PacketAuthor, false)); } if (!session.LocalPlayer.IsHost && !session.Factories.IsIncomingRequest.Value) { return; } } if (objectIds.Count < 25) { RegularDeleteEntities(factory, objectIds); return; } if (BlueprintTweaksPlugin.useFastDismantle.Value) { var player = GameMain.mainPlayer; PlayerAction_Build actionBuild = player.controller.actionBuild; float divLine = GetDivideLine(factory, actionBuild, objectIds); BPGratBox boundingBox = BlueprintUtils.GetBoundingRange(factory.planet, factory.planet.aux, objectIds.ToArray(), objectIds.Count, divLine); HashSet <int> edgeObjIds = new HashSet <int>(); int segmentCnt = 200; if (GameMain.localPlanet?.aux?.activeGrid != null) { segmentCnt = GameMain.localPlanet.aux.activeGrid.segment; } foreach (int objectId in objectIds) { if (objectId <= 0 || factory.entityPool[objectId].id != objectId) { continue; } if (boundingBox.IsOnEdgeOfGratBox(factory.entityPool[objectId].pos, segmentCnt)) { edgeObjIds.Add(objectId); } } if (edgeObjIds.Count == 0) { foreach (int objectId in objectIds) { if (objectId <= 0 || factory.entityPool[objectId].beltId <= 0) { continue; } RegularDeleteEntities(factory, objectIds); return; } } FastDeleteEntities(factory, objectIds, edgeObjIds.ToList()); } else { RegularDeleteEntities(factory, objectIds); } }
static IEnumerable <CodeInstruction> RefreshPreviews(IEnumerable <CodeInstruction> instructions, ILGenerator generator) { float MirrorBuildingRotation(float yaw, BlueprintBuilding building) { if (buildingsAxis.ContainsKey(building.modelIndex) && buildingsAxis[building.modelIndex] == MajorAxis.XAXIS) { return(MirrorRotation(yaw + 90f) - 90f); } return(MirrorRotation(yaw)); } CodeMatcher matcher = new CodeMatcher(instructions, generator) .MatchForward(true, new CodeMatch(OpCodes.Ldelem, typeof(Vector4)), new CodeMatch(OpCodes.Stloc_S), new CodeMatch(OpCodes.Ldloca_S)); matcher.Advance(1); object longAxisVar = matcher.Operand; while (matcher.Opcode != OpCodes.Stfld) { matcher.RemoveInstruction(); } matcher.RemoveInstructions(2); object latAxisVar = matcher.Operand; while (matcher.Opcode != OpCodes.Stfld) { matcher.RemoveInstruction(); } matcher.RemoveInstruction() .InsertAndAdvance(new CodeInstruction(OpCodes.Ldloc_S, longAxisVar)) .InsertAndAdvance(new CodeInstruction(OpCodes.Ldloc_S, latAxisVar)) .InsertAndAdvance(Transpilers.EmitDelegate <RefAction>(MirrorArea)); matcher.MatchForward(false, new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(BlueprintUtils), nameof(BlueprintUtils.TransitionWidthAndHeight)))) .Advance(-3) .RemoveInstruction().RemoveInstruction().RemoveInstruction() .SetInstruction(Transpilers.EmitDelegate <Func <float, BlueprintBuilding, Vector2> >((yaw, building) => { float x = building.localOffset_x; float y = building.localOffset_y; if ((mirrorLat && !mirrorLong || !mirrorLat && mirrorLong) && buildingsOffsets.ContainsKey(building.modelIndex)) { Vector2 offset = buildingsOffsets[building.modelIndex]; float rotatedYaw = MirrorBuildingRotation(building.yaw, building); offset = offset.Rotate(rotatedYaw + (mirrorLong ? 180 : 0)); x += offset.x; y += offset.y; } return(BlueprintUtils.TransitionWidthAndHeight(yaw, x, y)); })); matcher.MatchForward(false, new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BlueprintBuilding), nameof(BlueprintBuilding.yaw))) ).Advance(1) .InsertAndAdvance(new CodeInstruction(OpCodes.Ldloc_S, 30)) .InsertAndAdvance(Transpilers.EmitDelegate <Func <float, BlueprintBuilding, float> >(MirrorBuildingRotation)).Advance(2); matcher.MatchForward(false, new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BlueprintBuilding), nameof(BlueprintBuilding.yaw2))) ).Advance(1) .InsertAndAdvance(new CodeInstruction(OpCodes.Ldloc_S, 30)) .InsertAndAdvance(Transpilers.EmitDelegate <Func <float, BlueprintBuilding, float> >(MirrorBuildingRotation)); matcher.MatchForward(true, new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(BuildPreview), nameof(BuildPreview.desc))), new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(PrefabDesc), nameof(PrefabDesc.isInserter)))) .Advance(2); object previewVar2 = matcher.Operand; matcher.Advance(1) .InsertAndAdvance(new CodeInstruction(OpCodes.Ldloc_S, previewVar2)) .InsertAndAdvance(Transpilers.EmitDelegate <Action <BuildPreview> >(preview => { if (preview.input != null && preview.input.desc.slotPoses.Length > preview.inputFromSlot && !preview.input.desc.isBelt) { Quaternion invRot = Quaternion.Inverse(preview.input.lrot); Vector3 slotPosition = preview.lpos - preview.input.lpos; slotPosition = invRot * slotPosition; Quaternion slotRotation = invRot * preview.lrot; for (int i = 0; i < preview.input.desc.slotPoses.Length; i++) { Pose slotPose = preview.input.desc.slotPoses[i]; if (!((slotPose.position - slotPosition).sqrMagnitude < 0.1f)) { continue; } if (!slotPose.rotation.Approximately(slotRotation)) { continue; } if (preview.inputFromSlot == i) { break; } preview.inputFromSlot = i; break; } } if (preview.output != null && preview.output.desc.slotPoses.Length > preview.outputToSlot && !preview.output.desc.isBelt) { Quaternion invRot = Quaternion.Inverse(preview.output.lrot); Vector3 slotPosition = preview.lpos2 - preview.output.lpos; slotPosition = invRot * slotPosition; Quaternion slotRotation = invRot * (preview.lrot2 * Quaternion.Euler(0f, -180f, 0f)); for (int i = 0; i < preview.output.desc.slotPoses.Length; i++) { Pose slotPose = preview.output.desc.slotPoses[i]; if (!((slotPose.position - slotPosition).sqrMagnitude < 0.1f)) { continue; } if (!slotPose.rotation.Approximately(slotRotation)) { continue; } if (preview.outputToSlot == i) { break; } preview.outputToSlot = i; break; } } })); return(matcher.InstructionEnumeration()); }
public string DebugSaveBlueprint() { return(BlueprintUtils.SaveBlueprint(DebugBlueprintNew)); }
public static int SplitGratBoxInTropicAreas(BPGratBox _gratbox, BPGratBox[] _areaBoxes, int _segmentCnt = 200) { float startLong = _gratbox.x; float startLat = _gratbox.y; float endLong = _gratbox.z; float endLat = _gratbox.w; if (endLong < startLong - 1E-05f) { endLong += 6.2831855f; } int endIdx = BlueprintUtils.GetSnappedLatitudeGridIdx(endLat, _segmentCnt); int startIdx = BlueprintUtils.GetSnappedLatitudeGridIdx(startLat, _segmentCnt); float radPerGrid = BlueprintUtils.GetLatitudeRadPerGrid(_segmentCnt); int index = 0; int index1 = -1; float curLat = _gratbox.y; _areaBoxes[index] = BPGratBox.zero; _areaBoxes[index].y = _areaBoxes[index].w = curLat; int startSegCount = BlueprintUtils.GetLongitudeSegmentCount(startIdx, _segmentCnt); for (int i = startIdx; i <= endIdx; i++) { int curIdx = i + 1 > endIdx ? endIdx : i + 1; curLat = curIdx * radPerGrid; int curSegCount = startSegCount; int segmentCount = BlueprintUtils.GetLongitudeSegmentCount(curIdx, _segmentCnt); startSegCount = segmentCount; bool different = curSegCount != segmentCount; if (index1 < index) { float radPerGrid2 = BlueprintUtils.GetLongitudeRadPerGrid(curSegCount, _segmentCnt); float startCount = startLong / radPerGrid2; float endCount = endLong / radPerGrid2; float roundStartCount = BlueprintUtils._round(startCount); endCount = BlueprintUtils._round(endCount); float startLong2 = roundStartCount * radPerGrid2; float endLong2 = endCount * radPerGrid2; if (endLong2 > startLong2 + 6.2831855f - 1E-05f - 4E-06f) { endLong2 = startLong2 + 6.2831855f - radPerGrid2; } if (startLong2 < -3.1415927f) { startLong2 += 6.2831855f; } if (startLong2 > 3.1415927f) { startLong2 -= 6.2831855f; } if (endLong2 < -3.1415927f) { endLong2 += 6.2831855f; } if (endLong2 > 3.1415927f) { endLong2 -= 6.2831855f; } _areaBoxes[index].x = startLong2; _areaBoxes[index].z = endLong2; index1 = index; } if (different) { if (curIdx > 0) { curIdx = i > endIdx ? endIdx : i; curLat = curIdx * radPerGrid; } index++; _areaBoxes[index] = BPGratBox.zero; _areaBoxes[index].y = _areaBoxes[index].w = curLat; } else { if (curIdx < 0) { curIdx = i + 2 > endIdx ? endIdx : i + 2; curLat = curIdx * radPerGrid; } _areaBoxes[index].w = curLat; } } return(index + 1); }