public Renderer(TabControl mainTabs, string fileName, Package currentPackage) { MeshesToRender = new List<MeshObject>(); Animations = new List<Animation.Animation>(); cameras = new List<Tuple<string, Matrix4>>(); CurrentPackage = currentPackage; CurrentFileName = fileName; tabs = mainTabs; Debug = new DebugUtil(); Skeleton = new Skeleton(); // Default empty skeleton MaterialLoader = new MaterialLoader(CurrentFileName, CurrentPackage); }
void StreamProcessor_Closed(object sender, EventArgs e) { DebugUtil.Log("StreamClosed. Finish MovieStreamHelper"); Finish(); StreamClosed?.Invoke(sender, e); }
static IType Compiler_Class(string classname, bool bInterface, IList <string> basetype, string filename, IList <Token> tokens, int ibegin, int iend, bool EmbDebugToken, bool onlyGotType, IList <string> usinglist) { Type_Class typeClass = CQuark.AppDomain.GetTypeByKeywordQuiet(classname) as Type_Class; if (typeClass == null) { typeClass = new Type_Class(classname, bInterface, filename); } if (basetype != null && basetype.Count != 0 && onlyGotType == false) { List <IType> basetypess = new List <IType>(); foreach (string t in basetype) { IType type = CQuark.AppDomain.GetTypeByKeyword(t); basetypess.Add(type); } typeClass.SetBaseType(basetypess); } if (onlyGotType) { return(typeClass); } //if (env.useNamespace && usinglist != null) //{//使用命名空间,替换token // List<Token> newTokens = new List<Token>(); // for (int i = ibegin; i <= iend; i++) // { // if (tokens[i].type == TokenType.IDENTIFIER) // { // string ntype = null; // string shortname = tokens[i].text; // int startpos = i; // while (ntype == null) // { // foreach (var u in usinglist) // { // string ttype = u + "." + shortname; // if (env.GetTypeByKeywordQuiet(ttype) != null) // { // ntype = ttype; // break; // } // } // if (ntype != null) break; // if ((startpos + 2) <= iend && tokens[startpos + 1].text == "." && tokens[startpos + 2].type == TokenType.IDENTIFIER) // { // shortname += "." + tokens[startpos + 2].text; // startpos += 2; // if (env.GetTypeByKeywordQuiet(shortname) != null) // { // ntype = shortname; // break; // } // continue; // } // else // { // break; // } // } // if (ntype != null) // { // var t = tokens[i]; // t.text = ntype; // t.type = TokenType.TYPE; // newTokens.Add(t); // i = startpos; // continue; // } // } // newTokens.Add(tokens[i]); // } // tokens = newTokens; // ibegin = 0; // iend = tokens.Count - 1; //} typeClass.compiled = false; (typeClass._class as Class_CQuark).functions.Clear(); (typeClass._class as Class_CQuark).members.Clear(); //搜寻成员定义和函数 //定义语法 //Type id[= expr]; //函数语法 //Type id([Type id,]){block}; //属性语法 //Type id{get{},set{}}; bool bPublic = false; bool bStatic = false; if (EmbDebugToken)//SType 嵌入Token { typeClass.EmbDebugToken(tokens); } for (int i = ibegin; i <= iend; i++) { if (tokens[i].type == TokenType.KEYWORD && tokens[i].text == "public") { bPublic = true; continue; } else if (tokens[i].type == TokenType.KEYWORD && tokens[i].text == "private") { bPublic = false; continue; } else if (tokens[i].type == TokenType.KEYWORD && tokens[i].text == "static") { bStatic = true; continue; } else if (tokens[i].type == TokenType.TYPE || (tokens[i].type == TokenType.IDENTIFIER && tokens[i].text == classname))//发现类型 { IType idtype = CQuark.AppDomain.GetTypeByKeyword("null"); bool bctor = false; if (tokens[i].type == TokenType.TYPE)//类型 { if (tokens[i].text == classname && tokens[i + 1].text == "(") {//构造函数 bctor = true; i--; } else if (tokens[i + 1].text == "[" && tokens[i + 2].text == "]") { idtype = CQuark.AppDomain.GetTypeByKeyword(tokens[i].text + "[]"); i += 2; } else if (tokens[i].text == "void") { } else { idtype = CQuark.AppDomain.GetTypeByKeyword(tokens[i].text); } } if (tokens[i + 1].type == CQuark.TokenType.IDENTIFIER || bctor) //类型后面是名称 { string idname = tokens[i + 1].text; if (tokens[i + 2].type == CQuark.TokenType.PUNCTUATION && tokens[i + 2].text == "(")//参数开始,这是函数 { #if CQUARK_DEBUG DebugUtil.Log("发现函数:" + idname); #endif Class_CQuark.Function func = new Class_CQuark.Function(); func.bStatic = bStatic; func.bPublic = bPublic; int funcparambegin = i + 2; int funcparamend = FindBlock(tokens, funcparambegin); if (funcparamend - funcparambegin > 1) { int start = funcparambegin + 1; //Dictionary<string, ICQ_Type> _params = new Dictionary<string, ICQ_Type>(); for (int j = funcparambegin + 1; j <= funcparamend; j++) { if (tokens[j].text == "," || tokens[j].text == ")") { string ptype = ""; for (int k = start; k <= j - 2; k++) { ptype += tokens[k].text; } var pid = tokens[j - 1].text; var type = CQuark.AppDomain.GetTypeByKeyword(ptype); // _params[pid] = type; //func._params.Add(pid, type); if (type == null) { throw new Exception(filename + ":不可识别的函数头参数:" + tokens[funcparambegin].ToString() + tokens[funcparambegin].SourcePos()); } func._paramnames.Add(pid); func._paramtypes.Add(type); start = j + 1; } } } int funcbegin = funcparamend + 1; if (tokens[funcbegin].text == "{") { int funcend = FindBlock(tokens, funcbegin); Compiler_Expression_Block(tokens, funcbegin, funcend, out func.expr_runtime); if (func.expr_runtime == null) { DebugUtil.LogWarning("警告,该函数编译为null,请检查"); } (typeClass._class as Class_CQuark).functions.Add(idname, func); i = funcend; } else if (tokens[funcbegin].text == ";") { func.expr_runtime = null; (typeClass._class as Class_CQuark).functions.Add(idname, func); i = funcbegin; } else { throw new Exception(filename + ":不可识别的函数表达式:" + tokens[funcbegin].ToString() + tokens[funcbegin].SourcePos()); } } else if (tokens[i + 2].type == CQuark.TokenType.PUNCTUATION && tokens[i + 2].text == "{")//语句块开始,这是 getset属性 { //get set 成员定义 bool setpublic = true; bool haveset = false; for (int j = i + 3; j <= iend; j++) { if (tokens[j].text == "get") { setpublic = true; } if (tokens[j].text == "private") { setpublic = false; } if (tokens[j].text == "set") { haveset = true; } if (tokens[j].text == "}") { break; } } var member = new Class_CQuark.Member(); member.bStatic = bStatic; member.bPublic = bPublic; member.bReadOnly = !(haveset && setpublic); member.type = idtype; #if CQUARK_DEBUG DebugUtil.Log("发现Get/Set:" + idname); #endif //ICQ_Expression expr = null; if (tokens[i + 2].text == "=") { int jbegin = i + 3; int jdep; int jend = FindCodeAny(tokens, ref jbegin, out jdep); if (!Compiler_Expression(tokens, jbegin, jend, out member.expr_defvalue)) { DebugUtil.LogError("Get/Set定义错误"); } i = jend; } (typeClass._class as Class_CQuark).members.Add(idname, member); } else if (tokens[i + 2].type == CQuark.TokenType.PUNCTUATION && (tokens[i + 2].text == "=" || tokens[i + 2].text == ";"))//这是成员定义 { #if CQUARK_DEBUG DebugUtil.Log("发现成员定义:" + idname); #endif var member = new Class_CQuark.Member(); member.bStatic = bStatic; member.bPublic = bPublic; member.bReadOnly = false; member.type = idtype; //ICQ_Expression expr = null; if (tokens[i + 2].text == "=") { int posend = 0; for (int j = i; j < iend; j++) { if (tokens[j].text == ";") { posend = j - 1; break; } } int jbegin = i + 3; int jdep; int jend = FindCodeAny(tokens, ref jbegin, out jdep); if (jend < posend) { jend = posend; } if (!Compiler_Expression(tokens, jbegin, jend, out member.expr_defvalue)) { DebugUtil.LogError("成员定义错误"); } i = jend; } (typeClass._class as Class_CQuark).members.Add(idname, member); } bPublic = false; bStatic = false; continue; } else { throw new Exception(filename + ":不可识别的表达式:" + tokens[i].ToString() + tokens[i].SourcePos()); } } } typeClass.compiled = true; return(typeClass); }
private static async Task <bool> MoveToSpecifiedModeAsync(TargetDevice device, CancellationTokenSource cancel, string nextFunction, string nextState, bool isFirst = true) { var tcs = new TaskCompletionSource <bool>(); cancel?.Token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: false); PropertyChangedEventHandler status_observer = (sender, e) => { switch (e.PropertyName) { case nameof(CameraStatus.Status): var current = (sender as CameraStatus).Status; if (nextState == current) { DebugUtil.Log(() => "Camera state changed to " + nextState + " successfully."); tcs.TrySetResult(true); return; } else if (EventParam.NotReady != current) { DebugUtil.Log(() => "Unfortunately camera state changed to " + current); tcs.TrySetResult(false); return; } DebugUtil.Log(() => "It might be in transitioning state..."); break; default: break; } }; DebugUtil.Log(() => "Check current function at first..."); var getCurrentFailed = false; try { var already = await CheckCurrentFunction(device.Api.Camera, nextFunction).ConfigureAwait(false); if (already) { DebugUtil.Log(() => "Already in specified mode: " + nextFunction); return(true); } cancel.ThrowIfCancelled(); } catch (RemoteApiException e) { DebugUtil.Log(() => "Failed to get current state: " + e.StatusCode); if (isFirst) { getCurrentFailed = true; } else { DebugUtil.Log(() => "No recovery for second trial"); return(false); } } if (getCurrentFailed) { DebugUtil.Log(() => "Maybe in movie streaming mode..."); try { await device.Api.AvContent.StopStreamingAsync().ConfigureAwait(false); DebugUtil.Log(() => "Successfully stopped movie streaming mode"); } catch { } cancel.ThrowIfCancelled(); DebugUtil.Log(() => "Let's retry state transition"); return(await MoveToSpecifiedModeAsync(device, cancel, nextFunction, nextState, false)); } try { device.Status.PropertyChanged += status_observer; await device.Api.Camera.SetCameraFunctionAsync(nextFunction).ConfigureAwait(false); return(await tcs.Task); } catch (RemoteApiException e) { if (e.StatusCode == StatusCode.IllegalState) { DebugUtil.Log(() => "SetCameraFunction IllegalState: Already in specified mode"); return(true); } DebugUtil.Log(() => "Failed to change camera state: " + e.StatusCode); } finally { device.Status.PropertyChanged -= status_observer; } DebugUtil.Log(() => "Check current function again..."); try { return(await CheckCurrentFunction(device.Api.Camera, nextFunction).ConfigureAwait(false));; } catch (RemoteApiException e) { DebugUtil.Log(() => "Failed to get current state: " + e.StatusCode); return(false); } }
public virtual void OnScResponse(object s) { DebugUtil.Log("收到消息 " + ((IMessage)s).Descriptor.Name); }
public static void SetLocale(Locale locale) { sLocale = locale; DebugUtil.LogArgs(" -> Locale is now ", sLocale.ToString()); }
/// <inheritdoc /> public override TOut GetValueAt(dvec2 uv) { DebugUtil.AssertAllFinite(uv, nameof(uv)); return(Function.GetValueAt(Shift + Stretch * uv)); }
private void DetermineProxyLocations() { string[] scoutingLocations = Util.FileUtil.ReadScoutLocationFile(); HashSet <string> existingLocations = new HashSet <string>(); string[] debugLines = Util.FileUtil.ReadDebugFile(); List <Point2D> fromCurrentStart = new List <Point2D>(); List <Point2D> fromOtherStart = new List <Point2D>(); string mapName = Bot.Main.GameInfo.MapName; string mapStartString = mapName + "(" + Bot.Main.MapAnalyzer.StartLocation.X + ", " + Bot.Main.MapAnalyzer.StartLocation.Y + "):"; float dist; foreach (string line in scoutingLocations) { if (!line.StartsWith(mapName)) { continue; } existingLocations.Add(line); } /* * foreach (string line in debugLines) * { * if (!line.StartsWith(mapName)) * continue; * string position = line.Substring(line.LastIndexOf("(")); * position = position.Replace(")", "").Replace("(", ""); * string[] pos = position.Split(','); * Point2D point = new Point2D() { X = float.Parse(pos[0]), Y = float.Parse(pos[1]) }; * if (line.StartsWith(mapStartString)) * fromCurrentStart.Add(point); * else * fromOtherStart.Add(point); * DrawMap(mapName + " from current", fromCurrentStart); * DrawMap(mapName + " from other", fromOtherStart); * * Point2D basePos = null; * dist = 1000000; * foreach (Base b in Tyr.Bot.BaseManager.Bases) * { * float newDist = SC2Util.DistanceSq(b.BaseLocation.Pos, point); * if (newDist > dist) * continue; * dist = newDist; * basePos = b.BaseLocation.Pos; * } * string locationString = line.Substring(0, line.LastIndexOf("(")) + "(" + basePos.X + "," + basePos.Y + ")"; * if (!existingLocations.Contains(locationString)) * { * existingLocations.Add(locationString); * FileUtil.WriteScoutLocation(locationString); * } * } */ foreach (string line in scoutingLocations) { if (!line.StartsWith(mapStartString)) { continue; } string position = line.Substring(line.LastIndexOf("(")); position = position.Replace(")", "").Replace("(", ""); string[] pos = position.Split(','); Point2D point = new Point2D() { X = float.Parse(pos[0]), Y = float.Parse(pos[1]) }; ScoutLocations.Add(point); DebugUtil.WriteLine("Found scout location: " + point); } Point2D furthestScoutLocation = null; dist = 0; foreach (Point2D scoutLocation in ScoutLocations) { float newDist = SC2Util.DistanceSq(scoutLocation, Main.BaseLocation.Pos); if (newDist > dist) { dist = newDist; furthestScoutLocation = scoutLocation; } } HuntProxyTask1.ScoutBases = new List <Point2D>(); HuntProxyTask2.ScoutBases = new List <Point2D>(); /* * Point2D secondFarScoutLocation = null; * dist = 1000 * 1000; * foreach (Point2D scoutLocation in ScoutLocations) * { * if (scoutLocation == furthestScoutLocation) * continue; * float newDist = SC2Util.DistanceSq(scoutLocation, furthestScoutLocation); * if (newDist < dist) * { * dist = newDist; * secondFarScoutLocation = scoutLocation; * } * } * * HuntProxyTask1.ScoutBases.Add(furthestScoutLocation); * HuntProxyTask1.ScoutBases.Add(secondFarScoutLocation); * foreach (Point2D scoutLocation in ScoutLocations) * if (scoutLocation != furthestScoutLocation && scoutLocation != secondFarScoutLocation) * HuntProxyTask2.ScoutBases.Add(scoutLocation); */ HuntProxyTask1.ScoutBases = ScoutLocations; /* * * Point2D secondFarScoutLocation = null; * dist = 0; * foreach (Point2D scoutLocation in ScoutLocations) * { * float newDist = SC2Util.DistanceSq(scoutLocation, furthestScoutLocation); * if (newDist > dist) * { * dist = newDist; * secondFarScoutLocation = scoutLocation; * } * } * * HashSet<Point2D> assignedLocations = new HashSet<Point2D>(); * assignedLocations.Add(furthestScoutLocation); * assignedLocations.Add(secondFarScoutLocation); * HuntProxyTask1.ScoutBases.Add(furthestScoutLocation); * HuntProxyTask2.ScoutBases.Add(secondFarScoutLocation); * while (assignedLocations.Count < ScoutLocations.Count) * { * dist = 1000 * 1000; * Point2D nextLocation = null; * foreach (Point2D scoutLocation in ScoutLocations) * { * if (assignedLocations.Contains(scoutLocation)) * continue; * float newDist = SC2Util.DistanceSq(scoutLocation, furthestScoutLocation); * if (newDist < dist) * { * dist = newDist; * nextLocation = scoutLocation; * } * } * assignedLocations.Add(nextLocation); * HuntProxyTask1.ScoutBases.Add(nextLocation); * * if (assignedLocations.Count >= ScoutLocations.Count) * break; * dist = 1000 * 1000; * nextLocation = null; * foreach (Point2D scoutLocation in ScoutLocations) * { * if (assignedLocations.Contains(scoutLocation)) * continue; * float newDist = SC2Util.DistanceSq(scoutLocation, secondFarScoutLocation); * if (newDist < dist) * { * dist = newDist; * nextLocation = scoutLocation; * } * } * assignedLocations.Add(nextLocation); * HuntProxyTask2.ScoutBases.Add(nextLocation); * } */ HuntProxyTask1.KeepCycling = true; HuntProxyTask2.KeepCycling = true; }
private void GrantWish(UIMouseEvent evt, UIElement listeningelement) { Player player = Main.LocalPlayer; MyPlayer modplayer = Main.LocalPlayer.GetModPlayer <MyPlayer>(); bool UsedWish = false; switch (WishSelection) { case WishSelectionID.Power: if (modplayer.PowerWishesLeft > 0) { UsedWish = true; DoPowerWish(); SoundUtil.PlayCustomSound("Sounds/WishGranted", player.Center); } else { Main.PlaySound(SoundID.MenuClose); } break; case WishSelectionID.Wealth: UsedWish = true; DoWealthWish(); SoundUtil.PlayCustomSound("Sounds/WishGranted", player.Center); break; case WishSelectionID.Immortality: if (modplayer.ImmortalityWishesLeft > 0) { UsedWish = true; DoImmortalityWish(); SoundUtil.PlayCustomSound("Sounds/WishGranted", player.Center); } else { Main.PlaySound(SoundID.MenuClose); } break; case WishSelectionID.Genetic: UsedWish = true; DoGeneticWish(); SoundUtil.PlayCustomSound("Sounds/WishGranted", player.Center); break; case WishSelectionID.Awakening: if (modplayer.AwakeningWishesLeft > 0) { UsedWish = true; DoAwakeningWish(); SoundUtil.PlayCustomSound("Sounds/WishGranted", player.Center); } else { Main.PlaySound(SoundID.MenuClose); } break; default: break; } if (UsedWish) { DebugUtil.Log("Wish has been used."); WishSelection = WishSelectionID.None; DBZWorld.DestroyAndRespawnDragonBalls(); modplayer.WishActive = false; Main.PlaySound(SoundID.MenuClose); } Initialize(); DBZMOD.ActivateWishmenu(); }
public bool Load(IReader reader) { char[] array = reader.ReadChars(SAVE_HEADER.Length); if (array == null || array.Length != SAVE_HEADER.Length) { return(false); } for (int i = 0; i < SAVE_HEADER.Length; i++) { if (array[i] != SAVE_HEADER[i]) { return(false); } } int num = reader.ReadInt32(); int num2 = reader.ReadInt32(); if (num != 7 || num2 > 11) { DebugUtil.LogWarningArgs($"SAVE FILE VERSION MISMATCH! Expected {7}.{11} but got {num}.{num2}"); return(false); } ClearScene(); try { int num3 = reader.ReadInt32(); for (int j = 0; j < num3; j++) { string text = reader.ReadKleiString(); int num4 = reader.ReadInt32(); int num5 = 0; num5 = reader.ReadInt32(); Tag key = TagManager.Create(text); if (!prefabMap.TryGetValue(key, out GameObject value)) { DebugUtil.LogWarningArgs("Could not find prefab '" + text + "'"); reader.SkipBytes(num5); } else { List <SaveLoadRoot> value2 = new List <SaveLoadRoot>(num4); sceneObjects[key] = value2; for (int k = 0; k < num4; k++) { SaveLoadRoot x = SaveLoadRoot.Load(value, reader); if ((UnityEngine.Object)x == (UnityEngine.Object)null) { Debug.LogError("Error loading data [" + text + "]"); return(false); } } } } } catch (Exception ex) { DebugUtil.LogErrorArgs("Error deserializing prefabs\n\n", ex.ToString()); throw ex; } return(true); }
public SolidList(ChunkID id, long size, long position) : base(id, size, position) { DebugUtil.EnsureCondition( id == ChunkID.BCHUNK_SPEED_ESOLID_LIST_CHUNKS, () => $"Expected BCHUNK_SPEED_ESOLID_LIST_CHUNKS, got {id.ToString()}"); }
public void Sim33ms(float dt) { Vector2I xy = default(Vector2I); Vector2I xy2 = default(Vector2I); Vector3 vector = acceleration * dt; int num = co2Items.Count; for (int i = 0; i < num; i++) { CO2 cO = co2Items[i]; cO.velocity += vector; cO.lifetimeRemaining -= dt; Grid.PosToXY(cO.transform.GetPosition(), out xy); cO.transform.SetPosition(cO.transform.GetPosition() + cO.velocity * dt); Grid.PosToXY(cO.transform.GetPosition(), out xy2); int num2 = Grid.XYToCell(xy.x, xy.y); int num3 = num2; for (int num4 = xy.y; num4 >= xy2.y; num4--) { int num5 = Grid.XYToCell(xy.x, num4); bool flag = !Grid.IsValidCell(num5) || cO.lifetimeRemaining <= 0f; if (!flag) { Element element = Grid.Element[num5]; flag = (element.IsLiquid || element.IsSolid); } if (flag) { bool flag2 = false; int num6; if (num3 != num5) { num6 = num3; flag2 = true; } else { num6 = num5; while (Grid.IsValidCell(num6)) { Element element2 = Grid.Element[num6]; if (!element2.IsLiquid && !element2.IsSolid) { flag2 = true; break; } num6 = Grid.CellAbove(num6); } } cO.TriggerDestroy(); if (flag2) { SimMessages.ModifyMass(num6, cO.mass, byte.MaxValue, 0, CellEventLogger.Instance.CO2ManagerFixedUpdate, cO.temperature, SimHashes.CarbonDioxide); num--; co2Items[i] = co2Items[num]; co2Items.RemoveAt(num); } else { DebugUtil.LogWarningArgs("Couldn't emit CO2"); } break; } num3 = num5; } } }
private async Task DecodeLiveviewFrame(JpegPacket packet, bool retry = false) { Action trailingTask = null; if (LiveviewImageBitmap == null || sizeChanged) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { var writeable = await LiveviewUtil.AsWriteableBitmap(packet.ImageData, Dispatcher); OriginalLvSize = new BitmapSize { Width = (uint)writeable.PixelWidth, Height = (uint)writeable.PixelHeight }; var magnification = CalcLiveviewMagnification(); DebugUtil.Log(() => { return("Decode: mag: " + magnification + " offsetV: " + LvOffsetV); }); dpi = DEFAULT_DPI / magnification; RefreshOverlayControlParams(magnification); trailingTask = () => { if (Context?.Target?.Status != null) { RotateLiveviewImage(Context.Target.Status.LiveviewOrientationAsDouble, (sender, arg) => { RefreshOverlayControlParams(magnification); }); } sizeChanged = false; }; }); } else { rwLock.EnterWriteLock(); try { var toDelete = LiveviewImageBitmap; trailingTask = () => { // Dispose after it is drawn toDelete?.Dispose(); }; } finally { rwLock.ExitWriteLock(); } } using (var stream = new InMemoryRandomAccessStream()) { await stream.WriteAsync(packet.ImageData.AsBuffer()); stream.Seek(0); var bmp = await CanvasBitmap.LoadAsync(LiveviewImageCanvas, stream, (float)dpi); var size = bmp.SizeInPixels; rwLock.EnterWriteLock(); try { LiveviewImageBitmap = bmp; } finally { rwLock.ExitWriteLock(); } if (!OriginalLvSize.Equals(size)) { DisposeLiveviewImageBitmap(); if (!retry) { await DecodeLiveviewFrame(packet, true); } return; } } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { LiveviewImageCanvas.Invalidate(); trailingTask?.Invoke(); }); if (PendingPakcet != null) { var task = DecodeLiveviewFrame(PendingPakcet); PendingPakcet = null; } }
/// <inheritdoc /> public double RayIntersect(Ray ray) { dvec3 rayStart = ray.StartPosition; dvec3 rayDirection = ray.Direction; DebugUtil.AssertAllFinite(rayStart, nameof(rayStart)); DebugUtil.AssertAllFinite(rayDirection, nameof(rayDirection)); // Since we raytrace only using a cylindrical surface that is horizontal and at the origin, we // first shift and rotate the ray such that we get the right orientation: dvec3 start = CenterCurve.GetStartPosition(); dvec3 end = CenterCurve.GetEndPosition(); DebugUtil.AssertAllFinite(start, nameof(start)); DebugUtil.AssertAllFinite(end, nameof(end)); dvec3 tangent = CenterCurve.GetTangentAt(0.0).Normalized; dvec3 normal = CenterCurve.GetNormalAt(0.0).Normalized; dvec3 binormal = CenterCurve.GetBinormalAt(0.0).Normalized; DebugUtil.AssertAllFinite(tangent, nameof(tangent)); DebugUtil.AssertAllFinite(normal, nameof(normal)); DebugUtil.AssertAllFinite(binormal, nameof(binormal)); double length = dvec3.Distance(start, end); DebugUtil.AssertFinite(length, nameof(length)); // CenterCurve is guaranteed to be a LineSegment, since the base property CenterCurve is masked by this // class' CenterCurve property that only accepts a LineSegment, and similarly this class' constructor only // accepts a LineSegment. The following mathematics, which assumes that the central axis is a line segment, // is therefore valid. dmat3 rotationMatrix = new dmat3(normal, binormal, tangent / length).Transposed; dvec3 rescaledRay = rotationMatrix * (rayStart - start); dvec3 newDirection = rotationMatrix * rayDirection.Normalized; double x0 = rescaledRay.x; double y0 = rescaledRay.y; double z0 = rescaledRay.z; double a = newDirection.x; double b = newDirection.y; double c = newDirection.z; // Raytrace using a cylindrical surface equation x^2 + y^2. The parameters in the following line // represent the coefficients of the expanded cylindrical surface equation, after the substitution // x = x_0 + a t and y = y_0 + b t: QuarticFunction surfaceFunction = new QuarticFunction(x0 * x0 + y0 * y0, 2.0 * (x0 * a + y0 * b), a * a + b * b, 0.0, 0.0); IEnumerable <double> intersections = Radius.SolveRaytrace(surfaceFunction, z0, c); // The previous function returns a list of intersection distances. The value closest to 0.0f represents the // closest intersection point. double minimum = Single.PositiveInfinity; foreach (double i in intersections) { // Calculate the 3d point at which the ray intersects the cylinder: dvec3 intersectionPoint = rayStart + i * rayDirection; // Find the closest point to the intersectionPoint on the centerLine. // Get the vector v from the start of the cylinder to the intersection point: dvec3 v = intersectionPoint - start; // ...And project this vector onto the center line: double t = -dvec3.Dot(intersectionPoint, tangent * length) / (length * length); // Now we have the parameter t on the surface of the SymmetricCylinder at which the ray intersects. // Find the angle to the normal of the centerLine, so that we can determine whether the // angle is within the bound of the pie-slice at position t: dvec3 centerLineNormal = CenterCurve.GetNormalAt(t); dvec3 centerLineBinormal = CenterCurve.GetBinormalAt(t); dvec3 d = intersectionPoint - CenterCurve.GetPositionAt(t); double correctionShift = Math.Sign(dvec3.Dot(d, centerLineBinormal)); double phi = (correctionShift * Math.Acos(dvec3.Dot(d, centerLineNormal))) % (2.0 * Math.PI); // Determine if the ray is inside the pie-slice of the cylinder that is being displayed, // otherwise discard: if (phi > StartAngle.GetValueAt(t) && phi < EndAngle.GetValueAt(t) && i >= 0.0) { minimum = Math.Sign(i) * Math.Min(Math.Abs(minimum), Math.Abs(i)); } } return(minimum); }
public CarList(ChunkID id, long size, long position) : base(id, size, position) { DebugUtil.EnsureCondition( id == ChunkID.BCHUNK_CARINFO_ARRAY, () => $"Expected BCHUNK_CARINFO_ARRAY, got {id.ToString()}"); }
public override void OnFrame(Tyr tyr) { if (tyr.Observation.ActionErrors != null) { foreach (ActionError error in tyr.Observation.ActionErrors) { DebugUtil.WriteLine("Error with ability " + error.AbilityId + ": " + error.Result); } } foreach (WorkerDefenseTask task in WorkerDefenseTask.Tasks) { task.CannonDefenseRadius = 20; } TransformTask.Task.ThorsToSingleTarget(); if (tyr.EnemyStrategyAnalyzer.FourRaxDetected) { FourRaxSuspected = true; } if (!FourRaxSuspected) { Point2D enemyRamp = tyr.MapAnalyzer.GetEnemyRamp(); int enemyBarrackWallCount = 0; foreach (Unit enemy in tyr.Enemies()) { if (enemyRamp == null) { break; } if (enemy.UnitType == UnitTypes.BARRACKS && SC2Util.DistanceSq(enemy.Pos, enemyRamp) <= 5.5 * 5.5) { enemyBarrackWallCount++; } } if (enemyBarrackWallCount >= 2) { WorkerScoutTask.Task.Stopped = true; WorkerScoutTask.Task.Clear(); FourRaxSuspected = true; } } if (tyr.Frame % 224 == 0) { if (tyr.OrbitalAbilityManager.ScanCommands.Count == 0) { UnitLocation scanTarget = null; foreach (UnitLocation enemy in Tyr.Bot.EnemyMineManager.Mines) { scanTarget = enemy; break; } if (scanTarget != null) { tyr.OrbitalAbilityManager.ScanCommands.Add(new Managers.ScanCommand() { FromFrame = tyr.Frame, Pos = SC2Util.To2D(scanTarget.Pos) }); } } } if (tyr.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) == 1 && Completed(UnitTypes.SIEGE_TANK) > 0 && tyr.Frame <= 22.4 * 60 * 4 && Count(UnitTypes.COMMAND_CENTER) < 3) { IdleTask.Task.OverrideTarget = SC2Util.Point((tyr.MapAnalyzer.GetMainRamp().X + Natural.BaseLocation.Pos.X) / 2f, (tyr.MapAnalyzer.GetMainRamp().Y + Natural.BaseLocation.Pos.Y) / 2f); } else if (FourRaxSuspected && Completed(UnitTypes.SIEGE_TANK) > 0 && Count(UnitTypes.COMMAND_CENTER) == 2) { IdleTask.Task.OverrideTarget = SC2Util.Point((NaturalDefensePos.X + Natural.BaseLocation.Pos.X) / 2f, (NaturalDefensePos.Y + Natural.BaseLocation.Pos.Y) / 2f); } else if (Count(UnitTypes.COMMAND_CENTER) > 3) { IdleTask.Task.OverrideTarget = OverrideDefenseTarget; } else { IdleTask.Task.OverrideTarget = null; } if (ReapersDetected) { SiegeTask.Task.Stopped = true; TimingAttackTask.Task.RequiredSize = 30; TimingAttackTask.Task.RetreatSize = 8; TimingAttackTask.Task.Stopped = false; } else { SiegeTask.Task.Stopped = true; if (Completed(UnitTypes.LIBERATOR) >= 4 || FoodUsed() >= 198) { TimingAttackTask.Task.RequiredSize = 50; } else { TimingAttackTask.Task.RequiredSize = 70; } TimingAttackTask.Task.RetreatSize = 12; TimingAttackTask.Task.Stopped = false; TimingAttackTask.Task.CustomControllers = AttackMicroControllers; } /* * else * { * TimingAttackTask.Task.Stopped = true; * * if (Completed(UnitTypes.LIBERATOR) >= 4 || FoodUsed() >= 198) || SiegeTask.Task.RequiredSize = 50; || else || SiegeTask.Task.RequiredSize = 70; || SiegeTask.Task.RetreatSize = 12; || SiegeTask.Task.Stopped = false; || SiegeTask.Task.CustomControllers = AttackMicroControllers; ||}*/ bool attacking = (!TimingAttackTask.Task.Stopped && TimingAttackTask.Task.IsNeeded()) || (!SiegeTask.Task.Stopped && SiegeTask.Task.IsNeeded()); foreach (Task task in VikingDefenseTasks) { task.Stopped = attacking; } foreach (Task task in TankDefenseTasks) { task.Stopped = attacking; } foreach (Task task in LiberatorDefenseTasks) { task.Stopped = attacking; } int defendingTanksPerBase = 2; if (Completed(UnitTypes.SIEGE_TANK) >= 4 * (Count(UnitTypes.COMMAND_CENTER) - 1)) { defendingTanksPerBase = 4; } else if (Completed(UnitTypes.SIEGE_TANK) >= 3 * (Count(UnitTypes.COMMAND_CENTER) - 1)) { defendingTanksPerBase = 3; } foreach (DefenseSquadTask task in TankDefenseTasks) { task.MaxDefenders = defendingTanksPerBase; } foreach (DefenseSquadTask task in DefenseSquadTask.Tasks) { task.Priority = 4; task.MaxDefenders = 3; task.Stopped = task.Base != Main; } DefenseTask.AirDefenseTask.ExpandDefenseRadius = 20; DefenseTask.GroundDefenseTask.ExpandDefenseRadius = 20; DefenseTask.AirDefenseTask.MaxDefenseRadius = 80; DefenseTask.GroundDefenseTask.MaxDefenseRadius = 80; if (Count(UnitTypes.COMMAND_CENTER) > 2) { DefenseTask.GroundDefenseTask.MainDefenseRadius = 40; DefenseTask.AirDefenseTask.MainDefenseRadius = 40; } else { DefenseTask.GroundDefenseTask.MainDefenseRadius = 30; DefenseTask.AirDefenseTask.MainDefenseRadius = 30; } if (tyr.EnemyStrategyAnalyzer.BioDetected) { ReapersDetected = false; } else if ((tyr.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) > 4 || tyr.EnemyStrategyAnalyzer.Count(UnitTypes.BANSHEE) >= 1) && tyr.Frame < 22.4 * 600) { ReapersDetected = true; } BunkerDefendersTask.Task.LeaveBunkers = !tyr.EnemyStrategyAnalyzer.BioDetected && tyr.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) >= 1 && (tyr.EnemyStrategyAnalyzer.TotalCount(UnitTypes.REAPER) >= 2 || tyr.Frame <= 22.4 * 60 * 4); if (ReapersDetected) { DefenseSquadTask.Enable(CycloneDefenseTasks, false, false); } else { foreach (DefenseSquadTask task in CycloneDefenseTasks) { task.Stopped = true; task.Clear(); } } if (tyr.EnemyStrategyAnalyzer.Count(UnitTypes.STARPORT_TECH_LAB) + tyr.EnemyStrategyAnalyzer.Count(UnitTypes.BANSHEE) > 0 || (tyr.EnemyStrategyAnalyzer.Count(UnitTypes.FACTORY) > 0 && tyr.Frame <= 22.4 * 60 * 2.5)) { SuspectCloackedBanshees = true; } if (FourRaxSuspected) { tyr.OrbitalAbilityManager.SaveEnergy = 0; } else { tyr.OrbitalAbilityManager.SaveEnergy = 50; } if (tyr.TargetManager.PotentialEnemyStartLocations.Count == 1 && !ScanTimingsSet && tyr.Frame >= 22.4 * 60 * 2.25 && !FourRaxSuspected ) { ScanTimingsSet = true; tyr.OrbitalAbilityManager.ScanCommands.Add(new ScanCommand() { Pos = tyr.TargetManager.PotentialEnemyStartLocations[0], FromFrame = (int)(22.4 * 60 * 2.5) }); } }
private void Initialize() { Console.WriteLine("Start Ext2.Initialize"); mBuffer = new byte[mBackend.BlockSize]; fixed(byte *xBufferAddress = &mBuffer[0]) { mBufferAddress = xBufferAddress; } // first get the superblock; var mBufferAsSuperblock = (SuperBlock *)mBufferAddress; int xAddr = (int)mBufferAddress; Console.WriteLine("Buffer address: " + xAddr); Console.WriteLine("Start reading superblock"); mBackend.ReadBlock(2, mBuffer); Console.WriteLine("End reading"); mSuperblock = *mBufferAsSuperblock; DebugUtil.Send_Ext2SuperBlock(mSuperblock); // read the group descriptors Console.WriteLine("INodeCount: " + mSuperblock.INodesCount); Console.WriteLine("INode#1: " + mBufferAddress[0]); Console.WriteLine("INode#2: " + mBufferAddress[1]); Console.WriteLine("INode#3: " + mBufferAddress[2]); Console.WriteLine("INode#4: " + mBufferAddress[3]); Console.WriteLine("BlockCount: " + mSuperblock.BlockCount); Console.WriteLine("INodesPerGroup: " + (int)mSuperblock.INodesPerGroup); if (mSuperblock.INodesPerGroup == 0x4000) { Console.WriteLine("INodesPerGroup has correct value!"); } uint xGroupDescriptorCount = mSuperblock.INodesCount / mSuperblock.INodesPerGroup; mGroupDescriptors = new GroupDescriptor[xGroupDescriptorCount]; var xDescriptorPtr = (GroupDescriptor *)mBufferAddress; Console.WriteLine("Process GroupDescriptors: " + xGroupDescriptorCount); //Console.ReadLine(); for (int i = 0; i < xGroupDescriptorCount; i++) { Console.WriteLine("Processing GroupDescriptor " + i); uint xATABlock; if (BlockSize == 1024) { xATABlock = (BlockSize * 2) / mBackend.BlockSize; } else { xATABlock = (BlockSize) / mBackend.BlockSize; } xATABlock += (uint)(i / 16); if ((i % 16) == 0) { Console.WriteLine("Read new GroupDescriptorBlock"); mBackend.ReadBlock(xATABlock, mBuffer); Console.WriteLine("End Read"); } mGroupDescriptors[i] = xDescriptorPtr[i % 16]; Console.WriteLine("End of GroupDescriptor check"); } Console.WriteLine("Send GroupDescriptors to log"); DebugUtil.Send_Ext2GroupDescriptors(mGroupDescriptors); }
public void Unwrap(ref List <MeshManager.Triangle> triangles) { DebugUtil.StartStopwatch("Unwrap"); List <Vector3> vertices; List <Vector3> normals; Dictionary <int, Dictionary <DraggableMeshPoint, int> > smoothingGroups; GetVertices(triangles, out vertices, out normals, out smoothingGroups); // 6 faces Dictionary <int, Vector2>[] uvs = new Dictionary <int, Vector2> [6]; for (int i = 0; i < uvs.Length; i++) { uvs[i] = new Dictionary <int, Vector2>(); } Vector3 min, max; //float minF, maxF; GetBoundingBox(vertices, out min, out max); //GetBoundingBox(vertices, out minF, out maxF); for (int i = 0; i < vertices.Count; i++) { Vector3 vec = vertices[i] - min; vec.x /= (max.x - min.x); vec.y /= (max.y - min.y); vec.z /= (max.z - min.z); float[] ang = new float[6]; ang[0] = Vector3.Angle(Vector3.right, normals[i]); //+x ang[1] = Vector3.Angle(Vector3.left, normals[i]); //-x ang[2] = Vector3.Angle(Vector3.up, normals[i]); //+y ang[3] = Vector3.Angle(Vector3.down, normals[i]); //-y ang[4] = Vector3.Angle(Vector3.forward, normals[i]); //+z ang[5] = Vector3.Angle(Vector3.back, normals[i]); //-z int minIndex = 0; float minVal = 9999.0f; for (int k = 0; k < ang.Length; k++) { if (ang[k] < minVal) { minVal = ang[k]; minIndex = k; } } Vector2 uv; switch (minIndex) { default: case 0: uv.x = vec.z; uv.y = vec.y; break; case 1: uv.x = 1.0f - vec.z; uv.y = vec.y; break; case 2: uv.x = vec.x; uv.y = vec.z; break; case 3: uv.x = vec.x; uv.y = 1.0f - vec.z; break; case 4: uv.x = 1.0f - vec.x; uv.y = vec.y; break; case 5: uv.x = vec.x; uv.y = vec.y; break; } uvs[minIndex][i] = uv; } // Pack UVs var combinedUvs = PackUVs(uvs, vertices.Capacity, 0.3f); // Update triangles with uvs foreach (var triangle in triangles) { for (int i = 0; i < triangle.m_points.Length; i++) { int index = smoothingGroups[triangle.m_smoothGroupIndex][triangle.m_points[i]]; triangle.m_uvs[i] = combinedUvs[index]; } } DebugUtil.EndStopwatch("Unwrap"); }
/// <summary> /// Bundle打包,并生成Version配置文件 /// 1.Bundle包导出至AssttBundleOut内 /// 2.把基础包拷贝到StreamingAssets文件夹内 /// 3.生成VersionInfo文件,拷贝到StreamingAssets内 /// </summary> public static void BuildAllAssetBundle(BuildTarget buildTarget = BuildTarget.NoTarget) { if (AssetBundleConfig.Inst.CompleteAsset) { string _assetVersion = AssetBundleConfig.Inst.AssetVersion; } else { string _assetVersion = CommonUtil.SubAssetVersionIncrease(AssetBundleConfig.Inst.AssetVersion); } if (!Directory.Exists(FilePathTools.assetBundleOutPath)) { Directory.CreateDirectory(FilePathTools.assetBundleOutPath); } exportPathParent = FilePathTools.assetBundleOutPath + "/" + AssetBundleConfig.Inst.AssetVersion; //EditorUtility.DisplayCancelableProgressBar("打包中...", "0%", 0.01f); AssetDatabase.RemoveUnusedAssetBundleNames(); assetBundleVersionInfo = new AssetBundleVersionInfo { Version = AssetBundleConfig.Inst.AssetVersion, preloadConditions = AssetBundleConfig.Inst.preloadConditions }; //EditorUtility.DisplayCancelableProgressBar("打包中...", "10%", 0.1f); //删除老的bundle,(如果不删除可能会引起打包崩溃,但基本没发生过) //(不删除老的bundle,重新打bundle会很快) //if (Directory.Exists(exportPath)) // Directory.Delete(exportPath, true); if (Directory.Exists(FilePathTools.streamingAssetsPath_Platform)) { Directory.Delete(FilePathTools.streamingAssetsPath_Platform, true); } DirectoryInfo outFold = new DirectoryInfo(FilePathTools.assetBundleOutPath); DirectoryInfo[] outBundleFolds = outFold.GetDirectories(); if (outBundleFolds.Length > 0) { DirectoryInfo exportFold = outBundleFolds[0]; string foldName = exportFold.Name; if (foldName != AssetBundleConfig.Inst.AssetVersion) { exportFold.MoveTo(exportPathParent); } } if (!Directory.Exists(exportPathParent)) { Directory.CreateDirectory(exportPathParent); } //EditorUtility.ClearProgressBar(); float deltaProgress = 0.8f / AssetBundleConfig.Inst.Groups.Length; //按Group打包 for (int i = 0; i < AssetBundleConfig.Inst.Groups.Length; i++) { float currProgress = 0.1f + deltaProgress * i; //EditorUtility.DisplayCancelableProgressBar("打包中...", currProgress * 100 + "%", currProgress); BundleGroup bundleGroup = AssetBundleConfig.Inst.Groups[i]; BuildGroup(bundleGroup, Path.Combine(exportPathParent, bundleGroup.GroupName), buildTarget); } //保存version信息,把version存到exportPathParent的上一级目录 string assetBundleVersionInfoStr = assetBundleVersionInfo.ToString(); string versionFileName = "Version.txt"; FileUtil.CreateFile(exportPathParent, versionFileName, assetBundleVersionInfoStr); //EditorUtility.DisplayCancelableProgressBar("打包中...", "90%", 0.90f); //拷贝 InInitialPacket==true 的包到streamingasset文件夹下,Version.txt文件也拷贝到streamingasset文件夹下 if (!Directory.Exists(FilePathTools.streamingAssetsPath_Platform)) { Directory.CreateDirectory(FilePathTools.streamingAssetsPath_Platform); } foreach (BundleGroup group in AssetBundleConfig.Inst.Groups) { List <string> paths = group.GetBundlePaths(GetBundleMethod.All); // 拷贝到AssetBundleOutRelease下 foreach (string item in paths) { string srcFile = Path.Combine(Path.Combine(exportPathParent, group.GroupName), item.ToLower()); string destFile = Path.Combine(FilePathTools.assetBundleOutReleasePath + "/" + AssetBundleConfig.Inst.AssetVersion, item.ToLower()); //判断文件的存在 if (System.IO.File.Exists(srcFile)) { //存在文件 FileUtil.CopyFile(srcFile, destFile); } } if (!group.BaseGroup && !AssetBundleConfig.Inst.CompleteAsset) { continue; } // 拷贝到streamingAsset下 foreach (string item in paths) { string srcFile = Path.Combine(Path.Combine(exportPathParent, group.GroupName), item.ToLower()); string destFile = FilePathTools.streamingAssetsPath_Platform + "/" + item.ToLower(); //判断文件的存在 if (System.IO.File.Exists(srcFile)) { //存在文件 FileUtil.CopyFile(srcFile, destFile); } } } FileUtil.CopyFile(exportPathParent + "/" + versionFileName, FilePathTools.streamingAssetsPath_Platform + "/" + "Version.txt"); //如果不是CompleteAsset,AssetbundleOut下Version的副素材版本号+1。 //if (!AssetBundleConfig.Inst.CompleteAsset) //{ // FileUtil.CreateFile(exportPathParent, "Version.txt", assetBundleVersionInfo.SubAssetVersionIncrease().ToString()); //} //AssetBundleOut文件夹下Version拷贝到All文件夹下 FileUtil.CopyFile(exportPathParent + "/" + versionFileName, FilePathTools.assetBundleOutReleasePath + "/" + AssetBundleConfig.Inst.AssetVersion + "/" + "Version.txt"); //EditorUtility.DisplayCancelableProgressBar("打包中...", "100%", 1f); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); DebugUtil.Log("AssetBundle 打包成功"); }
private Vector2[] PackUVs(Dictionary <int, Vector2>[] uvs, int uvCount, float startScale, int triesLeft) { DebugUtil.StartStopwatch("UV Packing"); Vector2[] combinedUvs = new Vector2[uvCount]; if (triesLeft == 0) { Debug.LogWarning("No tries left for UV packing"); return(combinedUvs); } Dictionary <int, Vector2>[] originalUVs = (Dictionary <int, Vector2>[])uvs.Clone(); Rect[] rects = new Rect[uvs.Length]; Rect[] startRects = new Rect[uvs.Length]; for (int i = 0; i < uvs.Length; i++) { Vector2 min = new Vector2(9999, 9999); Vector2 max = new Vector2(-9999, -9999); var keys = new List <int>(uvs[i].Keys); foreach (var k in keys) { var uv = uvs[i][k]; uv.Scale(new Vector2(startScale, startScale)); if (uv.x < min.x) { min.x = uv.x; } if (uv.y < min.y) { min.y = uv.y; } if (uv.x > max.x) { max.x = uv.x; } if (uv.y > max.y) { max.y = uv.y; } uvs[i][k] = uv; } rects[i].min = min; rects[i].max = max; startRects[i].min = min; startRects[i].max = max; rects[i].position += new Vector2(0.01f, 0.01f) * i; } float stepSize = 0.08f; bool noOverlap = false; int iterations = 0; int maxIterations = 1000; while (!noOverlap && iterations < maxIterations) { noOverlap = true; iterations++; for (int i = 0; i < rects.Length; i++) { for (int k = 0; k < rects.Length; k++) { if (k == i) { continue; } if (rects[i].Overlaps(rects[k])) { noOverlap = false; // From k to i Vector2 dif = rects[i].position - rects[k].position; if (dif.sqrMagnitude > stepSize * stepSize) { dif = dif.normalized * stepSize; } Vector2 randOffset = Random.insideUnitCircle * 0.01f; dif += randOffset; if (dif.x < 0) { if (rects[i].xMin + dif.x < 0) { dif.x = 0 - rects[i].xMin; } } else { if (rects[i].xMax + dif.x > 1.0) { dif.x = 1 - rects[i].xMax; } } if (dif.y < 0) { if (rects[i].yMin + dif.y < 0) { dif.y = 0 - rects[i].yMin; } } else { if (rects[i].yMax + dif.y > 1.0) { dif.y = 1 - rects[i].yMax; } } rects[i].position += dif; } } } } for (int i = 0; i < uvs.Length; i++) { foreach (var uv in uvs[i]) { combinedUvs[uv.Key] = uv.Value + rects[i].position - startRects[i].position; } } DebugUtil.EndStopwatch("UV Packing"); if (noOverlap) { Debug.Log("Succes packing UVs"); } else { Debug.Log("Packing failed, retrying with smaller scale"); combinedUvs = PackUVs(originalUVs, uvCount, startScale * 0.8f, triesLeft - 1); } return(combinedUvs); }
/// <summary> /// API:parts /// </summary> /// <param name ="slot"></param> /// <param name ="partType"></param> public void DeleteWeaponPart(EWeaponSlotType slot, EWeaponPartType partType) { var agent = GetWeaponAgent(slot); if (!agent.IsValid()) { return; } WeaponPartsStruct lastParts = agent.PartsScan; var defaultParts = agent.WeaponConfigAssy.DefaultParts; int newPart = 0; //移除配件后装备默认配件 switch (partType) { case EWeaponPartType.LowerRail: newPart = defaultParts.LowerRail; break; case EWeaponPartType.UpperRail: newPart = defaultParts.UpperRail; break; case EWeaponPartType.Muzzle: newPart = defaultParts.Muzzle; break; case EWeaponPartType.Magazine: newPart = defaultParts.Magazine; break; case EWeaponPartType.Stock: newPart = defaultParts.Stock; break; case EWeaponPartType.SideRail: newPart = defaultParts.SideRail; break; case EWeaponPartType.Bore: newPart = defaultParts.Bore; break; case EWeaponPartType.Interlock: newPart = defaultParts.Interlock; break; case EWeaponPartType.Feed: newPart = defaultParts.Feed; break; case EWeaponPartType.Brake: newPart = defaultParts.Brake; break; case EWeaponPartType.Trigger: newPart = defaultParts.Trigger; break; default: break; } if (newPart <= 0) { newPart = 0; } var newParts = WeaponPartUtil.ModifyPartItem(lastParts, partType, newPart); agent.BaseComponent.ApplyParts(newParts); if (slot == HeldSlotType) { if (processHelper.FilterRefreshWeapon()) { ApperanceRefreshABreath(HeldWeaponAgent.BreathFactor); } } WeaponPartsRefreshStruct refreshData = new WeaponPartsRefreshStruct(); refreshData.weaponInfo = agent.ComponentScan; refreshData.slot = slot; refreshData.oldParts = lastParts; refreshData.newParts = newParts; RefreshWeaponModelAndParts(refreshData); DebugUtil.MyLog("Delete Weapon part:" + refreshData, DebugUtil.DebugColor.Green); }
//--- Class Methods --- private static int Main(string[] args) { bool useTty = true; TimeSpan time; // process command line arguments XDoc config = new XDoc("config"); for (int i = 0; i < args.Length; i += 2) { string key = args[i].ToLowerInvariant(); string value = ((i + 1) < args.Length) ? args[i + 1] : string.Empty; switch (key) { case "help": PrintUsage(); return(0); case "notty": --i; useTty = false; break; case "capture-stack-trace": --i; DebugUtil.CaptureStackTrace = true; break; case "nolog": --i; // NOTE (steveb): this option used to disable logging, but was removed in favor of using the automatic re-reading of app.config by log4net break; case "settings": case "config": if (!File.Exists(value)) { WriteError(key, "config file not found"); return(1); } config = XDocFactory.LoadFrom(value, MimeType.XML); break; case "script": config.Start("script").Attr("src", value).End(); break; case "ip": case "host": config.Elem("host", value); break; case "http-port": case "path-prefix": case "server-path": case "server-name": case "storage-dir": case "connect-limit": case "apikey": case "guid": config.Elem(key, value); break; case "public-uri": case "root-uri": config.Elem("uri.public", value); break; case "service-dir": config.Elem("storage-dir", value); break; case "collect-interval": int interval; if (!int.TryParse(value, out interval)) { WriteError(key, "invalid collection interval (must be an integer representing seconds)"); return(1); } if (interval > 0) { DebugUtil.SetCollectionInterval(TimeSpan.FromSeconds(interval)); } break; case "auth": config.Elem("authentication-shemes", value); break; default: WriteError(key, "unknown setting"); return(1); } } try { // initialize environment if (config["apikey"].IsEmpty) { string apikey = StringUtil.CreateAlphaNumericKey(32); config.Elem("apikey", apikey); Console.WriteLine("Dream Host APIKEY: {0}", apikey); } Console.WriteLine("-------------------- initializing"); time = DebugUtil.Stopwatch(() => { _host = new DreamHost(config); }); Console.WriteLine("-------------------- initialized {0} secs", time.TotalSeconds); // execute scripts time = DebugUtil.Stopwatch(() => { _host.RunScripts(config, null); }); Console.WriteLine("-------------------- ready {0} secs", time.TotalSeconds); // for UNIX systems, let's also listen to SIGTERM if (SysUtil.IsUnix) { new Thread(SigTermHandler) { IsBackground = true }.Start(); } // check if we can use the console if (useTty) { int debuglevel = 0; // wait for user input then exit while (_host.IsRunning) { Thread.Sleep(250); #region Interactive Key Handler if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.Q: case ConsoleKey.Escape: case ConsoleKey.Spacebar: Console.WriteLine("Shutting down"); return(0); case ConsoleKey.G: Console.WriteLine("Full garbage collection pass"); System.GC.Collect(); break; case ConsoleKey.C: Console.Clear(); break; case ConsoleKey.D: switch (++debuglevel) { default: debuglevel = 0; Threading.RendezVousEvent.CaptureTaskState = false; DebugUtil.CaptureStackTrace = false; Console.WriteLine("Debug capture: none"); break; case 1: Threading.RendezVousEvent.CaptureTaskState = true; DebugUtil.CaptureStackTrace = false; Console.WriteLine("Debug capture: task-state only"); break; case 2: Threading.RendezVousEvent.CaptureTaskState = true; DebugUtil.CaptureStackTrace = true; Console.WriteLine("Debug capture: task-state and stack-trace"); break; } break; case ConsoleKey.I: { Console.WriteLine("--- System Information ---"); // show memory Console.WriteLine("Allocated memory: {0}", GC.GetTotalMemory(false)); // show threads int workerThreads; int completionThreads; int dispatcherThreads; int backgroundThreads; AsyncUtil.GetAvailableThreads(out workerThreads, out completionThreads, out dispatcherThreads, out backgroundThreads); int maxWorkerThreads; int maxCompletionThreads; int maxDispatcherThreads; int maxBackgroundThreads; AsyncUtil.GetMaxThreads(out maxWorkerThreads, out maxCompletionThreads, out maxDispatcherThreads, out maxBackgroundThreads); Console.WriteLine("Thread-pool worker threads available: {0} (max: {1})", workerThreads, maxWorkerThreads); Console.WriteLine("Thread-pool completion threads available: {0} (max: {1})", completionThreads, maxCompletionThreads); Console.WriteLine("Dispatcher threads available: {0} (max: {1})", dispatcherThreads, maxDispatcherThreads); Console.WriteLine("Thread-pool background worker threads available: {0} (max: {1})", backgroundThreads, maxBackgroundThreads); // show pending/waiting timers var taskTimerStats = Tasking.TaskTimerFactory.GetStatistics(); Console.WriteLine("Pending timer objects: {0}", taskTimerStats.PendingTimers); Console.WriteLine("Queued timer objects: {0}", taskTimerStats.QueuedTimers); Console.WriteLine("Timer retries: {0}", taskTimerStats.Retries); // show activities var activities = _host.ActivityMessages; Console.WriteLine("Host activities: {0}", activities.Length); foreach (var activity in activities) { Console.WriteLine("* {0}: {1}", activity.Created.ToString(XDoc.RFC_DATETIME_FORMAT), activity.Description); } // show pending tasks Console.WriteLine("Pending rendez-vous events: {0}", Threading.RendezVousEvent.PendingCounter); Console.WriteLine("Pending results: {0}", AResult.PendingCounter); lock (Threading.RendezVousEvent.Pending) { int count = 0; foreach (var entry in Threading.RendezVousEvent.Pending.Values) { ++count; if (entry.Key != null) { var context = entry.Key.GetState <DreamContext>(); if (context != null) { Console.WriteLine("--- DreamContext for pending rendez-vous event #{0} ---", count); Console.WriteLine(context.Uri.ToString(false)); } } Console.WriteLine(); if (entry.Value != null) { Console.WriteLine("--- Stack trace for pending rendez-vous event #{0} ---", count); Console.WriteLine(entry.Value.ToString()); } } } Console.WriteLine("--------------------------"); } break; case ConsoleKey.H: Console.WriteLine("Help:"); Console.WriteLine(" Q - quit application"); Console.WriteLine(" ESC - quit application"); Console.WriteLine(" SPACE - quit application"); Console.WriteLine(" G - full garbage collection"); Console.WriteLine(" C - clear screen"); Console.WriteLine(" D - set debug capture level"); Console.WriteLine(" I - show system information (memory, threads, pending tasks)"); Console.WriteLine(" H - this help text"); break; } } #endregion } } else { _host.WaitUntilShutdown(); } } finally { Console.WriteLine("-------------------- shutting down"); TaskTimerFactory.ShutdownAll(); if (_host != null) { _host.Dispose(); } } return(0); }
public void Initialize(Cockpit cockpit) { cockpit.Name = "modelCockpit"; // Configure how the cockpit moves //cockpit.PositionMode = Cockpit.MovementMode.TrackPosition; // [RMS] use orientation mode to make cockpit follow view orientation. // (however default widgets below are off-screen!) //cockpit.PositionMode = Cockpit.MovementMode.TrackOrientation; var tracker = SmoothCockpitTracker.Enable(cockpit); //cockpit.TiltAngle = 10.0f; cockpit.TiltAngle = 0.0f; tracker.ShowIndicator = false; FScene Scene = cockpit.Scene; //ISurfaceBoxRegion region = new CylinderBoxRegion() { Radius = 1.0f, MinHeight = -1.0f, MaxHeight = 0.3f, HorzDegreeLeft = 50, HorzDegreeRight = 50 }; ISurfaceBoxRegion region = new SphereBoxRegion() { Radius = 1.0f, VertDegreeBottom = 30, VertDegreeTop = 10, HorzDegreeLeft = 55, HorzDegreeRight = 55 }; //Frame3f f = new Frame3f(new Vector3f(0, 0, 1), Vector3f.AxisZ); //f.RotateAround(Vector3f.Zero, Quaternionf.AxisAngleD(Vector3f.AxisX, 10)); //f.RotateAround(Vector3f.Zero, Quaternionf.AxisAngleD(Vector3f.AxisY, -50)); //ISurfaceBoxRegion region = new PlaneBoxRegion() { // Frame = f, Dimensions = new AxisAlignedBox2f(-0.15f, -0.5f, 0.5f, 0.2f) //}; BoxContainer leftPanelContainer = new BoxContainer(new BoxRegionContainerProvider(cockpit, region)); PinnedBoxes3DLayoutSolver leftPanelLayout = new PinnedBoxes3DLayoutSolver(leftPanelContainer, region); PinnedBoxesLayout layout = new PinnedBoxesLayout(cockpit, leftPanelLayout) { StandardDepth = 0.0f }; cockpit.AddLayout(layout, "3D", true); ISurfaceBoxRegion cylregion = new CylinderBoxRegion() { Radius = 1.0f, MinHeight = -1.0f, MaxHeight = 0.2f, HorzDegreeLeft = 55, HorzDegreeRight = 50 }; BoxContainer cylPanelContainer = new BoxContainer(new BoxRegionContainerProvider(cockpit, cylregion)); PinnedBoxes3DLayoutSolver cylPanelLayout = new PinnedBoxes3DLayoutSolver(cylPanelContainer, cylregion); PinnedBoxesLayout cyl_layout = new PinnedBoxesLayout(cockpit, cylPanelLayout) { StandardDepth = 0.0f }; cockpit.AddLayout(cyl_layout, "cylinder", true); float button_width = 0.32f; float button_height = 0.075f; float button_spacing = 0.015f; float text_height = button_height * 0.6f; float row_y_shift = button_height + button_spacing; Func <string, float, HUDLabel> MakeButtonF = (label, buttonW) => { HUDLabel button = new HUDLabel() { Shape = OrthogenUI.MakeMenuButtonRect(buttonW, button_height), TextHeight = text_height, AlignmentHorz = HorizontalAlignment.Center, BackgroundColor = OrthogenUI.ButtonBGColor, TextColor = OrthogenUI.ButtonTextColor, DisabledTextColor = OrthogenUI.DisabledButtonTextColor, Text = label, EnableBorder = false, BorderWidth = OrthogenUI.StandardButtonBorderWidth, BorderColor = OrthogenUI.ButtonTextColor }; button.Create(); button.Name = label; button.Enabled = true; return(button); }; /* * Scan UI */ HUDElementList scan_buttons_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Vertical }; HUDLabel trim_scan_button = MakeButtonF("Trim Scan", button_width); trim_scan_button.OnClicked += (sender, e) => { OG.Transition(OGWorkflow.TrimScanStartT); }; scan_buttons_list.AddListItem(trim_scan_button); HUDLabel align_scan_button = MakeButtonF("Align Scan", button_width); align_scan_button.OnClicked += (sender, e) => { OG.Transition(OGVRWorkflow.VRAlignScanStartT); }; scan_buttons_list.AddListItem(align_scan_button); HUDLabel accept_scan_button = MakeButtonF("Done Scan", button_width); accept_scan_button.OnClicked += (sender, e) => { OG.TransitionToState(RectifyState.Identifier); }; scan_buttons_list.AddListItem(accept_scan_button); scan_buttons_list.Create(); scan_buttons_list.Name = "scan_buttons_list"; cyl_layout.Add(scan_buttons_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(scan_buttons_list, BoxPosition.CenterTop), PinTargetPoint2D = LayoutUtil.BoxPointF(cylPanelContainer, BoxPosition.TopLeft) }); /* * Model UI UI */ HUDElementList model_buttons_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Vertical }; HUDLabel draw_offset_area_button = MakeButtonF("Offset Area", button_width); draw_offset_area_button.OnClicked += (sender, e) => { OGActions.CurrentLegDeformType = LegModel.LegDeformationTypes.Offset; OG.Transition(OGWorkflow.DrawAreaStartT); }; model_buttons_list.AddListItem(draw_offset_area_button); HUDLabel draw_smooth_area_button = MakeButtonF("Smooth Area", button_width); draw_smooth_area_button.OnClicked += (sender, e) => { OGActions.CurrentLegDeformType = LegModel.LegDeformationTypes.Smooth; OG.Transition(OGWorkflow.DrawAreaStartT); }; model_buttons_list.AddListItem(draw_smooth_area_button); HUDLabel add_plane_button = MakeButtonF("Add Plane", button_width); add_plane_button.OnClicked += (sender, e) => { OG.Transition(OGWorkflow.AddDeformRingStartT); }; model_buttons_list.AddListItem(add_plane_button); HUDLabel add_lengthen_button = MakeButtonF("Add Lengthen", button_width); add_lengthen_button.OnClicked += (sender, e) => { if (OGActions.CanAddLengthenOp()) { OGActions.AddLengthenOp(); } }; model_buttons_list.AddListItem(add_lengthen_button); HUDLabel sculpt_curve_model_button = MakeButtonF("Sculpt Curve", button_width); WorkflowRouter sculpt_router = WorkflowRouter.Build(new[] { OGWorkflow.RectifyState, OGWorkflow.SculptAreaStartT, OGWorkflow.SocketState, OGWorkflow.SculptTrimlineStartT }); sculpt_curve_model_button.OnClicked += (sender, e) => { sculpt_router.Apply(OG.Model.Workflow); }; model_buttons_list.AddListItem(sculpt_curve_model_button); HUDLabel accept_rectify_button = MakeButtonF("Begin Socket", button_width); accept_rectify_button.OnClicked += (sender, e) => { OG.TransitionToState(SocketDesignState.Identifier); OG.Leg.SetOpWidgetVisibility(false); }; model_buttons_list.AddListItem(accept_rectify_button); model_buttons_list.Create(); model_buttons_list.Name = "model_buttons_list"; cyl_layout.Add(model_buttons_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(model_buttons_list, BoxPosition.CenterTop), PinTargetPoint2D = LayoutUtil.BoxPointF(cylPanelContainer, BoxPosition.TopLeft) }); /* * Model UI UI */ HUDElementList socket_buttons_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Vertical }; HUDLabel draw_trim_line_button = MakeButtonF("Draw Trimline", button_width); draw_trim_line_button.OnClicked += (sender, e) => { OG.Transition(OGWorkflow.DrawTrimlineStartT); }; socket_buttons_list.AddListItem(draw_trim_line_button); HUDLabel plane_trim_line_button = MakeButtonF("Plane Trimline", button_width); plane_trim_line_button.OnClicked += (sender, e) => { OG.Transition(OGWorkflow.PlaneTrimlineStartT); }; socket_buttons_list.AddListItem(plane_trim_line_button); HUDLabel sculpt_trimline_button = MakeButtonF("Sculpt Trimline", button_width); sculpt_trimline_button.OnClicked += (sender, e) => { OG.Transition(OGWorkflow.SculptTrimlineStartT); }; socket_buttons_list.AddListItem(sculpt_trimline_button); HUDLabel add_socket_button = MakeButtonF("Add Socket", button_width); add_socket_button.OnClicked += (sender, e) => { if (OGActions.CanAddSocket()) { OGActions.AddSocket(); } }; socket_buttons_list.AddListItem(add_socket_button); HUDLabel export_socket_button = MakeButtonF("Export", button_width); export_socket_button.OnClicked += (sender, e) => { if (OGActions.CanExportSocket()) { OGActions.ExportSocket(); } }; socket_buttons_list.AddListItem(export_socket_button); // align button list top top-left of ui socket_buttons_list.Create(); socket_buttons_list.Name = "socket_buttons"; cyl_layout.Add(socket_buttons_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(socket_buttons_list, BoxPosition.CenterTop), PinTargetPoint2D = LayoutUtil.BoxPointF(cylPanelContainer, BoxPosition.TopLeft) }); HUDElementList ok_cancel_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Horizontal }; HUDLabel accept_button = MakeButtonF("Accept", button_width * 0.75f); accept_button.OnClicked += (sender, e) => { OGActions.AcceptCurrentTool(); }; HUDLabel cancel_button = MakeButtonF("Cancel", button_width * 0.75f); cancel_button.OnClicked += (sender, e) => { OGActions.CancelCurrentTool(); }; ok_cancel_list.AddListItem(accept_button); ok_cancel_list.AddListItem(cancel_button); // align button list top top-left of ui ok_cancel_list.Create(); ok_cancel_list.Name = "ok_cancel_list"; layout.Add(ok_cancel_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(ok_cancel_list, BoxPosition.CenterBottom), PinTargetPoint2D = LayoutUtil.BoxPointF(leftPanelContainer, BoxPosition.BottomLeft) }); HUDElementList size_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Horizontal }; HUDLabel size_1to1 = MakeButtonF("Real Size", button_width * 0.75f); size_1to1.OnClicked += (sender, e) => { OGActions.SetSizeMode(OGActions.SizeModes.RealSize); OGActions.RecenterVRView(false); }; HUDLabel size_medium = MakeButtonF("Zoom Size", button_width * 0.75f); size_medium.OnClicked += (sender, e) => { OGActions.SetSizeMode(OGActions.SizeModes.DemoSize); OGActions.RecenterVRView(false); }; size_list.AddListItem(size_1to1); size_list.AddListItem(size_medium); size_list.Create(); size_list.Name = "size_list"; layout.Add(size_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(size_list, BoxPosition.CenterBottom), PinTargetPoint2D = LayoutUtil.BoxPointF(leftPanelContainer, BoxPosition.BottomLeft), FrameAxesShift = new Vector3f(0, -row_y_shift, 0) }); HUDElementList view_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Horizontal }; HUDLabel recenter_button = MakeButtonF("Recenter", 2 * button_width * 0.75f); recenter_button.OnClicked += (sender, e) => { OGActions.RecenterVRView(true); }; view_list.AddListItem(recenter_button); view_list.Create(); view_list.Name = "view_list"; layout.Add(view_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(view_list, BoxPosition.CenterBottom), PinTargetPoint2D = LayoutUtil.BoxPointF(leftPanelContainer, BoxPosition.BottomLeft), FrameAxesShift = new Vector3f(0, -2 * row_y_shift, 0) }); HUDElementList capture_list = new HUDElementList() { Width = button_width, Height = button_height, Spacing = button_spacing, SizeMode = HUDElementList.SizeModes.AutoSizeToFit, Direction = HUDElementList.ListDirection.Horizontal }; HUDLabel capture_button = MakeButtonF("Capture", button_width * 0.75f); capture_button.OnClicked += (sender, e) => { if (FBCapture.CaptureOption.Active != null) { if (capture_button.Text == "Capture") { DebugUtil.Log("Starting 2D Capture..."); FBCapture.CaptureOption.Active.doSurroundCaptureOption = false; cockpit.Context.RegisterNextFrameAction(() => { //FBCapture.CaptureOption.Active.videoWidth = 4096; //FBCapture.CaptureOption.Active.videoHeight = 2048; FBCapture.CaptureOption.Active.StartCaptureVideo(); capture_button.Text = "Stop"; }); } else { FBCapture.CaptureOption.Active.StopCaptureVideo(); capture_button.Text = "Capture"; } } }; HUDLabel vrcapture_button = MakeButtonF("VRCapture", button_width * 0.75f); vrcapture_button.OnClicked += (sender, e) => { if (FBCapture.CaptureOption.Active != null) { if (vrcapture_button.Text == "VRCapture") { // [RMS] when we set this flag, we need to give CaptureOption.Update() a chance to see // it, which means we need to wait up to 2 frames FBCapture.CaptureOption.Active.doSurroundCaptureOption = true; cockpit.Context.RegisterNextFrameAction(() => { cockpit.Context.RegisterNextFrameAction(() => { GameObject encoderObj = GameObject.Find("EncoderObject"); encoderObj.transform.position = Camera.main.transform.position; encoderObj.transform.rotation = Quaternionf.Identity; GameObject head = UnityUtil.FindGameObjectByName("VRHead"); head.SetVisible(false); FBCapture.CaptureOption.Active.StartCaptureVideo(); vrcapture_button.Text = "Stop"; }); }); } else { FBCapture.CaptureOption.Active.StopCaptureVideo(); vrcapture_button.Text = "VRCapture"; } } }; capture_list.AddListItem(capture_button); capture_list.AddListItem(vrcapture_button); // align button list top top-left of ui capture_list.Create(); capture_list.Name = "capture_list"; layout.Add(capture_list, new LayoutOptions() { Flags = LayoutFlags.None, PinSourcePoint2D = LayoutUtil.LocalBoxPointF(capture_list, BoxPosition.CenterBottom), PinTargetPoint2D = LayoutUtil.BoxPointF(leftPanelContainer, BoxPosition.BottomLeft), FrameAxesShift = new Vector3f(0, -3 * row_y_shift, 0) }); leftPanelLayout.RecomputeLayout(); leftPanelLayout.RecomputeLayout(); leftPanelLayout.RecomputeLayout(); leftPanelLayout.RecomputeLayout(); leftPanelLayout.RecomputeLayout(); cylPanelLayout.RecomputeLayout(); // Configure interaction behaviors // - below we add behaviors for mouse, gamepad, and spatial devices (oculus touch, etc) // - keep in mind that Tool objects will register their own behaviors when active // setup key handlers (need to move to behavior...) cockpit.AddKeyHandler(new OrthoVRKeyHandler(cockpit.Context)); // these behaviors let us interact with UIElements (ie left-click/trigger, or either triggers for Touch) if (cockpit.Context.Use2DCockpit) { cockpit.InputBehaviors.Add(new Mouse2DCockpitUIBehavior(cockpit.Context) { Priority = 0 }); } cockpit.InputBehaviors.Add(new VRSpatialDeviceUIBehavior(cockpit.Context) { Priority = 0 }); cockpit.InputBehaviors.Add(new VRMouseUIBehavior(cockpit.Context) { Priority = 1 }); cockpit.InputBehaviors.Add(new SpatialDeviceGrabViewBehavior(cockpit) { Priority = 2 }); //cockpit.InputBehaviors.Add(new TwoHandViewManipBehavior(cockpit) { Priority = 1 }); //cockpit.InputBehaviors.Add(new SpatialDeviceViewManipBehavior(cockpit) { Priority = 2 }); // selection / multi-selection behaviors cockpit.InputBehaviors.Add(new MouseMultiSelectBehavior(cockpit.Context) { Priority = 10 }); cockpit.InputBehaviors.Add(new SpatialDeviceMultiSelectBehavior(cockpit.Context) { Priority = 10 }); cockpit.InputBehaviors.Add(new MouseDeselectBehavior(cockpit.Context) { Priority = 999 }); cockpit.InputBehaviors.Add(new SpatialDeviceDeselectBehavior(cockpit.Context) { Priority = 999 }); // update buttons enable/disable on state transitions, selection changes string main_state = ""; Action updateStateChangeButtons = () => { if (OG.IsInState(OGWorkflow.ScanState)) { main_state = OGWorkflow.ScanState; } else if (OG.IsInState(OGWorkflow.RectifyState)) { main_state = OGWorkflow.RectifyState; } else if (OG.IsInState(OGWorkflow.SocketState)) { main_state = OGWorkflow.SocketState; } scan_buttons_list.IsVisible = (main_state == OGWorkflow.ScanState); model_buttons_list.IsVisible = (main_state == OGWorkflow.RectifyState); socket_buttons_list.IsVisible = (main_state == OGWorkflow.SocketState); trim_scan_button.Enabled = OG.CanTransition(OGWorkflow.TrimScanStartT); align_scan_button.Enabled = OG.CanTransition(OGVRWorkflow.VRAlignScanStartT); accept_scan_button.Enabled = OG.IsInState(ScanState.Identifier) && OG.CanTransitionToState(RectifyState.Identifier); draw_offset_area_button.Enabled = OG.CanTransition(OGWorkflow.DrawAreaStartT); draw_smooth_area_button.Enabled = OG.CanTransition(OGWorkflow.DrawAreaStartT); add_plane_button.Enabled = OG.CanTransition(OGWorkflow.AddDeformRingStartT); add_lengthen_button.Enabled = OGActions.CanAddLengthenOp(); accept_rectify_button.Enabled = OG.IsInState(RectifyState.Identifier) && OG.CanTransitionToState(SocketDesignState.Identifier); draw_trim_line_button.Enabled = OG.CanTransition(OGWorkflow.DrawTrimlineStartT); plane_trim_line_button.Enabled = OG.CanTransition(OGWorkflow.PlaneTrimlineStartT); add_socket_button.Enabled = OGActions.CanAddSocket(); export_socket_button.Enabled = OGActions.CanExportSocket(); sculpt_curve_model_button.Enabled = sculpt_router.CanApply(OG.Model.Workflow); sculpt_trimline_button.Enabled = OG.CanTransition(OGWorkflow.SculptTrimlineStartT); }; OG.OnWorfklowInitialized += (o, e) => { updateStateChangeButtons(); }; OG.OnStateTransition += (from, to) => { updateStateChangeButtons(); }; OG.OnDataModelModified += (from, to) => { updateStateChangeButtons(); }; cockpit.Scene.SelectionChangedEvent += (o, e) => { if (OG.WorkflowInitialized) { updateStateChangeButtons(); } }; cockpit.Scene.ChangedEvent += (scene, so, type) => { if (OG.WorkflowInitialized) { updateStateChangeButtons(); } }; // accept/cancel buttons need to be checked every frame because the CanApply state // could change at any time, and there is no event about it cockpit.Context.RegisterEveryFrameAction("update_buttons", () => { if (cockpit.Context.ToolManager.ActiveRightTool != null) { cancel_button.Enabled = true; accept_button.Enabled = cockpit.Context.ToolManager.ActiveRightTool.CanApply; } else { cancel_button.Enabled = accept_button.Enabled = false; } // [RMS] currently this state changes outside workflow state changes... add_socket_button.Enabled = OGActions.CanAddSocket(); }); }
public override Delegate CreateDelegate(DeleFunction delefunc) { DeleFunction _func = delefunc; Delegate _dele = delefunc.cacheFunction(this._type, null); if (_dele != null) { return(_dele); } Action <T, T1> dele = (T param0, T1 param1) => { var func = _func.calltype.functions[_func.function]; if (func.expr_runtime != null) { CQ_Content content = CQ_ObjPool.PopContent(); try { content.CallThis = _func.callthis; content.CallType = _func.calltype; #if CQUARK_DEBUG content.function = _func.function; #endif CQ_Value p0 = new CQ_Value(); p0.SetObject(func._paramtypes[0].typeBridge, param0); content.DefineAndSet(func._paramnames[0], func._paramtypes[0].typeBridge, p0); CQ_Value p1 = new CQ_Value(); p1.SetObject(func._paramtypes[0].typeBridge, param1); content.DefineAndSet(func._paramnames[1], func._paramtypes[1].typeBridge, p1); func.expr_runtime.ComputeValue(content); content.DepthRemove(); } catch (Exception err) { string errinfo = "Dump Call in:"; if (_func.calltype != null) { errinfo += _func.calltype.Name + "::"; } if (_func.function != null) { errinfo += _func.function; } errinfo += "\n"; DebugUtil.Log(errinfo + content.Dump()); throw err; } CQ_ObjPool.PushContent(content); } }; Delegate d = dele as Delegate; if ((Type)this.typeBridge != typeof(Action)) { _dele = Delegate.CreateDelegate(this.typeBridge, d.Target, d.Method); } else { _dele = dele; } return(delefunc.cacheFunction(this._type, _dele)); }
public void Init() { DebugUtil.Info("开始初始化"); _sdkApi.Init(); }
private void DetermineFinalLocation(BaseLocation loc, List <Gas> gasses) { for (int i = 0; i < gasses.Count; i++) { foreach (MineralField field in loc.MineralFields) { if (SC2Util.DistanceSq(field.Pos, gasses[i].Pos) <= 8 * 8) { loc.Gasses.Add(gasses[i]); gasses[i] = gasses[gasses.Count - 1]; gasses.RemoveAt(gasses.Count - 1); i--; break; } } } if (loc.Gasses.Count == 1) { for (int i = 0; i < gasses.Count; i++) { if (SC2Util.DistanceSq(loc.Gasses[0].Pos, gasses[i].Pos) <= 8 * 8) { loc.Gasses.Add(gasses[i]); gasses[i] = gasses[gasses.Count - 1]; gasses.RemoveAt(gasses.Count - 1); i--; break; } } } float x = 0; float y = 0; foreach (MineralField field in loc.MineralFields) { x += (int)field.Pos.X; y += (int)field.Pos.Y; } x /= loc.MineralFields.Count; y /= loc.MineralFields.Count; // Round to nearest half position. Nexii are 5x5 and therefore always centered in the middle of a tile. x = (int)(x) + 0.5f; y = (int)(y) + 0.5f; // Temporary position, we still need a proper position. loc.Pos = SC2Util.Point(x, y); MineralField closest = null; float distance = 10000; foreach (MineralField field in loc.MineralFields) { if (SC2Util.DistanceGrid(field.Pos, loc.Pos) < distance) { distance = SC2Util.DistanceGrid(field.Pos, loc.Pos); closest = field; } } // Move the estimated base position slightly away from the closest mineral. // This ensures that the base location will not end up on the far side of the minerals. if (closest.Pos.X < loc.Pos.X) { loc.Pos.X += 2; } else if (closest.Pos.X > loc.Pos.X) { loc.Pos.X -= 2; } if (closest.Pos.Y < loc.Pos.Y) { loc.Pos.Y += 2; } else if (closest.Pos.Y > loc.Pos.Y) { loc.Pos.Y -= 2; } bool test = SC2Util.DistanceSq(loc.Pos, new Point2D() { X = 127.5f, Y = 77.5f }) <= 10 * 10; float closestDist = 1000000; Point2D approxPos = loc.Pos; for (int i = 0; i < 20; i++) { for (int j = 0; j == 0 || j < i; j++) { float maxDist; Point2D newPos; newPos = SC2Util.Point(approxPos.X + i - j, approxPos.Y + j); maxDist = checkPosition(newPos, loc); if (maxDist < closestDist) { loc.Pos = newPos; closestDist = maxDist; } newPos = SC2Util.Point(approxPos.X + i - j, approxPos.Y - j); maxDist = checkPosition(newPos, loc); if (maxDist < closestDist) { loc.Pos = newPos; closestDist = maxDist; } newPos = SC2Util.Point(approxPos.X - i + j, approxPos.Y + j); maxDist = checkPosition(newPos, loc); if (maxDist < closestDist) { loc.Pos = newPos; closestDist = maxDist; } newPos = SC2Util.Point(approxPos.X - i + j, approxPos.Y - j); maxDist = checkPosition(newPos, loc); if (maxDist < closestDist) { loc.Pos = newPos; closestDist = maxDist; } } } if (loc.Gasses.Count != 2) { FileUtil.Debug("Wrong number of gasses, found: " + loc.Gasses.Count); } if (closestDist >= 999999) { DebugUtil.WriteLine("Unable to find proper base placement: " + loc.Pos); } }
public Language(ChunkID id, long size, long position) : base(id, size, position) { DebugUtil.EnsureCondition( id == ChunkID.BCHUNK_LANGUAGE, () => $"Expected BCHUNK_LANGUAGE, got {id.ToString()}"); }
public void Analyze(Tyr tyr) { // Determine the start location. foreach (Unit unit in tyr.Observation.Observation.RawData.Units) { if (unit.Owner == tyr.PlayerId && UnitTypes.ResourceCenters.Contains(unit.UnitType)) { StartLocation = unit.Pos; } } List <MineralField> mineralFields = new List <MineralField>(); foreach (Unit mineralField in tyr.Observation.Observation.RawData.Units) { if (UnitTypes.MineralFields.Contains(mineralField.UnitType)) { mineralFields.Add(new MineralField() { Pos = mineralField.Pos, Tag = mineralField.Tag }); } } // The Units provided in our observation are not guaranteed to be in the same order every game. // To ensure the base finding algorithm finds the same base location every time we sort the mineral fields by position. mineralFields.Sort((a, b) => (int)(2 * (a.Pos.X + a.Pos.Y * 10000 - b.Pos.X - b.Pos.Y * 10000))); Dictionary <ulong, int> mineralSetIds = new Dictionary <ulong, int>(); List <List <MineralField> > mineralSets = new List <List <MineralField> >(); int currentSet = 0; foreach (MineralField mineralField in mineralFields) { if (mineralSetIds.ContainsKey(mineralField.Tag)) { continue; } BaseLocation baseLocation = new BaseLocation(); BaseLocations.Add(baseLocation); mineralSetIds.Add(mineralField.Tag, currentSet); baseLocation.MineralFields.Add(mineralField); for (int i = 0; i < baseLocation.MineralFields.Count; i++) { MineralField mineralFieldA = baseLocation.MineralFields[i]; foreach (MineralField closeMineralField in mineralFields) { if (mineralSetIds.ContainsKey(closeMineralField.Tag)) { continue; } if (SC2Util.DistanceSq(mineralFieldA.Pos, closeMineralField.Pos) <= 4 * 4) { mineralSetIds.Add(closeMineralField.Tag, currentSet); baseLocation.MineralFields.Add(closeMineralField); } } } currentSet++; } List <Gas> gasses = new List <Gas>(); foreach (Unit unit in tyr.Observation.Observation.RawData.Units) { if (UnitTypes.GasGeysers.Contains(unit.UnitType)) { gasses.Add(new Gas() { Pos = unit.Pos, Tag = unit.Tag }); } } // The Units provided in our observation are not guaranteed to be in the same order every game. // To ensure the base finding algorithm finds the same base location every time we sort the gasses by position. gasses.Sort((a, b) => (int)(2 * (a.Pos.X + a.Pos.Y * 10000 - b.Pos.X - b.Pos.Y * 10000))); foreach (BaseLocation loc in BaseLocations) { DetermineFinalLocation(loc, gasses); } if (tyr.GameInfo.MapName.Contains("Blueshift")) { foreach (BaseLocation loc in BaseLocations) { if (SC2Util.DistanceSq(loc.Pos, SC2Util.Point(141.5f, 112.5f)) <= 5 * 5 && (loc.Pos.X != 141.5 || loc.Pos.Y != 112.5)) { DebugUtil.WriteLine("Incorrect base location, fixing: " + loc.Pos); loc.Pos = SC2Util.Point(141.5f, 112.5f); } else if (SC2Util.DistanceSq(loc.Pos, SC2Util.Point(34.5f, 63.5f)) <= 5 * 5 && (loc.Pos.X != 34.5 || loc.Pos.Y != 63.5)) { DebugUtil.WriteLine("Incorrect base location, fixing: " + loc.Pos); loc.Pos = SC2Util.Point(34.5f, 63.5f); } } } Stopwatch stopWatch = Stopwatch.StartNew(); int width = Tyr.Bot.GameInfo.StartRaw.MapSize.X; int height = Tyr.Bot.GameInfo.StartRaw.MapSize.Y; Placement = new ImageBoolGrid(tyr.GameInfo.StartRaw.PlacementGrid); StartArea = Placement.GetConnected(SC2Util.To2D(StartLocation)); ArrayBoolGrid startLocations = new ArrayBoolGrid(Placement.Width(), Placement.Height()); foreach (Point2D startLoc in Tyr.Bot.GameInfo.StartRaw.StartLocations) { for (int x = -2; x <= 2; x++) { for (int y = -2; y <= 2; y++) { startLocations[(int)startLoc.X + x, (int)startLoc.Y + y] = true; } } } for (int x = -2; x <= 2; x++) { for (int y = -2; y <= 2; y++) { startLocations[(int)StartLocation.X + x, (int)StartLocation.Y + y] = true; } } BoolGrid unPathable; if (Tyr.Bot.OldMapData) { unPathable = new ImageBoolGrid(Tyr.Bot.GameInfo.StartRaw.PathingGrid).GetAnd(startLocations.Invert()); Pathable = unPathable.Invert(); } else { Pathable = new ImageBoolGrid(Tyr.Bot.GameInfo.StartRaw.PathingGrid).GetOr(startLocations); unPathable = Pathable.Invert(); } BoolGrid chokes = Placement.Invert().GetAnd(Pathable); BoolGrid mainExits = chokes.GetAdjacent(StartArea); enemyDistances = EnemyDistances; int dist = 1000; Point2D mainRamp = null; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (mainExits[x, y]) { int newDist = enemyDistances[x, y]; if (newDist < dist) { dist = newDist; mainRamp = SC2Util.Point(x, y); } } } } Ramp = chokes.GetConnected(mainRamp); BoolGrid pathingWithoutRamp = Pathable.GetAnd(Ramp.Invert()); MainAndPocketArea = pathingWithoutRamp.GetConnected(SC2Util.To2D(StartLocation)); if (Tyr.Bot.MyRace == Race.Protoss) { DetermineWall(Ramp, unPathable); } WallDistances = Distances(unPathable); stopWatch.Stop(); DebugUtil.WriteLine("Total time to find wall: " + stopWatch.ElapsedMilliseconds); }
static IList <IType> _FileCompiler(string filename, IList <Token> tokens, bool embDeubgToken, bool onlyGotType) { List <IType> typelist = new List <IType>(); List <string> usingList = new List <string>(); //识别using //扫描token有没有要合并的类型 //using的实现在token级别处理即可 bool bJumpClass = false; for (int i = 0; i < tokens.Count; i++) { if (tokens[i].type == TokenType.PUNCTUATION && tokens[i].text == ";") { continue; } if (tokens[i].type == TokenType.COMMENT) { continue; } if (tokens[i].type == TokenType.KEYWORD && tokens[i].text == "using") { int dep; int pos = i; int iend = FindCodeAny(tokens, ref pos, out dep); List <string> list = Compiler_Using(tokens, pos, iend); string useText = ""; for (int j = 0; j < list.Count; j++) { useText += list[j]; if (j != list.Count - 1) { useText += "."; } } usingList.Add(useText); i = iend; continue; } if (tokens[i].type == TokenType.PUNCTUATION && tokens[i].text == "[") { if (tokens[i + 1].text == "NotScipt" || (tokens[i + 1].text == "CQuark" && tokens[i + 3].text == "NotScipt")) { bJumpClass = true; i = i + 2; continue; } } if (tokens[i].type == TokenType.KEYWORD && (tokens[i].text == "class" || tokens[i].text == "interface")) { string name = tokens[i + 1].text; //在这里检查继承 List <string> typebase = null; int ibegin = i + 2; if (onlyGotType) { while (tokens[ibegin].text != "{") { ibegin++; } } else { if (tokens[ibegin].text == ":") { typebase = new List <string>(); ibegin++; } while (tokens[ibegin].text != "{") { if (tokens[ibegin].type == TokenType.TYPE) { typebase.Add(tokens[ibegin].text); } ibegin++; } } int iend = FindBlock(tokens, ibegin); if (iend == -1) { DebugUtil.LogError("查找文件尾失败。"); return(null); } if (bJumpClass) { DebugUtil.Log("(NotScript)findclass:" + name + "(" + ibegin + "," + iend + ")"); } else if (onlyGotType) { DebugUtil.Log("(scriptPreParser)findclass:" + name + "(" + ibegin + "," + iend + ")"); } else { DebugUtil.Log("(scriptParser)findclass:" + name + "(" + ibegin + "," + iend + ")"); } if (bJumpClass) {//忽略这个Class //ICQ_Type type = Compiler_Class(env, name, (tokens[i].text == "interface"), filename, tokens, ibegin, iend, embDeubgToken, true); //bJumpClass = false; } else { IType type = Compiler_Class(name, (tokens[i].text == "interface"), typebase, filename, tokens, ibegin, iend, embDeubgToken, onlyGotType, usingList); if (type != null) { typelist.Add(type); } } i = iend; continue; } } return(typelist); }
public void SetSymbolOverride(int symbol_idx, KAnim.Build.SymbolFrameInstance symbol_frame_instance) { DebugUtil.Assert(usingNewSymbolOverrideSystem, "KBatchedAnimController requires usingNewSymbolOverrideSystem to bet to true to enable symbol overrides."); base.symbolOverrideInfoGpuData.SetSymbolOverrideInfo(symbol_idx, symbol_frame_instance); }
public override Delegate CreateDelegate(DeleFunction delefunc) { DeleFunction _func = delefunc; Delegate _dele = delefunc.cacheFunction(this._type, null); if (_dele != null) { return(_dele); } NonVoidDelegate dele = delegate(T param0, T1 param1, T2 param2) { var func = _func.calltype.functions[_func.function]; if (func.expr_runtime != null) { CQ_Content content = CQ_ObjPool.PopContent(); try { content.CallThis = _func.callthis; content.CallType = _func.calltype; #if CQUARK_DEBUG content.function = _func.function; #endif CQ_Value p0 = new CQ_Value(); p0.SetObject(func._paramtypes[0].typeBridge, param0); content.DefineAndSet(func._paramnames[0], func._paramtypes[0].typeBridge, p0); CQ_Value p1 = new CQ_Value(); p1.SetObject(func._paramtypes[1].typeBridge, param1); content.DefineAndSet(func._paramnames[1], func._paramtypes[1].typeBridge, p1); CQ_Value p2 = new CQ_Value(); p2.SetObject(func._paramtypes[2].typeBridge, param2); content.DefineAndSet(func._paramnames[2], func._paramtypes[2].typeBridge, p2); CQ_Value retValue = func.expr_runtime.ComputeValue(content); content.DepthRemove(); CQ_ObjPool.PushContent(content); return((ReturnType)retValue.GetObject()); } catch (Exception err) { string errinfo = "Dump Call in:"; if (_func.calltype != null) { errinfo += _func.calltype.Name + "::"; } if (_func.function != null) { errinfo += _func.function; } errinfo += "\n"; DebugUtil.Log(errinfo + content.Dump()); throw err; } } return(default(ReturnType)); }; _dele = Delegate.CreateDelegate(this.typeBridge, dele.Target, dele.Method); return(delefunc.cacheFunction(this._type, _dele)); }
// Use this for initialization void Start() { //find the bullet manager in the scene bulletManager = GameObject.Find("BulletManager"); //initialise health to 10 health = 10; //initialise timer to 0; timer = 0.0f; //by default the player can fire canFire = true; //initialise the player player = gameObject.GetComponent<Rigidbody> (); // initialise the sphere world gravity = GameObject.FindGameObjectWithTag ("Sphere").GetComponent<GravChange> (); //disable use of unity's gravity for the player player.useGravity = false; //freexe rotation for this game object player.constraints = RigidbodyConstraints.FreezeRotation; //stop the mouse pointer from moving Cursor.lockState = CursorLockMode.Locked; //make the mouse cursor invisible Cursor.visible = false; //initialise the camera to the main scene camera cam = Camera.main; //initialise debugger by finding it in the scene m_debugger = GameObject.Find("Canvas").GetComponentInChildren<DebugUtil>(); //initialise fuel gague m_fuelGague = 5.0f; //player is not flying by default m_flying = false; //initialise the respawn manager rManager = GameObject.Find("RespawnManager").GetComponent<RespawnManagerScript>(); }