private void OnLoad(object sender, EventArgs e) { baseGrid = new ParticleGrid(20, 5, GuiContext); ViewerControl.Camera.SetViewportSize(ViewerControl.GLControl.Width, ViewerControl.GLControl.Height); ViewerControl.Camera.SetLocation(new Vector3(256)); ViewerControl.Camera.LookAt(new Vector3(0)); LoadScene(); if (Scene.AllNodes.Any()) { var bbox = Scene.AllNodes.First().BoundingBox; var location = new Vector3(bbox.Max.Z, 0, bbox.Max.Z) * 1.5f; ViewerControl.Camera.SetLocation(location); ViewerControl.Camera.LookAt(bbox.Center); } staticOctreeRenderer = new OctreeDebugRenderer <SceneNode>(Scene.StaticOctree, Scene.GuiContext, false); dynamicOctreeRenderer = new OctreeDebugRenderer <SceneNode>(Scene.DynamicOctree, Scene.GuiContext, true); if (renderModeComboBox != null) { var supportedRenderModes = Scene.AllNodes .SelectMany(r => r.GetSupportedRenderModes()) .Distinct(); SetAvailableRenderModes(supportedRenderModes); } ViewerControl.GLLoad -= OnLoad; ViewerControl.GLPaint += OnPaint; GuiContext.ClearCache(); }
/// <summary> /// Lays out all of the contained controls horizontally. /// </summary> public override void Render(GuiContext c) { Width = 0; Height = 0; c.PushXY(); foreach (var control in Controls.ToArray()) { // adjust position for padding c.MoveTo(c.X + control.Settings.LeftPadding, c.Y); c.PushXY(); c.MoveTo(c.X, c.Y + control.Settings.TopPadding); // save layout's size if (control.TotalHeight > Height) { Height = control.TotalHeight; } Width += control.TotalWidth; // render and save the extents for mouse events control.Render(c); control.LastRenderPosition.X = c.X; control.LastRenderPosition.Y = c.Y; control.LastRenderPosition.Width = control.Width; control.LastRenderPosition.Height = control.Height; // move to the next control's position c.PopXY(); c.MoveTo(c.X + control.Width + control.Settings.RightPadding, c.Y); } c.PopXY(); }
private bool ResultSubscribePLCTag(IIncomingMessage Message) { bool RetValue = true; // get msg application data var MsgData = GeneralHelper.DeserializeObject(Message.MessageData) as PLCTagData; Logger.InfoFormat("Ricevuto Messaggio {1}/{2}:{3} da {0}", Message.SourceApplicationName, MsgData.Tag.PLCName, MsgData.Tag.Address, MsgData.Tag.Value); TagItem tag = new TagItem() { PLCName = MsgData.Tag.PLCName, Address = MsgData.Tag.Address }; if (tag != null) { Logger.InfoFormat("Aggiunto {0}/{1}", tag.PLCName, tag.Address); if (GuiContext != null) { GuiContext.Send((o) => { model.ListTagItems.Add(tag); }, null); } else { Logger.InfoFormat("GuiContext NULL"); Debug.Assert(false); } } return(RetValue); }
public SwitchList(GuiContext context) : base(context) { Items = new ObservableCollection <object>(); Items.CollectionChanged += (sender, args) => ValidateIndex(); _selectedIndex = -1; }
internal void PostMediaEndedEvent() { LogEventStart(nameof(MediaEnded)); GuiContext.EnqueueInvoke(() => { MediaEnded?.Invoke(this, EventArgs.Empty); LogEventDone(nameof(MediaEnded)); }); }
internal void PostSeekingStartedEvent() { LogEventStart(nameof(SeekingStarted)); GuiContext.EnqueueInvoke(() => { SeekingStarted?.Invoke(this, EventArgs.Empty); LogEventDone(nameof(SeekingStarted)); }); }
internal void PostMediaStateChangedEvent(MediaPlaybackState oldValue, MediaPlaybackState newValue) { LogEventStart(nameof(MediaStateChanged)); GuiContext.EnqueueInvoke(() => { MediaStateChanged?.Invoke(this, new MediaStateChangedEventArgs(oldValue, newValue)); LogEventDone(nameof(MediaStateChanged)); }); }
internal void PostPositionChangedEvent(TimeSpan oldValue, TimeSpan newValue) { // Event logging disabled because this happens too often. GuiContext.EnqueueInvoke(() => { PositionChanged?.Invoke( this, new PositionChangedEventArgs(MediaCore.State, oldValue, newValue)); }); }
internal void PostMediaChangedEvent(MediaInfo mediaInfo) { LogEventStart(nameof(MediaChanged)); GuiContext.EnqueueInvoke(() => { MediaChanged?.Invoke(this, new MediaOpenedEventArgs(mediaInfo)); LogEventDone(nameof(MediaChanged)); }); }
internal void PostMediaFailedEvent(Exception ex) { LogEventStart(nameof(MediaFailed)); GuiContext.EnqueueInvoke(() => { MediaFailed?.Invoke(this, new MediaFailedEventArgs(ex)); LogEventDone(nameof(MediaFailed)); }); }
public override void Load() { var pixel = new Texture2D(context.GraphicsDevice, 1, 1); pixel.SetData(new[] { Color.White }); _guiContext = new GuiContext(pixel); _guifont = content.Load <SpriteFont>(FontName); _guiCam = new Camera(new Vector2()); _guiCam = new Camera(new Vector2(VirtualResolution.Width / 2, VirtualResolution.Height / 2)); base.Load(); }
public override void Render(GuiContext c) { var box = new Rectangle(c.X, c.Y, Width, Height); var g = c.GetGraphics(); // important locations (TODO: fix for horizontal) var fullRect = new RectangleF(c.X, c.Y, Width, Height); var faderAreaRect = new RectangleF(c.X, c.Y, Width / 2, Height); var slotRect = new RectangleF(faderAreaRect.X + faderAreaRect.Width / 2 - 3, faderAreaRect.Y, 6, faderAreaRect.Height); var valueAreaRect = new RectangleF(c.X + Width / 2, c.Y, Width / 2, Height); // draw slot g.FillRectangle(new SolidBrush(Parent.Gray1), slotRect); g.DrawLine(new Pen(Parent.Gray5, 2), slotRect.X, slotRect.Y, slotRect.X + slotRect.Width, slotRect.Y); g.DrawLine(new Pen(Parent.Gray5, 2), slotRect.X, slotRect.Y, slotRect.X, slotRect.Y + slotRect.Height); // draw fader knob float knobHeight = faderAreaRect.Height / 10; RectangleF faderKnob = new RectangleF(); if (Type == FaderType.Vertical) { faderKnob = new RectangleF(faderAreaRect.X, faderAreaRect.Y + faderAreaRect.Height - (int)(Percent * (faderAreaRect.Height * 0.9)) - faderAreaRect.Height / 10, faderAreaRect.Width, faderAreaRect.Height / 10); } else if (Type == FaderType.Horizontal) { faderKnob = new RectangleF(faderAreaRect.X + (int)(Percent * (faderAreaRect.Width * 0.9)), faderAreaRect.Y, faderAreaRect.Width / 10, faderAreaRect.Height); } g.FillRectangle(new SolidBrush(Parent.BaseColor), faderKnob); // draw value var valuePen = new Pen(Parent.BaseColor, 5); if (Type == FaderType.Vertical) { float x0 = valueAreaRect.X + valueAreaRect.Width / 2; float y1 = valueAreaRect.Y + valueAreaRect.Height; float y0 = (float)(y1 - valueAreaRect.Height * Percent); g.DrawLine(valuePen, x0, y0, x0, y1); } // draw borders //var pen = new Pen(Color.White, 3); // g.DrawRectangle(pen, box); }
/// <summary> /// Copies the renderered image to the GuiContext. /// </summary> public override void Render(GuiContext c) { // should we assume its already rendered? //Rendererer.Render(); var r = new Rectangle(); r.X = c.X; r.Y = c.Y; r.Width = Width; r.Height = Height; var g = c.GetGraphics(); g.DrawImageUnscaledAndClipped(Rendererer.Image, r); }
public VerticalList(GuiContext context) : base(context) { }
/// <summary> /// Constructor accepts the context this is for. /// </summary> public ControlRegistration(GuiContext parent) { Parent = parent; }
/// <summary> /// Draws a white circle 3px thick with a line representing /// the current value, with 1/4 of the circle at the bottom /// not used, with a curve around it from the start point /// to the current point in yellow. /// </summary> public override void Render(GuiContext c) { var testbmp = new Bitmap(Width, Height); //var g = Graphics.FromImage(testbmp); var g = c.GetGraphics(); g.SmoothingMode = SmoothingMode.AntiAlias; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; // get different radiuses var fullRadius = Width / 2.0; var lineStartRadius = fullRadius * 0.25; var lineEndRadius = fullRadius * 0.55; // get theta of value var theta0 = Math.PI * (-0.25); var theta1 = Math.PI * 1.25; var theta = theta0 + ((theta1 - theta0) * (1 - Percent)); // get line sizes float valuePenWidth = (float)Width * 0.12F; float linePenWidth = (float)Width * 0.04F; // shadow positions float shadowOffset1 = Width * 0.035F; float shadowOffset2 = Width * 0.025F; // calculate important points var midpoint = new PointF(c.X + Width / 2, c.Y + Height / 2); var fullRect = new RectangleF(c.X, c.Y, Width, Height); var borderRect = new RectangleF(c.X + valuePenWidth / 2, c.Y + valuePenWidth / 2, Width - valuePenWidth, Height - valuePenWidth); var bandCenterRect = new RectangleF(c.X + valuePenWidth, c.Y + valuePenWidth, Width - valuePenWidth * 2, Height - valuePenWidth * 2); var knobRect = new RectangleF(c.X + valuePenWidth * 1.5F, c.Y + valuePenWidth * 1.5F, Width - valuePenWidth * 3F, Height - valuePenWidth * 3F); var knobBorderRect = new RectangleF(knobRect.X + 1, knobRect.Y + 1, knobRect.Width - 2, knobRect.Height - 2); var shawdowRect = new RectangleF(fullRect.X + 2, fullRect.Y + 5, fullRect.Width, fullRect.Height); // draw the outer band g.FillEllipse(new LinearGradientBrush(borderRect, BandColor1, BandColor2, LinearGradientMode.Vertical), borderRect); // draw the outline for the outer band g.DrawEllipse(new Pen(OuterBorderColor, 2), borderRect); //g.DrawEllipse(new Pen(InnerBorderColor1, 3), knobBorderRect); //g.DrawEllipse(new Pen(InnerBorderColor2, 5), knobBorderRect2); // draw the knob g.FillEllipse(new LinearGradientBrush(knobRect, KnobColor1, KnobColor2, LinearGradientMode.Vertical), knobRect); g.DrawArc(new Pen(InnerBorderColor1, 1), knobBorderRect, 210, 120); g.DrawArc(new Pen(InnerBorderColor2, 2), knobBorderRect, 30, 120); // draw the value arc float arcLength = (float)Percent * 270; g.DrawArc(new Pen(ValueColor, valuePenWidth), fullRect, 135, arcLength); g.DrawArc(new Pen(ValueBandColor, valuePenWidth), bandCenterRect, 135, arcLength); // draw the line pointing at the value var lineStartRel = new PointF((float)(Math.Cos(theta) * lineStartRadius), (float)(Math.Sin(theta) * lineStartRadius)); var lineEndRel = new PointF((float)(Math.Cos(theta) * lineEndRadius), (float)(Math.Sin(theta) * lineEndRadius)); g.DrawLine(new Pen(LineColor, linePenWidth), midpoint.X + lineStartRel.X, midpoint.Y - lineStartRel.Y, midpoint.X + lineEndRel.X, midpoint.Y - lineEndRel.Y); // label test var font = new Font("arial", 8); g.DrawString("Knob", font, new SolidBrush(Color.White), c.X + Width / 2, c.Y + Height, new StringFormat() { Alignment = StringAlignment.Center }); }
public Button(GuiContext context) : base(context) { }
public Label(GuiContext context) : base(context) { }
static void Main(string[] args) { { double[][] arr; arr = new double[3][]; arr[0] = new double[4] { 9, 8, 7, 6 }; arr[1] = new double[4] { 42, 13, 7, 2 }; arr[2] = new double[4] { 101, 102, 103, 104 }; MeshAttributeCLASSES meshComponent2 = MeshAttributeCLASSES.makeDouble4(arr); double[] readback = meshComponent2.getDouble4Accessor()[1]; int breakPointHere = 42; } // test solver for trivial cases { double one = 1.0; double J11 = 1.0, J22 = 1.0, J33 = 1.0, // principal moments of inertia of the body w1 = 0, w2 = 0, w3 = 0, // angular velocity of spacecraft in spacecraft frame // result values q1Dot, q2Dot, q3Dot, q4Dot, w1Dot, w2Dot, w3Dot, // coeefficients, taken from the paper gamma = 0.7, aCoefficient = 1.25, d = 7.5, k = 3.0, betaOne = 0.001; Quaternion spacecraftOrientationError; // set to identity /* * spacecraftOrientationError.i = 0; * spacecraftOrientationError.j = 0; * spacecraftOrientationError.k = 0; * spacecraftOrientationError.scalar = 1; */ spacecraftOrientationError = QuaternionUtilities.makeFromAxisAndAngle(new SpatialVectorDouble(new double[] { 1, 0, 0 }), 1.0); QuaternionFeedbackRegulatorForSpacecraft.calcControl( J11, J22, J33, spacecraftOrientationError.i, spacecraftOrientationError.j, spacecraftOrientationError.k, spacecraftOrientationError.scalar, w1, w2, w3, out q1Dot, out q2Dot, out q3Dot, out q4Dot, out w1Dot, out w2Dot, out w3Dot, aCoefficient, gamma, d, k, betaOne ); // changes must be zero Debug.Assert(q1Dot == 0); Debug.Assert(q2Dot == 0); Debug.Assert(q3Dot == 0); Debug.Assert(q4Dot == 0); Debug.Assert(w1Dot == 0); Debug.Assert(w2Dot == 0); Debug.Assert(w3Dot == 0); int breakPointHere = 42; } SimplexSolver simplexSolver = new SimplexSolver(); /* first example from video tutorial, https://www.youtube.com/watch?v=Axg9OhJ4cjg, bottom row is negative unlike in the video */ simplexSolver.matrix = Matrix.makeByRowsAndColumns(3, 5); simplexSolver.matrix[0, 0] = 4; simplexSolver.matrix[0, 1] = 8; simplexSolver.matrix[0, 2] = 1; simplexSolver.matrix[0, 3] = 0; simplexSolver.matrix[0, 4] = 24; simplexSolver.matrix[1, 0] = 2; simplexSolver.matrix[1, 1] = 1; simplexSolver.matrix[1, 2] = 0; simplexSolver.matrix[1, 3] = 1; simplexSolver.matrix[1, 4] = 10; simplexSolver.matrix[2, 0] = -3; simplexSolver.matrix[2, 1] = -4; simplexSolver.matrix[2, 2] = 0; simplexSolver.matrix[2, 3] = 0; simplexSolver.matrix[2, 4] = 0; simplexSolver.iterate(); // result must be ~16.67 Debug.Assert(simplexSolver.matrix[2, 4] > 16.6 && simplexSolver.matrix[2, 4] < 16.8); // TODO< move into unittest for Matrix > Matrix toInverseMatrix = new Matrix(2, 2); toInverseMatrix[0, 0] = 2.0f; toInverseMatrix[0, 1] = 1.0f; toInverseMatrix[1, 0] = 2.0f; toInverseMatrix[1, 1] = 2.0f; Matrix inversedMatrix = toInverseMatrix.inverse(); Debug.Assert(System.Math.Abs(inversedMatrix[0, 0] - 1.0f) < 0.001f); Debug.Assert(System.Math.Abs(inversedMatrix[0, 1] - -0.5f) < 0.001f); Debug.Assert(System.Math.Abs(inversedMatrix[1, 0] - -1.0f) < 0.001f); Debug.Assert(System.Math.Abs(inversedMatrix[1, 1] - 1.0f) < 0.001f); // test pid controller if (false) { Pid.Configuration pidConfiguration = new Pid.Configuration(); pidConfiguration.integral = 0; pidConfiguration.derivative = 0.1; pidConfiguration.proportial = 0.3; Pid pid = Pid.makeByTargetAndConfiguration(0, pidConfiguration); double value = 1.0; double control; control = pid.step(value, 0.5); value += control; for (int i = 0; i < 10; i++) { control = pid.step(value, 0.5); value += control; Console.WriteLine("value={0} control={1}", value, control); } int breakPointHere0 = 1; } EntityManager entityManager = new EntityManager(); SolidResponsibility solidResponsibility; EffectResponsibility effectResponsibility; ThrusterResponsibility thrusterResponsibility; AttitudeAndAccelerationControlResponsibility attitudeAndAccelerationControlResponsibility; thrusterResponsibility = new ThrusterResponsibility(); attitudeAndAccelerationControlResponsibility = new AttitudeAndAccelerationControlResponsibility(thrusterResponsibility); effectResponsibility = new EffectResponsibility(); solidResponsibility = new SolidResponsibility(); solidResponsibility.mapping = new PhysicsObjectIdToSolidClusterMapping(); EntityController entityController = new EntityController(); IKeyboardInputHandler keyboardInputHandler = new PlayerShipControlInputHandler(entityController); KeyboardInputRemapper keyboardInputRemapper = new KeyboardInputRemapper(keyboardInputHandler); SoftwareRenderer softwareRenderer = new SoftwareRenderer(); PrototypeForm prototypeForm = new PrototypeForm(); prototypeForm.softwareRenderer = softwareRenderer; IGuiRenderer guiRenderer = prototypeForm.softwareGuiRenderer; GuiContext guiContext = new GuiContext(guiRenderer); prototypeForm.guiContext = guiContext; KeyboardEventRouterOfGui keyboardEventRouterOfGui = new KeyboardEventRouterOfGui(guiContext.selectionTracker); KeyboardInputRouter keyboardInputRouter = new KeyboardInputRouter(keyboardInputRemapper, keyboardEventRouterOfGui); prototypeForm.keyboardInputRouter = keyboardInputRouter; prototypeForm.Show(); PhysicsEngine physicsEngine = new PhysicsEngine(); solidResponsibility.physicsEngine = physicsEngine; physicsEngine.collisionHandlers.Add(new DefaultCollisionHandler()); // add the default collision handler for absorbing all particles AttachedForce thruster = new AttachedForce( new SpatialVectorDouble(new double[] { 0, 1, 0 }), // localLocation new SpatialVectorDouble(new double[] { 1, 0, 0 }) // localDirection ); PhysicsComponent physicsComponent; { double mass = 1.0; Matrix inertiaTensor = InertiaHelper.calcInertiaTensorForCube(mass, 1.0, 1.0, 1.0); physicsComponent = physicsEngine.createPhysicsComponent(new SpatialVectorDouble(new double[] { 0, 0, 10 }), new SpatialVectorDouble(new double[] { 0, 0, 0 }), mass, inertiaTensor); } physicsComponent.attachedForces.Add(thruster); MeshComponent meshComponent = new MeshComponent(); meshComponent.mesh = new MeshWithExplicitFaces(); meshComponent.mesh.faces = new MeshWithExplicitFaces.Face[1]; meshComponent.mesh.faces[0] = new MeshWithExplicitFaces.Face(); meshComponent.mesh.faces[0].verticesIndices = new uint[] { 0, 1, 2 }; { // create a VerticesWithAttributes with just positions MutableMeshAttribute positionMeshAttribute = MutableMeshAttribute.makeDouble4ByLength(4); positionMeshAttribute.getDouble4Accessor()[0] = new double[] { -1, -1, 0, 1 }; positionMeshAttribute.getDouble4Accessor()[1] = new double[] { 1, -1, 0, 1 }; positionMeshAttribute.getDouble4Accessor()[2] = new double[] { 0, 1, 0, 1 }; positionMeshAttribute.getDouble4Accessor()[3] = new double[] { 0, 0, 1, 1 }; VerticesWithAttributes verticesWithAttributes = new VerticesWithAttributes(new AbstractMeshAttribute[] { positionMeshAttribute }, 0); meshComponent.mesh.verticesWithAttributes = verticesWithAttributes; } //TransformedMeshComponent transformedMeshComponentForPhysics = new TransformedMeshComponent(); //transformedMeshComponentForPhysics.meshComponent = meshComponent; IList <ColliderComponent> colliderComponents = new List <ColliderComponent>(); { SpatialVectorDouble colliderComponentSize = new SpatialVectorDouble(new double[] { 2, 2, 2 }); SpatialVectorDouble colliderComponentLocalPosition = new SpatialVectorDouble(new double[] { 0, 0, 0 }); SpatialVectorDouble colliderComponentLocalRotation = new SpatialVectorDouble(new double[] { 0, 0, 0 }); ColliderComponent colliderComponent0 = ColliderComponent.makeBox(colliderComponentSize, colliderComponentLocalPosition, colliderComponentLocalRotation); colliderComponents.Add(colliderComponent0); } ///physicsEngine.physicsAndMeshPairs.Add(new PhysicsComponentAndCollidersPair(physicsComponent, colliderComponents)); // same mesh for the visualization TransformedMeshComponent transformedMeshComponentForRendering = new TransformedMeshComponent(); transformedMeshComponentForRendering.meshComponent = meshComponent; ///softwareRenderer.physicsAndMeshPairs.Add(new PhysicsComponentAndMeshPair(physicsComponent, transformedMeshComponentForRendering)); physicsEngine.tick(); // TODO< read object description from json and create physics and graphics objects > // TODO< read and create solid description from json > // create and store solids of rocket // refactored /* * if ( true ) { * * * SolidCluster solidClusterOfRocket = new SolidCluster(); * * // create solid of rocket * { * SpatialVectorDouble solidSize = new SpatialVectorDouble(new double[] { 2, 2, 2 }); * double massOfSolidInKilogram = 1.0; * IList<CompositionFraction> solidCompositionFractions = new List<CompositionFraction>() { new CompositionFraction(new Isotope("Fe56"), massOfSolidInKilogram) }; * Composition solidComposition = new Composition(solidCompositionFractions); * * physics.solid.Solid solid = physics.solid.Solid.makeBox(solidComposition, solidSize); * * SpatialVectorDouble solidLocalPosition = new SpatialVectorDouble(new double[] { 0, 0, 0 }); * SpatialVectorDouble solidLocalRotation = new SpatialVectorDouble(new double[] { 0, 0, 0 }); * * solidClusterOfRocket.solids.Add(new SolidCluster.SolidWithPositionAndRotation(solid, solidLocalPosition, solidLocalRotation)); * } * * /// TODO, uncommented because it uses the not existing physics object * /// solidResponsibility.mapping.physicsObjectIdToSolidCluster[rocketPhysicsObject.id] = solidClusterOfRocket; * } */ // add test particle if (false) { SpatialVectorDouble particlePosition = new SpatialVectorDouble(new double[] { 0, 0, 0 }); SpatialVectorDouble particleVelocity = new SpatialVectorDouble(new double[] { 0, 0, 1 }); PhysicsComponent particlePhysicsComponent = physicsEngine.createPhysicsComponent(particlePosition, particleVelocity, 1.0, null); physicsEngine.addParticle(particlePhysicsComponent); } // write game object for TestMissile if (true) { DemoObjectSerializer.seralizeAndWriteShip(); DemoObjectSerializer.serializeAndWriteMissile(); } GameObjectBuilder gameObjectBuilder = new GameObjectBuilder(); gameObjectBuilder.physicsEngine = physicsEngine; gameObjectBuilder.softwareRenderer = softwareRenderer; gameObjectBuilder.solidResponsibility = solidResponsibility; gameObjectBuilder.effectResponsibility = effectResponsibility; gameObjectBuilder.thrusterResponsibility = thrusterResponsibility; gameObjectBuilder.attitudeAndAccelerationControlResponsibility = attitudeAndAccelerationControlResponsibility; // load missile game object from json and construct it if (false) { GameObjectTemplate deserilizedGameObjectTemplate; // load { List <string> uriParts = new List <string>(AssemblyDirectory.Uri.Segments); uriParts.RemoveAt(0); // remove first "/" uriParts.RemoveRange(uriParts.Count - 4, 4); uriParts.AddRange(new string[] { "gameResources/", "prototypingMissile.json" }); string path = string.Join("", uriParts).Replace('/', '\\').Replace("%20", " "); string fileContent = File.ReadAllText(path); deserilizedGameObjectTemplate = GameObjectTemplate.deserialize(fileContent); } // build game object from template Entity createdEntity; { SpatialVectorDouble globalPosition = new SpatialVectorDouble(new double[] { 0, 0, 5 }); SpatialVectorDouble globalVelocity = new SpatialVectorDouble(new double[] { 0, 0, 0 }); createdEntity = gameObjectBuilder.buildFromTemplate(deserilizedGameObjectTemplate, globalPosition, globalVelocity); entityManager.addEntity(createdEntity); } // manually add components { // TODO< chemical explosive ignition component > DummyComponent chemicalExplosiveIgnitionComponent = new DummyComponent(); // remap proximityEnter to explode EventRemapperComponent eventRemapper = new EventRemapperComponent(chemicalExplosiveIgnitionComponent); eventRemapper.eventTypeMap["proximityEnter"] = "explode"; // TODO< blacklist somehow other missiles > PhysicsComponent parentPhysicsComponent = createdEntity.getSingleComponentsByType <PhysicsComponent>(); ProximityDetectorComponent proximityDetector = ProximityDetectorComponent.makeSphereDetector(physicsEngine, parentPhysicsComponent, 20.0, eventRemapper); entityManager.addComponentToEntity(createdEntity, proximityDetector); } } Entity playerShip; if (true) { GameObjectTemplate deserilizedGameObjectTemplate; // load { List <string> uriParts = new List <string>(AssemblyDirectory.Uri.Segments); uriParts.RemoveAt(0); // remove first "/" uriParts.RemoveRange(uriParts.Count - 4, 4); uriParts.AddRange(new string[] { "gameResources/", "prototypingShip.json" }); string path = string.Join("", uriParts).Replace('/', '\\').Replace("%20", " "); string fileContent = File.ReadAllText(path); deserilizedGameObjectTemplate = GameObjectTemplate.deserialize(fileContent); } // build game object from template { SpatialVectorDouble globalPosition = new SpatialVectorDouble(new double[] { 0, 0, 10 }); SpatialVectorDouble globalVelocity = new SpatialVectorDouble(new double[] { 0, 0, 0 }); Entity createdEntity = gameObjectBuilder.buildFromTemplate(deserilizedGameObjectTemplate, globalPosition, globalVelocity); entityManager.addEntity(createdEntity); playerShip = createdEntity; } } Entity aiShip = null; EntityController aiShipController = new EntityController(); VehicleAlignToCommand command = null; bool withTestAiShip = true; if (withTestAiShip) { GameObjectTemplate deserilizedGameObjectTemplate; // load { List <string> uriParts = new List <string>(AssemblyDirectory.Uri.Segments); uriParts.RemoveAt(0); // remove first "/" uriParts.RemoveRange(uriParts.Count - 4, 4); uriParts.AddRange(new string[] { "gameResources/", "prototypingShip.json" }); string path = string.Join("", uriParts).Replace('/', '\\').Replace("%20", " "); string fileContent = File.ReadAllText(path); deserilizedGameObjectTemplate = GameObjectTemplate.deserialize(fileContent); } // build game object from template { SpatialVectorDouble globalPosition = new SpatialVectorDouble(new double[] { 0, 0, 10 }); SpatialVectorDouble globalVelocity = new SpatialVectorDouble(new double[] { 0, 0, 0 }); Entity createdEntity = gameObjectBuilder.buildFromTemplate(deserilizedGameObjectTemplate, globalPosition, globalVelocity); entityManager.addEntity(createdEntity); aiShip = createdEntity; } { // control aiShip.getSingleComponentsByType <VehicleControllerComponent>().controller = aiShipController; } { // AI initialization double dt = 1.0 / 60.0; SpatialVectorDouble targetDirection = new SpatialVectorDouble(new double[] { 1, 0, 0.1 }).normalized(); double targetDerivationDistance = 0.001; ulong targetPhysicsObjectId = aiShip.getSingleComponentsByType <PhysicsComponent>().id; command = VehicleAlignToCommand.makeByGettingPidConfigurationFromAttitudeAndAccelerationControlResponsibility( attitudeAndAccelerationControlResponsibility, physicsEngine, dt, targetDirection, aiShipController, targetPhysicsObjectId, targetDerivationDistance); } } // { } playerShip.getSingleComponentsByType <VehicleControllerComponent>().controller = entityController; // create test GUI { Button button = new subsystems.gui.Button(); button.position = new SpatialVectorDouble(new double[] { 0.2, 0.2 }); button.size = new SpatialVectorDouble(new double[] { 0.3, 0.1 }); button.text = "[Gamesave05-res.save](35)"; button.textScale = new SpatialVectorDouble(new double[] { 0.05, 0.08 }); guiContext.addGuiElement(button); } ulong frameCounter = 0; ulong debugFrameCounter = 0; // used to limit the frames we do for debugging a scenario bool isFixedScenarioDebugMode = false; // TODO< use logger > StreamWriter debugLogFileOfVariables = null; // used to debug variables and coeeficients of the debug scenario if (isFixedScenarioDebugMode) { if (!File.Exists("E:\\myLogShipOrientation.txt")) { using (var stream = File.Create("E:\\myLogShipOrientation.txt")); } debugLogFileOfVariables = File.AppendText("E:\\myLogShipOrientation.txt"); } for (;;) { Console.WriteLine("frame={0}", frameCounter); guiContext.tick(); physicsEngine.tick(); if (!isFixedScenarioDebugMode) { prototypeForm.Refresh(); Application.DoEvents(); // HACK, EVIL } // AI { // we just do this small AI because we are testing if (false && aiShip != null) { command.process(); } } // AI - attitude control test // we change the rotation velocity of the spacecraft directly to simulate "perfect" thruster control { PhysicsComponent objectOfControlledSpacecraft = aiShip.getSingleComponentsByType <PhysicsComponent>(); double // principal moments of inertia of the body // the controller assumes that the body has an inertia tensor like an box, but small derivations are propably fine, too J11 = objectOfControlledSpacecraft.inertiaTensor[0, 0], J22 = objectOfControlledSpacecraft.inertiaTensor[1, 1], J33 = objectOfControlledSpacecraft.inertiaTensor[2, 2], // angular velocity of spacecraft in spacecraft frame w1 = objectOfControlledSpacecraft.eulerLocalAngularVelocity.x, w2 = objectOfControlledSpacecraft.eulerLocalAngularVelocity.y, w3 = objectOfControlledSpacecraft.eulerLocalAngularVelocity.z, // result values q1Dot, q2Dot, q3Dot, q4Dot, w1Dot, w2Dot, w3Dot, // coeefficients, taken from the paper gamma = 0.7, aCoefficient = 1.25, d = 7.5, k = 3.0, betaOne = 0.001; // calculate the rotation delta to our target orientation from the current orientation double debugMagnitude = objectOfControlledSpacecraft.rotation.magnitude; Quaternion spacecraftOrientationError = objectOfControlledSpacecraft.rotation.difference(QuaternionUtilities.makeFromEulerAngles(0, 0.5, 0)); QuaternionFeedbackRegulatorForSpacecraft.calcControl( J11, J22, J33, spacecraftOrientationError.i, spacecraftOrientationError.j, spacecraftOrientationError.k, spacecraftOrientationError.scalar, w1, w2, w3, out q1Dot, out q2Dot, out q3Dot, out q4Dot, out w1Dot, out w2Dot, out w3Dot, aCoefficient, gamma, d, k, betaOne ); Console.WriteLine( "w1dot={0}, w2dot={1}, w3dot={2}", w1Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w2Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w3Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) ); if (isFixedScenarioDebugMode) { debugLogFileOfVariables.WriteLine("w1dot={0}, w2dot={1}, w3dot={2}", w1Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w2Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture), w3Dot.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture)); debugLogFileOfVariables.Flush(); } // access directly objectOfControlledSpacecraft.eulerLocalAngularVelocity.x += (w1Dot * (1.0 / 60.0)); objectOfControlledSpacecraft.eulerLocalAngularVelocity.y += (w2Dot * (1.0 / 60.0)); objectOfControlledSpacecraft.eulerLocalAngularVelocity.z += (w3Dot * (1.0 / 60.0)); } attitudeAndAccelerationControlResponsibility.resetAllThrusters(); entityManager.updateAllEntities(); // order after update is important attitudeAndAccelerationControlResponsibility.limitAllThrusters(); attitudeAndAccelerationControlResponsibility.transferThrusterForce(); //thruster.forceInNewton = 0.5 * entityController.inputAcceleration; if (!isFixedScenarioDebugMode) { Thread.Sleep((int)((1.0 / 60.0) * 1000.0)); } if (isFixedScenarioDebugMode) { debugLogFileOfVariables.WriteLine("{0},", aiShip.getSingleComponentsByType <PhysicsComponent>().rotation.j.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture)); debugLogFileOfVariables.Flush(); } //File.AppendText("E:\\myLogShipOrientation.txt").WriteLine("{0},", aiShip.getSingleComponentsByType<PhysicsComponent>().rotation.y); if (isFixedScenarioDebugMode && debugFrameCounter >= 8000) // 30000 { break; } debugFrameCounter++; frameCounter++; } }
/// <summary> /// Draws nothing. /// </summary> public override void Render(GuiContext c) { }
public RootContext () { GuiContext = new GuiContext(); instance = this; Turn = 1; }
public GuiManager(UserSession parent) : base(parent) { Context = new GuiContext(1024, 768); // first gen iPad resolution }
/// <summary> /// Draws this control, or if it's a container, all of the /// nested controls. /// </summary> public abstract void Render(GuiContext c);