public Window() : base(640, 480, GraphicsMode.Default, "XSharp") { GL.Enable(EnableCap.DepthTest); ISharpShape shape = new Sphere().Subsect(new Vector(0.5, 0.5, 0.5), new Vector(0.5, 0.5, 0.5)); this.Tree = OctoTree.Create(shape, 5); PointCloud.Point[] points = new PointCloud.Point[80000]; for (int t = 0; t < points.Length; t++) { double ang = (double)t / (double)points.Length * Math.PI * 2.0; double elv = (double)Math.Sin(ang * 100.0); double x = (double)Math.Sin(ang); double z = (double)Math.Cos(ang); points[t] = new PointCloud.Point() { Position = new Vector(x, z, elv), A = 255, R = 0, G = 255, B = 0 }; } this.MyPointCloud = new PointCloud(); this.MyPointCloud.Submit(points, 2.0f); }
/// <summary> /// Initializes a new instance of the <see cref="SphereObject"/> class. /// </summary> /// <param name="pos">The pos.</param> /// <param name="raio">The raio.</param> /// <param name="mass">The mass.</param> /// <param name="scale">The scale.</param> /// <param name="materialDescription">The material description.</param> public SphereObject(Vector3 pos, float raio, float mass = 10,float scale = 1,MaterialDescription materialDescription = null) : base(materialDescription,mass) { this.scale = new Vector3(scale); entity = new Sphere(pos, raio * scale, mass); }
public TestableInput(TestableGameObject obj, IInput input, Sphere sphere) : base(obj) { this.sphere = sphere; this.input = input; }
internal static Scene SphereScene (int level, Vector center, double radius) { Sphere sphere = new Sphere (center, radius); if (level == 1) { return sphere; } else { Group scene = new Group (new Sphere (center, 3.0 * radius)); scene.Add (sphere); double rn = 3.0 * radius / Math.Sqrt (12.0); for (int dz = -1; dz <= 1; dz += 2) { for (int dx = -1; dx <= 1; dx += 2) { Vector c2 = new Vector ( center.x - dx * rn , center.y + rn , center.z - dz * rn ); scene.Add (SphereScene (level - 1, c2, radius / 2.0)); } } return scene; } }
public void Sphere_Constructor_saves_radius() { var centre = new Point(50.0f, -12.0f, 4.2f); var radius = 12.2f; var s = new Sphere(centre, radius); Assert.AreEqual(radius, s.Radius); }
public static Result ModifyObjectColor(RhinoDoc doc) { ObjRef obj_ref; var rc = RhinoGet.GetOneObject("Select object", false, ObjectType.AnyObject, out obj_ref); if (rc != Result.Success) return rc; var rhino_object = obj_ref.Object(); var color = rhino_object.Attributes.ObjectColor; bool b = Rhino.UI.Dialogs.ShowColorDialog(ref color); if (!b) return Result.Cancel; rhino_object.Attributes.ObjectColor = color; rhino_object.Attributes.ColorSource = ObjectColorSource.ColorFromObject; rhino_object.CommitChanges(); // an object's color attributes can also be specified // when the object is added to Rhino var sphere = new Sphere(Point3d.Origin, 5.0); var attributes = new ObjectAttributes(); attributes.ObjectColor = Color.CadetBlue; attributes.ColorSource = ObjectColorSource.ColorFromObject; doc.Objects.AddSphere(sphere, attributes); doc.Views.Redraw(); return Result.Success; }
/// <summary> /// Constructs a new demo. /// </summary> /// <param name="game">Game owning this demo.</param> public BroadPhaseDemo(DemosGame game) : base(game) { //Make a fatter kapow sphere. Space.Remove(kapow); kapow = new Sphere(new Vector3(11000, 0, 0), 1.5f, 1000); Space.Add(kapow); Space.Solver.IterationLimit = 1; //Essentially no sustained contacts, so don't need to worry about accuracy. Space.ForceUpdater.Gravity = Vector3.Zero; int numColumns = 15; int numRows = 15; int numHigh = 15; float separation = 3; Entity toAdd; for (int i = 0; i < numRows; i++) for (int j = 0; j < numColumns; j++) for (int k = 0; k < numHigh; k++) { toAdd = new Box(new Vector3(separation * i, k * separation, separation * j), 1, 1, 1, 1); toAdd.Material.Bounciness = 1; //Superbouncy boxes help propagate shock waves. toAdd.LinearDamping = 0f; toAdd.AngularDamping = 0f; Space.Add(toAdd); } game.Camera.Position = new Vector3(0, 3, -10); game.Camera.ViewDirection = new Vector3(0, 0, 1); }
public void sphere(Vector3 a, float r, Color c) { var s = new Sphere(); s.At = a; s.Radius = r; s.Col = c; Spheres.Add(s); }
public void SetCollision() { MotionState motionState = new MotionState(); motionState.Position = Position; motionState.Orientation = Quaternion.Identity; Entity = new Sphere(motionState, radius, mass); }
/// <summary> /// Constructs a new demo. /// </summary> /// <param name="game">Game owning this demo.</param> public IncomingDemo(DemosGame game) : base(game) { Entity toAdd; //Build the stack... for (int k = 1; k <= 12; k++) { if (k % 2 == 1) { toAdd = new Box(new Vector3(-3, k, 0), 1, 1, 7, 10); Space.Add(toAdd); toAdd = new Box(new Vector3(3, k, 0), 1, 1, 7, 10); Space.Add(toAdd); } else { toAdd = new Box(new Vector3(0, k, -3), 7, 1, 1, 10); Space.Add(toAdd); toAdd = new Box(new Vector3(0, k, 3), 7, 1, 1, 10); Space.Add(toAdd); } } //And then smash it! toAdd = new Sphere(new Vector3(0, 150, 0), 3, 100); Space.Add(toAdd); Space.Add(new Box(new Vector3(0, 0, 0), 10, 1f, 10)); game.Camera.Position = new Vector3(0, 6, 30); }
public void RealizaTeste(List<BoundingVolume> boundingVolumes) { PRN = new List<PreRedeNeural> (); for (int i = 0; i < boundingVolumes.Count; i++) { if (tipo.AaA){ BoundingVolume c1 = boundingVolumes [i]; List<Vector> pontos = new List<Vector> (); int nome2 = 0; for (int j = 0; j < boundingVolumes.Count; j++) { if (i != j) { pontos.AddRange (boundingVolumes [j].Pontos.ToArray ()); nome2 += Convert.ToInt32 (Math.Pow (2,i)); } } BoundingVolume c2 = new OBB (pontos, nome2, boundingVolumes [i].nivel); if (tipo.BV == 2){ } if (tipo.BV == 1){ //caixas.Add(new AABB(dadosTreino[i], "-" + i.ToString() + "-",0)); } if (tipo.BV == 0){ c2 = new Sphere (pontos, nome2, boundingVolumes [i].nivel); } //encontra todos os planos List<Plano> planos = testeColisao (c1, c2); //seleciona os melhores planos planos = SelecionaPlanos (c1, c2, planos); //gera a pré-rede neural PreRedeNeural p = GeraPreRedeNeural (c1, c2, planos); PRN.Add (p); } else { BoundingVolume c1 = boundingVolumes [i]; for (int j=i+1; j<boundingVolumes.Count; j++) { //encontra os planos BoundingVolume c2 = boundingVolumes [j]; List<Plano> planos = testeColisao (c1, c2); //seleciona os melhores planos planos = SelecionaPlanos (c1, c2, planos); //gera a pré-rede neural PreRedeNeural p = GeraPreRedeNeural (c1, c2, planos); PRN.Add (p); } } Console.WriteLine(" + - RN " + i.ToString() + " gerada."); } }
public static void Run() { // Initialize scene object Scene scene = new Scene(); // Initialize Node class object Node cubeNode = new Node("sphere"); // ExStart:ConvertSpherePrimitivetoMesh // Initialize object by Sphere class IMeshConvertible convertible = new Sphere(); // Convert a Sphere to Mesh Mesh mesh = convertible.ToMesh(); // ExEnd:ConvertSpherePrimitivetoMesh // Point node to the Mesh geometry cubeNode.Entity = mesh; // Add Node to a scene scene.RootNode.ChildNodes.Add(cubeNode); // The path to the documents directory. string MyDir = RunExamples.GetDataDir() + RunExamples.GetOutputFilePath("SphereToMeshScene.fbx"); // Save 3D scene in the supported file formats scene.Save(MyDir, FileFormat.FBX7400ASCII); Console.WriteLine("\n Converted the primitive Sphere to a mesh successfully.\nFile saved at " + MyDir); }
/// <summary> /// Constructs a new demo. /// </summary> /// <param name="game">Game owning this demo.</param> public PlanetDemo(DemosGame game) : base(game) { Space.ForceUpdater.Gravity = Vector3.Zero; //By pre-allocating a bunch of box-box pair handlers, the simulation will avoid having to allocate new ones at runtime. NarrowPhaseHelper.Factories.BoxBox.EnsureCount(1000); var planet = new Sphere(new Vector3(0, 0, 0), 30); Space.Add(planet); var field = new GravitationalField(new InfiniteForceFieldShape(), planet.Position, 66730 / 2f, 100); Space.Add(field); //Drop the "meteorites" on the planet. Entity toAdd; int numColumns = 10; int numRows = 10; int numHigh = 10; float separation = 5; for (int i = 0; i < numRows; i++) for (int j = 0; j < numColumns; j++) for (int k = 0; k < numHigh; k++) { toAdd = new Box(new Vector3(separation * i - numRows * separation / 2, 40 + k * separation, separation * j - numColumns * separation / 2), 1f, 1f, 1f, 5); toAdd.LinearVelocity = new Vector3(30, 0, 0); toAdd.LinearDamping = 0; toAdd.AngularDamping = 0; Space.Add(toAdd); } game.Camera.Position = new Vector3(0, 0, 150); }
protected CharacterCardBase(CardType printedCardType, string title, CardSet cardSet, uint cardNumber, Sphere printedSphere, byte printedWillpower, byte printedAttack, byte printedDefense, byte printedHitPoints) : base(printedCardType, title, cardSet, cardNumber, printedSphere) { this.PrintedWillpower = printedWillpower; this.PrintedAttack = printedAttack; this.PrintedDefense = printedDefense; this.PrintedHitPoints = printedHitPoints; }
void Launch() { Sphere sphere = new Sphere(Game.Camera.Position, 1, 10); sphere.CollisionInformation.Events.InitialCollisionDetected += eventHandler; sphere.LinearVelocity = Game.Camera.WorldMatrix.Forward * 30; Space.Add(sphere); Game.ModelDrawer.Add(sphere); }
private void SetUp() { //Earth diameter is 0.042479 light seconds diameter = 1.042479f; //Distance from Earth to sun is 499.2 light seconds distanceToStar = 499.2f; sphere = new Sphere(diameter / 2, device, Microsoft.Xna.Framework.Color.White, 90); }
//public Skybox( Game game, Camera camera ) : base( game, "skybox" ) //{ // this.camera = camera; //} public GameSpace(Game game, String model) : base(game, model) { _sphere = new Sphere(BEPUutilities.Vector3.Zero, 100f); //_sphere.PositionUpdateMode = PositionUpdateMode.Continuous; //(game.Services.GetService(typeof(Space)) as Space).Add(_sphere); }
public MainForm() { InitializeComponent(); p = new Perspective(this); testSphere = new Sphere (new Point3(100, 100, 0), 100, Color.Yellow); testSphere2 = new Sphere (new Point3 (250, 250, 0), 50, Color.Blue); testSphere3 = new Sphere (new Point3 (250, 250, 0), 10, Color.Wheat); }
public Asteroid(string id, int health) : base(id, "Asteroid_model", 1, 0, 0, 0) { _box = new Sphere(new Vector3(0, 0, 0), 1.45f, Geometric.Generate_Quaternion(0, 0, 0, 0)); _health = health; _damage = 0; _isDead = false; }
protected override void LoadContent() { Texture2D progradeTex = Content.Load<Texture2D> ("Prograde.png"); Texture2D hor = Content.Load<Texture2D> ("Horizon.png"); ball = new Sphere (1.0f, graphics.GraphicsDevice, hor, progradeTex, Content.Load<Texture2D>("Retrograde"),Content.Load<Texture2D>("Maneuver"),Content.Load<Texture2D>("Target_prograde"), Content.Load<Texture2D>("Target_retrograde")); }
public static Minkowski_Description Minkowskize_Sphere_In_OBB(Sphere sph, OBB obb) { var ret = new Minkowski_Description(); ret.HalfAxis.X = sph.Radius; ret.Position_LM = obb.Point_W_To_L(sph.Position); return ret; }
/// <summary> /// Create sphere model physics. /// </summary> /// <param name="game">The game.</param> /// <param name="model">The visual model.</param> /// <param name="position">The position of the sphere entity.</param> /// <param name="mass">The physics mass.</param> public SphereModelPhysics(XiGame game, Model model, Vector3 position, float mass) { this.game = game; Vector3[] vertices; int[] indices; model.GetVerticesAndIndices(out vertices, out indices); BoundingSphere boundingSphere = BoundingSphere.CreateFromPoints(vertices); body = new Sphere(position, boundingSphere.Radius, mass); }
public Asteroid(Game game, string model) : base(game, model) { _sphere = new Sphere(2 * MathConverter.Convert(Vector3.Up), 0.5f, 8.0f); _sphere.CollisionInformation.Events.InitialCollisionDetected += Events_InitialCollisionDetected; _sphere.PositionUpdateMode = PositionUpdateMode.Continuous; (game.Services.GetService(typeof(Space)) as Space).Add(_sphere); }
public ObjectComposer AppendDummyCollider() { Sphere sphere = new Sphere(Vector3.Zero, 0); owner.PhysicsSpace.Add(sphere); sphere.Tag = currentObject; currentObject.PhysicsEntity = sphere; return onColliderAdded(); }
public void Sphere_GetNormalAtPoint_returns_normalised_vector() { var centre = new Point(50.0f, -12.0f, 4.2f); var radius = 10.0f; var s = new Sphere(centre, radius); var actual = s.GetNormalAtPoint(new Point(60.0f, -12.0f, 4.2f)); Assert.AreEqual(1.0f, actual.Norm(), EPSILON); }
public bool Intersect(Sphere s) { Plane p = Plane.FromPointAndNormal(s.Position, Direction); float f = p.Intersect(Start, End); if (f < 0) f = 0; else if (f > 1) f = 1; Vector3 nearest = Start + f * (End - Start); float dist = (s.Position - nearest).Length; return dist <= s.Radius; }
public void Sphere_GetNormalAtPoint_returns_vector_in_correct_direction() { var centre = new Point(50.0f, -12.0f, 4.2f); var radius = 10.0f; var s = new Sphere(centre, radius); var actual = s.GetNormalAtPoint(new Point(60.0f, -12.0f, 4.2f)); Assert.AreEqual(new Vector(1.0f, 0.0f, 0.0f), actual); }
public void Load(GraphicsDevice decive, ContentManager content) { tex = content.Load<Texture2D>("skyhalf"); sphere = Sphere.CreateHalf(decive, 15, 7, v=> new VertexPositionTexture(v.Position, new Vector2(v.TextureCoordinate.X , 1-v.TextureCoordinate.Y))); //sphere = Sphere.Create(decive); sphere.effect.Texture = tex; sphere.effect.TextureEnabled = true; }
public static void RayTrace(float cX, float cY, float cZ, float r, float eyeX, float eyeY, float eyeZ, float dirX, float dirY, float dirZ) { // Sphere.intersect() does not use the {@code surface} field. Sphere sphere = new Sphere(null, new Vector3D(cX, cY, cZ), r); ArrayList objects = new ArrayList(); objects.Add(sphere); Vector3D eye = new Vector3D(eyeX, eyeY, eyeZ); Vector3D dir = new Vector3D(dirX, dirY, dirZ); new Ray(eye, dir).Trace(objects); }
public TestableExample(TestableGameObject parent, IAudioSource source, Sphere sphere, [Resource("audio/beep")] AudioClip beep) : base(parent) { this.source = source; this.beep = beep; this.Obj.transform.localScale = new Vector3(5, 5, 5); }
public void ChangingTransform() { var s = new Sphere(Translation(2f, 3f, 4f)); Assert.AreEqual(s.Transform.Matrix, Translation(2f, 3f, 4f)); }
/// <summary> /// GetLocalSkinWireframe /// </summary> /// <param name="skin"></param> /// <returns>VertexPositionColor[]</returns> public static VertexPositionColor[] GetLocalSkinWireframe(this CollisionSkin skin) { List <VertexPositionColor> wireframe = new List <VertexPositionColor>(); for (int i = 0; i < skin.NumPrimitives; i++) { Primitive p = skin.GetPrimitiveLocal(i); Matrix trans = p.TransformMatrix; if (p is Sphere) { Sphere np = (Sphere)p; List <Vector3> SpherePoints = calcCirclePoints(np.Radius); AddShapeToWireframe(SpherePoints, wireframe, trans, Color.Blue); AddShapeToWireframe(SpherePoints, wireframe, Matrix.CreateRotationY(MathHelper.PiOver2) * trans, Color.Red); AddShapeToWireframe(SpherePoints, wireframe, Matrix.CreateRotationX(MathHelper.PiOver2) * trans, Color.Green); } else if (p is Capsule) { Capsule np = (Capsule)p; List <Vector3> Ball = calcCirclePoints(np.Radius); List <Vector3> CylPoints = new List <Vector3>(); List <Vector3> CirclePoints = new List <Vector3>(); List <Vector3> SidePoints = new List <Vector3>(); // Create LongWays profile slice foreach (Vector3 v in Ball) { Vector3 t = Vector3.Transform(v, Matrix.CreateRotationX(MathHelper.PiOver2)); CylPoints.Add(t); } float len = np.Length; SidePoints.Add(Vector3.Transform(new Vector3(np.Radius, len, 0), Matrix.CreateRotationX(MathHelper.PiOver2))); SidePoints.Add(Vector3.Transform(new Vector3(np.Radius, 0, 0), Matrix.CreateRotationX(MathHelper.PiOver2))); SidePoints.Add(Vector3.Transform(new Vector3(-np.Radius, 0, 0), Matrix.CreateRotationX(MathHelper.PiOver2))); SidePoints.Add(Vector3.Transform(new Vector3(-np.Radius, len, 0), Matrix.CreateRotationX(MathHelper.PiOver2))); // Create Y Rungs AddShapeToWireframe(Ball, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0.0f * len)) * trans, Color.Green); AddShapeToWireframe(Ball, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0.5f * np.Length)) * trans, Color.Green); AddShapeToWireframe(Ball, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 1.0f * np.Length)) * trans, Color.Green); // Create Z Profile Matrix Zmat = Matrix.CreateRotationZ(MathHelper.PiOver2); AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, np.Length)) * Zmat * trans, Color.Blue); AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Zmat * trans, Color.Blue); AddLineToWireframe(SidePoints[0], SidePoints[1], wireframe, Zmat * trans, Color.Blue); AddLineToWireframe(SidePoints[2], SidePoints[3], wireframe, Zmat * trans, Color.Blue); //// Create X Profile Matrix Xmat = Matrix.Identity; AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, np.Length)) * Xmat * trans, Color.Red); AddShapeToWireframe(CylPoints, wireframe, Matrix.CreateTranslation(new Vector3(0, 0, 0)) * Xmat * trans, Color.Red); AddLineToWireframe(SidePoints[0], SidePoints[1], wireframe, Xmat * trans, Color.Red); AddLineToWireframe(SidePoints[2], SidePoints[3], wireframe, Xmat * trans, Color.Red); } else if (p is Box) { Box np = (Box)p; List <Vector3> xPoints = new List <Vector3>(); List <Vector3> yPoints = new List <Vector3>(); List <Vector3> zPoints = new List <Vector3>(); Vector3 slen = np.SideLengths; xPoints.Add(new Vector3(slen.X, slen.Y, slen.Z)); xPoints.Add(new Vector3(0, slen.Y, slen.Z)); xPoints.Add(new Vector3(slen.X, 0, slen.Z)); xPoints.Add(new Vector3(0, 0, slen.Z)); xPoints.Add(new Vector3(slen.X, slen.Y, 0)); xPoints.Add(new Vector3(0, slen.Y, 0)); xPoints.Add(new Vector3(slen.X, 0, 0)); xPoints.Add(new Vector3(0, 0, 0)); yPoints.Add(new Vector3(slen.X, slen.Y, slen.Z)); yPoints.Add(new Vector3(slen.X, 0, slen.Z)); yPoints.Add(new Vector3(0, slen.Y, slen.Z)); yPoints.Add(new Vector3(0, 0, slen.Z)); yPoints.Add(new Vector3(slen.X, slen.Y, 0)); yPoints.Add(new Vector3(slen.X, 0, 0)); yPoints.Add(new Vector3(0, slen.Y, 0)); yPoints.Add(new Vector3(0, 0, 0)); zPoints.Add(new Vector3(slen.X, slen.Y, slen.Z)); zPoints.Add(new Vector3(slen.X, slen.Y, 0)); zPoints.Add(new Vector3(0, slen.Y, slen.Z)); zPoints.Add(new Vector3(0, slen.Y, 0)); zPoints.Add(new Vector3(slen.X, 0, slen.Z)); zPoints.Add(new Vector3(slen.X, 0, 0)); zPoints.Add(new Vector3(0, 0, slen.Z)); zPoints.Add(new Vector3(0, 0, 0)); AddLinesToWireframe(xPoints, wireframe, trans, Color.Red); AddLinesToWireframe(yPoints, wireframe, trans, Color.Green); AddLinesToWireframe(zPoints, wireframe, trans, Color.Blue); } else if (p is AABox) { } else if (p is Heightmap) { Heightmap hm = (Heightmap)p; Vector3 point, normal; for (int e = 0; e < hm.Heights.Nx; e += 5) { for (int j = 0; j < hm.Heights.Nz; j += 5) { hm.GetSurfacePosAndNormal(out point, out normal, e, j); AddLineToWireframe(point, point - 0.5f * normal, wireframe, trans, Color.GreenYellow); } } } else if (p is JigLibX.Geometry.Plane) { } else if (p is TriangleMesh) { TriangleMesh np = (TriangleMesh)p; for (int j = 0; j < np.GetNumTriangles(); j++) { IndexedTriangle t = np.GetTriangle(j); Vector3 p1 = np.GetVertex(t.GetVertexIndex(0)); Vector3 p2 = np.GetVertex(t.GetVertexIndex(1)); Vector3 p3 = np.GetVertex(t.GetVertexIndex(2)); List <Vector3> tPoints = new List <Vector3>(); tPoints.Add(p1); tPoints.Add(p2); tPoints.Add(p3); tPoints.Add(p1); AddShapeToWireframe(tPoints, wireframe, trans, Color.Red); } } } return(wireframe.ToArray()); }
public void SetWalkableCheckPos(Sphere sphere) { WalkableCheckPos = new Sphere(sphere); }
public void ClearSphereText(Sphere SphereToClear) { SphereToClear.textmesh.text = ""; }
static void Main(string[] args) { Console.WriteLine("Generating a transparency!"); // Floor of scene var floor = new Plane(); floor.Transform = Matrix.RotationY(0.31415); floor.Material.Reflective = 0.1; floor.Material.Specular = 0.8; floor.Material.Diffuse = 0.4; floor.Material.Ambient = 0.5; floor.Material.Pattern = new CheckersPattern(Color.Black, new Color(0.75, 0.75, 0.75)); // Ceiling of scene var ceiling = new Plane(); ceiling.Transform = Matrix.Translation(0, 5, 0); ceiling.Material.Specular = 0; ceiling.Material.Ambient = 0.5; ceiling.Material.Pattern = new CheckersPattern(new Color(0.85, 0.85, 0.85), new Color(1, 1, 1)); ceiling.Material.Pattern.Transform = Matrix.Scaling(0.2, 0.2, 0.2); // West wall var wwall = new Plane(); wwall.Transform = Matrix.Translation(-5, 0, 0) * Matrix.RotationZ(1.5708) * Matrix.RotationY(1.5708); wwall.Material.Specular = 0; wwall.Material.Pattern = new CheckersPattern(Color.Black, new Color(0.75, 0.75, 0.75)); wwall.Material.Pattern.Transform = Matrix.Scaling(0.5, 0.5, 0.5); // East wall var ewall = new Plane(); ewall.Transform = Matrix.Translation(5, 0, 0) * Matrix.RotationZ(1.5708) * Matrix.RotationY(1.5708); ewall.Material.Specular = 0; ewall.Material.Pattern = new CheckersPattern(Color.Black, new Color(0.75, 0.75, 0.75)); ewall.Material.Pattern.Transform = Matrix.Scaling(0.5, 0.5, 0.5); // North wall var nwall = new Plane(); nwall.Transform = Matrix.Translation(0, 0, 5) * Matrix.RotationX(1.5708); nwall.Material.Specular = 0; nwall.Material.Pattern = new CheckersPattern(Color.Black, new Color(0.75, 0.75, 0.75)); nwall.Material.Pattern.Transform = Matrix.Scaling(0.5, 0.5, 0.5); // South wall var swall = new Plane(); swall.Transform = Matrix.Translation(0, 0, -5) * Matrix.RotationX(1.5708); swall.Material.Specular = 0; swall.Material.Pattern = new CheckersPattern(Color.Black, new Color(0.75, 0.75, 0.75)); swall.Material.Pattern.Transform = Matrix.Scaling(0.5, 0.5, 0.5); // Background Ball 1 var bball1 = new Sphere(); bball1.Transform = Matrix.Translation(4, 1, 4); bball1.Material.Color = new Color(0.8, 0.1, 0.3); bball1.Material.Specular = 0; // Background Ball 2 var bball2 = new Sphere(); bball2.Transform = Matrix.Translation(4.6, 0.4, 2.9) * Matrix.Scaling(0.4, 0.4, 0.4); bball2.Material.Color = new Color(0.1, 0.8, 0.2); bball2.Material.Shininess = 200; // Background Ball 3 var bball3 = new Sphere(); bball3.Transform = Matrix.Translation(2.6, 0.6, 4.4) * Matrix.Scaling(0.6, 0.6, 0.6); bball3.Material.Color = new Color(0.2, 0.1, 0.8); bball3.Material.Shininess = 10; bball3.Material.Specular = 0.4; // Glass Ball var gball = new Sphere(); gball.Transform = Matrix.Translation(0.25, 1, 0) * Matrix.Scaling(1, 1, 1); gball.Material.Color = new Color(0.8, 0.8, 0.9); gball.Material.Ambient = 0; gball.Material.Diffuse = 0.2; gball.Material.Specular = 0.9; gball.Material.Shininess = 300; gball.Material.Transparency = 0.8; gball.Material.RefractiveIndex = 1.57; var world = new World(); world.Lights.Add(new PointLight(new Point(-4.9, 4.9, 1), Color.White)); world.Objects.Add(floor); world.Objects.Add(ceiling); world.Objects.Add(wwall); world.Objects.Add(ewall); world.Objects.Add(nwall); world.Objects.Add(swall); world.Objects.Add(bball1); world.Objects.Add(bball2); world.Objects.Add(bball3); world.Objects.Add(gball); var camera = new Camera(400, 400, 0.5); camera.Transform = Matrix.ViewTransform(new Point(-4.5, 0.85, -4), new Point(0, 0.85, 0), Vector.VectorY); var c = camera.Render(world); System.IO.File.WriteAllText("transparency.ppm", c.GetPPM()); Console.WriteLine("Done!"); }
public Renderable(ref Sphere s) : this() { Type = RenderableType.Sphere; SphereData = s; }
public void SphereHasMaterial() { var s = new Sphere(); Assert.AreEqual(s.Material, PhongMaterial.Default); }
/// <summary> /// Tests for intersection between this sphere and another sphere. /// </summary> /// <param name="sphere">Other sphere.</param> /// <returns>True if the spheres intersect, false otherwise.</returns> public bool Intersects(Sphere sphere) { return((sphere.center - center).Length <= (sphere.radius + radius)); }
protected EventCardBase(string title, CardSet cardSet, uint cardNumber, Sphere printedSphere, byte resourceCost) : base(CardType.Event, title, cardSet, cardNumber, printedSphere, resourceCost) { }
/// <summary> /// Draws the scene with an environment map. /// </summary> private void DrawEnvironmentMap() { #region Pass 1-6 GraphicsDevice.DepthStencilState = DepthStencilState.Default; // Draw to our cubemap from the robot position for (var face = CubeMapFace.PositiveX; face <= CubeMapFace.NegativeZ; face++) { // Set the render target as our cubemap face, we are drawing the scene in this texture GraphicsDevice.SetRenderTarget(EnvironmentMapRenderTarget, face); GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0); SetCubemapCameraForOrientation(face); CubeMapCamera.BuildView(); // Draw our scene. Do not draw our tank as it would be occluded by itself // (if it has backface culling on) Scene.Draw(Matrix.Identity, CubeMapCamera.View, CubeMapCamera.Projection); } #endregion #region Pass 7 // Set the render target as null, we are drawing on the screen! GraphicsDevice.SetRenderTarget(null); GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0); // Draw our scene with the default effect and default camera Scene.Draw(Matrix.Identity, Camera.View, Camera.Projection); // Draw our sphere #region Draw Sphere Effect.CurrentTechnique = Effect.Techniques["EnvironmentMapSphere"]; Effect.Parameters["environmentMap"].SetValue(EnvironmentMapRenderTarget); Effect.Parameters["eyePosition"].SetValue(Camera.Position); var sphereWorld = Matrix.CreateTranslation(SpherePosition); // World is used to transform from model space to world space Effect.Parameters["World"].SetValue(sphereWorld); // InverseTransposeWorld is used to rotate normals Effect.Parameters["InverseTransposeWorld"]?.SetValue(Matrix.Transpose(Matrix.Invert(sphereWorld))); // WorldViewProjection is used to transform from model space to clip space Effect.Parameters["WorldViewProjection"].SetValue(sphereWorld * Camera.View * Camera.Projection); Sphere.Draw(Effect); #endregion #region Draw Robot // Set up our Effect to draw the robot Effect.CurrentTechnique = Effect.Techniques["EnvironmentMap"]; Effect.Parameters["baseTexture"].SetValue(BasicEffect.Texture); // We get the base transform for each mesh var modelMeshesBaseTransforms = new Matrix[Robot.Bones.Count]; Robot.CopyAbsoluteBoneTransformsTo(modelMeshesBaseTransforms); var worldMatrix = Matrix.CreateTranslation(RobotPosition); // World is used to transform from model space to world space Effect.Parameters["World"].SetValue(worldMatrix); // InverseTransposeWorld is used to rotate normals Effect.Parameters["InverseTransposeWorld"]?.SetValue(Matrix.Transpose(Matrix.Invert(worldMatrix))); // WorldViewProjection is used to transform from model space to clip space Effect.Parameters["WorldViewProjection"].SetValue(worldMatrix * Camera.View * Camera.Projection); Robot.Meshes.FirstOrDefault().Draw(); #endregion // Debug our cubemap! // Show a quad DebugTextureEffect.Parameters["World"].SetValue(QuadWorld); DebugTextureEffect.Parameters["cubeMapTexture"]?.SetValue(EnvironmentMapRenderTarget); FullScreenQuad.Draw(DebugTextureEffect); #endregion }
public static int GetIntersections(Line l, Sphere s, out double p1, out double p2) { return(GetIntersections(l.origin, l.vector, s, out p1, out p2)); }
private float distanceTo(Sphere otherSphere) { return((transform.position - otherSphere.transform.position).magnitude); }
///------------------------------------------------------------------------------------------------- /// <summary> Main entry-point for this application. </summary> /// /// <remarks> Kemp, 1/18/2019. </remarks> /// /// <param name="args"> An array of command-line argument strings. </param> ///------------------------------------------------------------------------------------------------- static void Main(string[] args) { World defaultWorld = new World(); defaultWorld.AddLight(new LightPoint(new Point(-10, 10, -10), new Color(1, 1, 1))); Sphere s1 = new Sphere(); s1.Material = new Material(); s1.Material.Color = new Color(0.8, 1.0, 0.6); s1.Material.Diffuse = new Color(0.7, 0.7, 0.7); s1.Material.Specular = new Color(0.2, 0.2, 0.2); Sphere s2 = new Sphere(); s2.Transform = MatrixOps.CreateScalingTransform(0.5, 0.5, 0.5); defaultWorld.AddObject(s1); defaultWorld.AddObject(s2); { //ComputingNormalOnTranslatedShape TestShape s = new TestShape(); s.Transform = MatrixOps.CreateTranslationTransform(0, 1, 0); RayTracerLib.Vector n = s.NormalAt(new Point(0, 1.70711, -0.70711)); bool foo = (n.Equals(new RayTracerLib.Vector(0, 0.70711, -0.70711))); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~"); } { World w = new World(); w.AddLight(new LightPoint(new Point(-10, 10, -10), new Color(1, 1, 1))); Sphere s3 = new Sphere(); s3.Material = new Material(); s3.Material.Color = new Color(0.8, 1.0, 0.6); s3.Material.Diffuse = new Color(0.7, 0.7, 0.7); s3.Material.Specular = new Color(0.2, 0.2, 0.2); w.AddObject(s3); Plane p = new Plane(); p.Transform = (Matrix)(MatrixOps.CreateTranslationTransform(0, 0, 2) * MatrixOps.CreateRotationXTransform(Math.PI / 2)); p.Material.Pattern = new CheckedPattern(new Color(0, 0, 1), new Color(1, 0.9, 0.9)); w.AddObject(p); Plane p1 = new Plane(); p1.Transform = MatrixOps.CreateTranslationTransform(1, 0, 0); p1.Material.Pattern = new GradientPattern(new Color(1, 0, 0), new Color(1, 0.9, 0.9)); w.AddObject(p1); Ray r = new Ray(new Point(1, 1, -5), new RayTracerLib.Vector(0, -0.5, 0)); List <Intersection> xs = p.Intersect(r); bool foo1, foo2, foo3; if (xs.Count > 0) { foo1 = (xs.Count == 1); foo2 = (xs[0].T >= 1); foo3 = (xs[0].Obj.Equals(p)); } Camera camera = new Camera(400, 200, Math.PI / 2); camera.Transform = MatrixOps.CreateViewTransform(new Point(3, 3, -5), new Point(0, 0, 0), new RayTracerLib.Vector(0, 1, 0)); Canvas image = w.Render(camera); String ppm = image.ToPPM(); System.IO.File.WriteAllText(@"ToPPM.ppm", ppm); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~"); } Console.Write("Press Enter to finish ... "); Console.Read(); }
public void DefaultTransform() { var s = new Sphere(); Assert.AreEqual(s.Transform, Transform.Identity); }
public float dostuff() { Sphere s = new Sphere(42); return(s.r); }
/// <summary> /// Create an STL file for a cell. /// Currently only works for cells with both hyperideal vertices and cells. /// </summary> public static void HoneycombHyperidealLegs(HoneycombDef def, int lod, Dictionary <Vector3D, H3.Cell> complete) { int p = def.P; int q = def.Q; int r = def.R; m_div = TextureHelper.SetLevels(lod); bool ball = false; Sphere[] simplex = SimplexCalcs.Mirrors(p, q, r, moveToBall: ball); H3.Cell.Edge[] edges; if (ball) { edges = SimplexCalcs.SimplexEdgesBall(p, q, r); } else { edges = SimplexCalcs.SimplexEdgesUHS(p, q, r); } // Two edges of one simplex facet. H3.Cell.Edge e1 = edges[2]; H3.Cell.Edge e2 = edges[3]; Vector3D[] points1, points2; if (ball) { points1 = H3Models.Ball.GeodesicPoints(e1.Start, e1.End, 2 * m_div); points2 = H3Models.Ball.GeodesicPoints(e2.Start, e2.End, 2 * m_div); } else { points1 = H3Models.UHS.GeodesicPoints(e1.Start, e1.End, 2 * m_div); points2 = H3Models.UHS.GeodesicPoints(e2.Start, e2.End, 2 * m_div); } Sphere cellSphere = simplex[0]; Sphere vertexSphere = simplex[3]; // Because one vertex the facet triangle is hyperideal, it will actually look like a square. List <Vector3D[]> allPoints = new List <Vector3D[]>(); for (int i = 0; i < points1.Length; i++) { Vector3D p1 = points1[i]; Vector3D p2 = points2[i]; Vector3D[] arcPoints; if (i == points1.Length - 1) //if( false ) { // NOTE: This arc is not generally geodesic! // Or is it? arcPoints = ball ? H3Models.Ball.GeodesicPoints(p1, p2, m_div) : H3Models.UHS.GeodesicPoints(p1, p2, m_div); /*Circle3D arc = cellSphere.Intersection( vertexSphere ); * double angleTot = (p1 - arc.Center).AngleTo( p2 - arc.Center ); * arcPoints = Shapeways.CalcArcPoints( arc.Center, arc.Radius, p1, arc.Normal, -angleTot, div );*/ } else { Circle3D c = Circle3D.FromCenterAnd2Points(cellSphere.Center, p1, p2); double angleTot = (p1 - c.Center).AngleTo(p2 - c.Center); arcPoints = Shapeways.CalcArcPoints(cellSphere.Center, cellSphere.Radius, p1, c.Normal, -angleTot, m_div); } //Vector3D[] arcPoints = new Vector3D[] { p1, p2 }; allPoints.Add(arcPoints); } // Create the triangles for the patch. Mesh mesh = new Mesh(); for (int i = 0; i < allPoints.Count - 1; i++) { Vector3D[] arc1 = allPoints[i]; Vector3D[] arc2 = allPoints[i + 1]; for (int j = 0; j < arc1.Length - 1; j++) { // Points of (i,j) box; Vector3D p1 = arc1[j]; Vector3D p2 = arc2[j]; Vector3D p3 = arc1[j + 1]; Vector3D p4 = arc2[j + 1]; Mesh.Triangle tri1 = new Mesh.Triangle(p1, p2, p3); Mesh.Triangle tri2 = new Mesh.Triangle(p2, p4, p3); // We need to thicken after reflecting around, otherwise we can't apply a min thickness. /*Sphere normal = cellSphere; * Mesh.Triangle[] thickened1 = Thicken( tri1, normal ); * Mesh.Triangle[] thickened2 = Thicken( tri2, normal ); * mesh.Triangles.AddRange( thickened1 ); * mesh.Triangles.AddRange( thickened2 );*/ mesh.Triangles.Add(tri1); mesh.Triangles.Add(tri2); } } // AuxPoints will be used for multiple things. // - The first two points are for an an that will fill the gap where there is a missing face. // - We'll also store the points for the 4 edges of our fundamental triangle. List <Vector3D> auxPoints = new List <Vector3D>(); { var edge1 = allPoints.First(); var edge2 = allPoints.Last(); List <Vector3D> edge3 = new List <Vector3D>(), edge4 = new List <Vector3D>(); for (int i = 0; i < allPoints.Count; i++) { edge3.Add(allPoints[i][0]); edge4.Add(allPoints[i][allPoints[i].Length - 1]); } edge4.Reverse(); auxPoints.Add(e1.Start); auxPoints.Add(e1.End); auxPoints.AddRange(edge1.Reverse()); auxPoints.AddRange(edge2); auxPoints.AddRange(edge3); auxPoints.AddRange(edge4); } Vector3D cen = HoneycombPaper.InteriorPointBall; /* Reorientation code. Move this elsewhere. * * // Face centered orientation. * bool faceCentered = false; * if( faceCentered ) * SimplexCalcs.PrepForFacetCentering( p, q, simplex, ref cen ); * * Mobius mUHS = SimplexCalcs.FCOrientMobius( p, q ); * Mobius mBall = HoneycombPaper.FCOrientMobius( H3Models.UHSToBall( cellSphere ) ); * * simplex = simplex.Select( s => * { * s = H3Models.UHSToBall( s ); * //H3Models.TransformInBall2( s, mBall ); * return s; * } ).ToArray(); * * * { * for( int i = 0; i < mesh.Triangles.Count; i++ ) * { * Mesh.Triangle tri = mesh.Triangles[i]; * * if( faceCentered ) * { * tri.a = mUHS.ApplyToQuaternion( tri.a ); * tri.b = mUHS.ApplyToQuaternion( tri.b ); * tri.c = mUHS.ApplyToQuaternion( tri.c ); * } * * tri.a = H3Models.UHSToBall( tri.a ); * tri.b = H3Models.UHSToBall( tri.b ); * tri.c = H3Models.UHSToBall( tri.c ); * * if( faceCentered ) * { * tri.a = H3Models.TransformHelper( tri.a, mBall ); * tri.b = H3Models.TransformHelper( tri.b, mBall ); * tri.c = H3Models.TransformHelper( tri.c, mBall ); * } * mesh.Triangles[i] = tri; * } * * if( faceCentered ) * cen = H3Models.TransformHelper( cen, mBall ); * } */ // Now we need to reflect around this fundamental patch. H3.Cell[] simplices = GenCell(simplex, mesh, cen, auxPoints.ToArray(), ball); // Existing cells take precedence. foreach (H3.Cell c in simplices) { Vector3D t = c.Center; H3.Cell dummy; if (!complete.TryGetValue(t, out dummy)) { complete[t] = c; } } }
// Start is called before the first frame update void Start() { sphere = SphereObject.GetComponent <Sphere>(); sphere.SendMessage("SendtoConsole"); }
private static void HoneycombFiniteVertexFig(HoneycombDef def, int lod, Dictionary <Vector3D, H3.Cell> complete) { int p = def.P; int q = def.Q; int r = def.R; double scale = 1.0; Vector3D vUHS = H3Models.BallToUHS(SimplexCalcs.VertexPointBall(p, q, r)); if (Geometry2D.GetGeometry(q, r) != Geometry.Hyperbolic) // Vertex-centered if possible { scale = 1.0 / vUHS.Z; } System.Func <Vector3D, Vector3D> trans = v => { v = H3Models.BallToUHS(v); v *= scale; v = H3Models.UHSToBall(v); return(v); }; bool ball = true; Sphere[] simplex = SimplexCalcs.Mirrors(p, q, r, moveToBall: ball); simplex = simplex.Select(s => { s = H3Models.BallToUHS(s); Sphere.ScaleSphere(s, scale); s = H3Models.UHSToBall(s); return(s); }).ToArray(); H3.Cell.Edge[] edges = SimplexCalcs.SimplexEdgesBall(p, q, r); // Two edges of the simplex facet. // NOTE: This contruction only works for material triangles, and matches the construction in the TextureHelper. m_div = TextureHelper.SetLevels(lod); int[] elementIndices = TextureHelper.TextureElements(1, lod); List <Vector3D> points = new List <Vector3D>(); H3.Cell.Edge e1 = edges[2]; H3.Cell.Edge e2 = edges[3]; Vector3D p1 = trans(e1.Start), p2 = trans(e1.End), p3 = trans(e2.End); Vector3D[] points1 = H3Models.Ball.GeodesicPoints(p2, p1, m_div); Vector3D[] points2 = H3Models.Ball.GeodesicPoints(p3, p1, m_div); for (int i = 0; i < m_div; i++) { points.AddRange(H3Models.Ball.GeodesicPoints(points1[i], points2[i], m_div - i)); } points.Add(p1); Mesh mesh = new Mesh(); for (int i = 0; i < elementIndices.Length / 3; i++) { int idx1 = i * 3; int idx2 = i * 3 + 1; int idx3 = i * 3 + 2; Vector3D v1 = points[elementIndices[idx1]]; Vector3D v2 = points[elementIndices[idx2]]; Vector3D v3 = points[elementIndices[idx3]]; mesh.Triangles.Add(new Mesh.Triangle(v1, v2, v3)); } // AuxPoints will be used for multiple things. // - The first is a definition point for a face, so we can check for duplicates. // - We'll also store the points for the 3 edges of our fundamental triangle. List <Vector3D> auxPoints = new List <Vector3D>(); { auxPoints.Add((p1 + p2 + p3) / 3); auxPoints.AddRange(points1); auxPoints.AddRange(points2.Reverse()); auxPoints.AddRange(H3Models.Ball.GeodesicPoints(points2[0], points1[0], m_div)); } Vector3D cen = HoneycombPaper.InteriorPointBall; H3.Cell[] simplices = GenCell(simplex, mesh, cen, auxPoints.ToArray(), ball); // Existing cells take precedence. foreach (H3.Cell c in simplices) { Vector3D t = c.AuxPoints[0]; H3.Cell dummy; if (!complete.TryGetValue(t, out dummy)) { complete[t] = c; } } }
public unsafe override void Initialize(ContentArchive content, Camera camera) { camera.Position = new Vector3(-20f, 13, -20f); camera.Yaw = MathHelper.Pi * 3f / 4; camera.Pitch = MathHelper.Pi * 0.1f; Simulation = Simulation.Create(BufferPool, new DemoNarrowPhaseCallbacks(), new DemoPoseIntegratorCallbacks(new Vector3(0, -10, 0))); var shape = new Sphere(0.5f); shape.ComputeInertia(1, out var sphereInertia); var shapeIndex = Simulation.Shapes.Add(shape); const int width = 64; const int height = 64; const int length = 64; var spacing = new Vector3(1.01f); var halfSpacing = spacing / 2; float randomization = 0.9f; var randomizationSpan = (spacing - new Vector3(1)) * randomization; var randomizationBase = randomizationSpan * -0.5f; var random = new Random(5); for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { for (int k = 0; k < length; ++k) { var r = new Vector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); var location = spacing * (new Vector3(i, j, k) + new Vector3(-width, 1, -length)) + randomizationBase + r * randomizationSpan; if ((i + j + k) % 2 == 1) { var bodyDescription = new BodyDescription { Activity = new BodyActivityDescription { MinimumTimestepCountUnderThreshold = 32, SleepThreshold = -0.1f }, Pose = new RigidPose { Orientation = BepuUtilities.Quaternion.Identity, Position = location }, Collidable = new CollidableDescription { Continuity = new ContinuousDetectionSettings { Mode = ContinuousDetectionMode.Discrete }, SpeculativeMargin = 0.1f, Shape = shapeIndex }, LocalInertia = sphereInertia }; Simulation.Bodies.Add(bodyDescription); } else { var staticDescription = new StaticDescription { Pose = new RigidPose { Orientation = BepuUtilities.Quaternion.Identity, Position = location }, Collidable = new CollidableDescription { Continuity = new ContinuousDetectionSettings { Mode = ContinuousDetectionMode.Discrete }, SpeculativeMargin = 0.1f, Shape = shapeIndex } }; Simulation.Statics.Add(staticDescription); } } } } refineTimes = new TimingsRingBuffer(sampleCount, BufferPool); testTimes = new TimingsRingBuffer(sampleCount, BufferPool); }
public void IsShape() { var s = new Sphere(); s.Should().BeAssignableTo <IGeometry>(); }
public void SetSphereColor(Sphere sphere, Color SphereColor) { Renderer SphereRenderer = sphere.GetComponent <Renderer>(); SphereRenderer.material.SetColor("_Color", SphereColor); }
// // Used to connect up the four thickened edges of the region. // private static Mesh ThickenBoundary(Vector3D[] edge, Sphere normal) { System.Func <Vector3D, System.Tuple <Vector3D, Vector3D> > fn = v => Thicken(v, normal); return(ThickenBoundary(edge, fn)); }
private static System.Tuple <Vector3D, Vector3D> ThickenSimple(Vector3D v, Dictionary <Vector3D, Vector3D> normalMap) { Sphere s = SphereFuncBall(Geometry.Hyperbolic, v); return(ThickenSimple(v, normalMap[v], s.Radius)); }
unsafe void DeformationMeshParallel() { Vertex[] vertices = new Vertex[vertex_count]; ushort[] indices = new ushort[index_count]; mesh.SubMeshes[0].VertexData.GetSomeGeometry(ref changeable_vertex_pos, ref changeable_vertex_norm); if (first_init_mesh == false) { /*for (int i = 0; i < vertex_count; i++) * { * Vertex vertex = new Vertex(); * vertex.position = original_vertex_pos[i]; * vertex.normal = original_vertex_norm[i]; * vertex.texCoord = original_vertex_tc[i]; * vertices[i] = vertex; * } * for (int i = 0; i < index_count; i++) * { * indices[i] = (ushort)(original_vertex_ind[i]); * }*/ ParallelLoopResult parallel_result = Parallel.For(0, vertex_count, i => { Vertex vertex = new Vertex(); vertex.position = original_vertex_pos[i]; vertex.normal = original_vertex_norm[i]; vertex.texCoord = original_vertex_tc[i]; vertices[i] = vertex; }); if (parallel_result.IsCompleted) { for (int i = 0; i < index_count; i++) { indices[i] = (ushort)(original_vertex_ind[i]); } } SubMesh sub_mesh = mesh.SubMeshes[0]; { HardwareVertexBuffer vertex_buffer = sub_mesh.VertexData.VertexBufferBinding.GetBuffer(0); IntPtr buffer = vertex_buffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(Vertex *pvertices = vertices) { NativeUtils.CopyMemory(buffer, (IntPtr)pvertices, vertices.Length * sizeof(Vertex)); } vertex_buffer.Unlock(); } { HardwareIndexBuffer index_buffer = sub_mesh.IndexData.IndexBuffer; IntPtr buffer = index_buffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(ushort *pindices = indices) { NativeUtils.CopyMemory(buffer, (IntPtr)pindices, indices.Length * sizeof(ushort)); } index_buffer.Unlock(); } first_init_mesh = true; } else { if (hit_other != null) { ParallelLoopResult parallel_result = Parallel.For(0, vertex_count, i => { Vertex vertex = new Vertex(); Vec3 p = ((original_vertex_pos[i] * attached_mesh.ScaleOffset) * Rotation) + (Position + attached_mesh.PositionOffset); Vec3 pp = hit_pos; Sphere sp = new Sphere(pp, Type.CONF.DeformationRadius); Vec3 nvec = Vec3.Zero; Vec3 nnorm = Vec3.Zero; if (sp.IsContainsPoint(p)) { Ray ray = new Ray(p, changeable_vertex_norm[i] * .01f); if (!Single.IsNaN(ray.Direction.X) && !Single.IsNaN(ray.Origin.X)) { RayCastResult[] piercingResult = PhysicsWorld.Instance.RayCastPiercing( ray, (int)ContactGroup.CastOnlyDynamic);/*(int)ContactGroup.CastOnlyContact);*/ Vec3 collision_pos = Vec3.Zero; Vec3 collision_nor = Vec3.Zero; bool collision = false; foreach (RayCastResult result in piercingResult) { if (Array.IndexOf(PhysicsModel.Bodies, result.Shape.Body) != -1) { continue; } collision = true; collision_pos = result.Position; collision_nor = result.Normal; break; } if (collision) { float old_x = 0, old_y = 0, old_z = 0, new_x = 0, new_y = 0, new_z = 0; float deformation = 0, force = 0, max_deformation = Type.CONF.MaxStrengthDeformation, mass = 0, vel = 0; mass = hit_other.Body.Mass; vel = hit_other.Body.LastStepLinearVelocity.Length(); force = (((hit_this.Body.Mass * hit_this.Body.LastStepLinearVelocity.Length()) + (mass * vel)) / hit_this.Body.Mass) / 100.0f; if (force > max_deformation) { deformation = max_deformation; } else { deformation = force; } //Deform X if (changeable_vertex_pos[i].X > 0) { old_x = original_vertex_pos[i].X - deformation; if (old_x < changeable_vertex_pos[i].X) { new_x = old_x; } else { new_x = changeable_vertex_pos[i].X; } } else { old_x = original_vertex_pos[i].X + deformation; if (old_x > changeable_vertex_pos[i].X) { new_x = old_x; } else { new_x = changeable_vertex_pos[i].X; } } //Deform Y if (changeable_vertex_pos[i].Y > 0) { old_y = original_vertex_pos[i].Y - deformation; if (old_y < changeable_vertex_pos[i].Y) { new_y = old_y; } else { new_y = changeable_vertex_pos[i].Y; } } else { old_y = original_vertex_pos[i].Y + deformation; if (old_y > changeable_vertex_pos[i].Y) { new_y = old_y; } else { new_y = changeable_vertex_pos[i].Y; } } //Deform Z if (changeable_vertex_pos[i].Z > 0) { old_z = original_vertex_pos[i].Z - deformation; if (old_z < changeable_vertex_pos[i].Z) { new_z = old_z; } else { new_z = changeable_vertex_pos[i].Z; } } else { old_z = original_vertex_pos[i].Z + deformation; if (old_z > changeable_vertex_pos[i].Z) { new_z = old_z; } else { new_z = changeable_vertex_pos[i].Z; } } nvec = new Vec3(new_x, new_y, new_z); nnorm = -collision_nor; } else { nvec = changeable_vertex_pos[i]; nnorm = changeable_vertex_norm[i]; } } } else { nvec = changeable_vertex_pos[i]; nnorm = changeable_vertex_norm[i]; } vertex.position = nvec; vertex.normal = nnorm; vertex.texCoord = original_vertex_tc[i]; vertices[i] = vertex; }); if (parallel_result.IsCompleted) { for (int i = 0; i < index_count; i++) { indices[i] = (ushort)(original_vertex_ind[i]); } SubMesh sub_mesh = mesh.SubMeshes[0]; { HardwareVertexBuffer vertex_buffer = sub_mesh.VertexData.VertexBufferBinding.GetBuffer(0); IntPtr buffer = vertex_buffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(Vertex *pvertices = vertices) { NativeUtils.CopyMemory(buffer, (IntPtr)pvertices, vertices.Length * sizeof(Vertex)); } vertex_buffer.Unlock(); } { HardwareIndexBuffer index_buffer = sub_mesh.IndexData.IndexBuffer; IntPtr buffer = index_buffer.Lock(HardwareBuffer.LockOptions.Discard); fixed(ushort *pindices = indices) { NativeUtils.CopyMemory(buffer, (IntPtr)pindices, indices.Length * sizeof(ushort)); } index_buffer.Unlock(); } } } hit_other = null; } }
public static void S3BiHelicoid() { double cutoff = 8.0; int div = 500; Matrix4D mat = Matrix4D.MatrixToRotateinCoordinatePlane(1 * Math.PI / 4, 0, 3); Mesh m1 = S3Helicoid(div, mat, reciprocal: false); //m1.Triangles = m1.Triangles.Where( t => t.a.Abs() < cutoff && t.b.Abs() < cutoff && t.c.Abs() < cutoff ).ToList(); Mesh m2 = S3Helicoid(div, mat, reciprocal: true); //m2.Triangles = m2.Triangles.Where( t => t.a.Abs() < cutoff && t.b.Abs() < cutoff && t.c.Abs() < cutoff ).ToList(); Mesh m3 = new Mesh(); System.Action <bool> addCore = recip => { List <Vector3D> circlePoints = new List <Vector3D>(); double aOffset = 2 * Math.PI / div; for (int i = 0; i <= div; i++) { double x = Math.Sin(aOffset * i); double y = Math.Cos(aOffset * i); circlePoints.Add(recip ? new Vector3D(x, y) : new Vector3D(0, 0, x, y)); } // partial transform to R3 here. circlePoints = circlePoints.Select(p => { p = mat.RotateVector(p); p = Sterographic.S3toR3(p); return(p); }).ToList(); List <Vector3D> ePoints = new List <Vector3D>(); List <double> eRadii = new List <double>(); foreach (Vector3D pNE in circlePoints) { Sphere sphere = SphereFuncBall(Geometry.Spherical, pNE, false); ePoints.Add(sphere.Center); eRadii.Add(sphere.Radius); } Shapeways shapeways = new Shapeways(); shapeways.AddClosedCurve(ePoints.ToArray(), eRadii.ToArray()); m3.Append(shapeways.Mesh); }; addCore(false); addCore(true); for (int i = 0; i < m3.Triangles.Count; i++) { Mesh.Triangle t = m3.Triangles[i]; m3.Triangles[i] = Transform(t, SphericalModels.StereoToEquidistant); } string filename = "helicoid.stl"; File.Delete(filename); using (StreamWriter sw = File.AppendText(filename)) { STL.AppendMeshToSTL(m1, sw); STL.AppendMeshToSTL(m2, sw); STL.AppendMeshToSTL(m3, sw); } //HelicoidHelper( thinMesh, boundaryPoints ); }
public BoundingType sphere_intersects_cell(Sphere sphere) { return(CellBSP.sphere_intersects_cell_bsp(sphere)); }
public static void HoneycombFiniteVertexFig(HoneycombDef def) { // This will be used to remove duplicates. // Our faces will be doubled-up. We'll make a hash from one of the interior meshPoints. Dictionary <Vector3D, H3.Cell> complete = new Dictionary <Vector3D, H3.Cell>(); m_thresh = 0.07; HoneycombFiniteVertexFig(def, 3, complete); m_thresh = 0.02; HoneycombFiniteVertexFig(def, 2, complete); m_thresh = 0.007; HoneycombFiniteVertexFig(def, 1, complete); //m_thresh = 0.005; //CreateHoneycombSTL( def, 0, complete ); string filename = "cell.stl"; System.IO.File.Delete(filename); using (StreamWriter sw = File.AppendText(filename)) { foreach (H3.Cell cell in complete.Values) { //STL.AppendMeshToSTL( cell.Mesh, sw ); bool reverse = cell.Depths.Sum() % 2 == 1; Mesh m = new Mesh(); Sphere normal = cell.Facets[0].Sphere; foreach (Mesh.Triangle tri in cell.Mesh.Triangles) { Mesh.Triangle[] thickened = ThickenSimple(tri, normal); m.Triangles.AddRange(thickened); } if (reverse) { ReverseTris(m); } STL.AppendMeshToSTL(m, sw); System.Func <Vector3D, System.Tuple <Vector3D, Vector3D> > thickenFn = v => ThickenSimple(v, normal); int stride = (int)Math.Sqrt(cell.Mesh.Triangles.Count) + 1; Vector3D[] e1 = cell.AuxPoints.Skip(1 + 0 * stride).Take(stride).ToArray(); Vector3D[] e2 = cell.AuxPoints.Skip(1 + 1 * stride).Take(stride).ToArray(); Vector3D[] e3 = cell.AuxPoints.Skip(1 + 2 * stride).Take(stride).ToArray(); Mesh m1 = ThickenBoundary(e1, thickenFn), m2 = ThickenBoundary(e2, thickenFn), m3 = ThickenBoundary(e3, thickenFn); if (reverse) { ReverseTris(m1); ReverseTris(m2); ReverseTris(m3); } STL.AppendMeshToSTL(m1, sw); STL.AppendMeshToSTL(m2, sw); STL.AppendMeshToSTL(m3, sw); } } }
private void OnRecognize(SpeechRecognitionEvent result, Dictionary <string, object> customData) { if (result != null && result.results.Length > 0) { foreach (var res in result.results) { foreach (var alt in res.alternatives) { string text = string.Format("{0} ({1}, {2:0.00})\n", alt.transcript, res.final ? "Final" : "Interim", alt.confidence); Log.Debug("ExampleStreaming.OnRecognize()", text); ResultsField.text = text; bool disappear = text.Contains("disappear"); bool stop = text.Contains("stop"); if (res.final == true) { if (stop == true) { Debug.Log("You said Stop!!"); GameObject Bullet; Bullet = GameObject.Find("Bullet"); Bullet.SetActive(false); } if (disappear == true) { Debug.Log("You said disappear!!"); GameObject House; House = GameObject.Find("House"); House.SetActive(false); GameObject Sphere; Sphere = GameObject.Find("Sphere"); Sphere.SetActive(false); GameObject Cube; Cube = GameObject.Find("Cube"); Cube.SetActive(false); } } } if (res.keywords_result != null && res.keywords_result.keyword != null) { foreach (var keyword in res.keywords_result.keyword) { Log.Debug("ExampleStreaming.OnRecognize()", "keyword: {0}, confidence: {1}, start time: {2}, end time: {3}", keyword.normalized_text, keyword.confidence, keyword.start_time, keyword.end_time); } } if (res.word_alternatives != null) { foreach (var wordAlternative in res.word_alternatives) { Log.Debug("ExampleStreaming.OnRecognize()", "Word alternatives found. Start time: {0} | EndTime: {1}", wordAlternative.start_time, wordAlternative.end_time); foreach (var alternative in wordAlternative.alternatives) { Log.Debug("ExampleStreaming.OnRecognize()", "\t word: {0} | confidence: {1}", alternative.word, alternative.confidence); } } } } } }
public static void HoneycombHyperidealLegs(HoneycombDef def) { // This will be used to avoid duplicates. // The key is the cell center. Dictionary <Vector3D, H3.Cell> complete = new Dictionary <Vector3D, H3.Cell>(); m_thresh = 0.05; //m_thresh = 0.07; HoneycombHyperidealLegs(def, 3, complete); m_thresh = 0.01; //m_thresh = 0.02; HoneycombHyperidealLegs(def, 2, complete); m_thresh = 0.004; //m_thresh = 0.007; HoneycombHyperidealLegs(def, 1, complete); string filename = "cell.stl"; System.IO.File.Delete(filename); using (StreamWriter sw = File.AppendText(filename)) { HashSet <H3.Cell.Edge> edgesToMesh = new HashSet <H3.Cell.Edge>(new H3.Cell.EdgeEqualityComparer()); foreach (H3.Cell cell in complete.Values) { int depth = cell.Depths.Sum(); Mesh m = new Mesh(); Sphere normal = cell.Facets[0].Sphere; foreach (Mesh.Triangle tri in cell.Mesh.Triangles) { Mesh.Triangle[] thickened = Thicken(tri, normal); m.Triangles.AddRange(thickened.Select(t => Transform(t))); } List <object> boundary = new List <object>(); int skip = 2; int stride = (int)Math.Sqrt(cell.Mesh.Triangles.Count) / 2 + 1; int num = stride; boundary.Add(cell.AuxPoints.Skip(skip).Take(num)); skip += num; boundary.Add(cell.AuxPoints.Skip(skip).Take(num)); skip += num; num = 2 * m_div + 1; boundary.Add(cell.AuxPoints.Skip(skip).Take(num)); skip += num; boundary.Add(cell.AuxPoints.Skip(skip).Take(num)); skip += num; foreach (object e in boundary) { var enumerable = (IEnumerable <Vector3D>)e; //if( depth % 2 == 0 ) // enumerable = enumerable.Reverse(); Mesh m2 = ThickenBoundary(enumerable.ToArray(), normal); if (depth % 2 == 0) { ReverseTris(m2); } m.Triangles.AddRange(m2.Triangles.Select(t => Transform(t))); } STL.AppendMeshToSTL(m, sw); edgesToMesh.Add(new H3.Cell.Edge(cell.AuxPoints[0], cell.AuxPoints[1])); } /*foreach( H3.Cell.Edge e in edgesToMesh ) * { * Mesh m3 = new Mesh(); * AddEdge( m3, Transform( e.Start ), Transform( e.End ) ); * STL.AppendMeshToSTL( m3, sw ); * }*/ } }
public static Scene LoadJsonFile(string fileName) { var scene = new Scene { Meshes = new List <Mesh>() }; var data = File.ReadAllText(fileName); var json = JObject.Parse(data); // Import polyhedrons. foreach (var jToken in (JArray)json["meshes"]) { var meshJson = (JObject)jToken; if (meshJson["vertices"] == null) { if (((string)meshJson["name"]).Equals("Cube")) { var mesh = new Cube((float)meshJson["length"], (float)meshJson["width"], (float)meshJson["height"]) { Position = ParseVector3(meshJson["position"]), Rotation = ParseQuaternion(meshJson["rotation"]), Scaling = ParseVector3(meshJson["scaling"]), Name = (string)meshJson["name"] }; scene.Meshes.Add(mesh); } else if (((string)meshJson["name"]).Equals("Sphere")) { var mesh = new Sphere((float)meshJson["radius"], (int)meshJson["numberLongtitude"], (int)meshJson["numberLatitude"]) { Position = ParseVector3(meshJson["position"]), Rotation = ParseQuaternion(meshJson["rotation"]), Scaling = ParseVector3(meshJson["scaling"]), Name = (string)meshJson["name"] }; scene.Meshes.Add(mesh); } else if (((string)meshJson["name"]).Equals("Cone")) { var mesh = new Cone((float)meshJson["height"], (float)meshJson["bottomRadius"], (float)meshJson["topRadius"], (int)meshJson["numberSides"], (int)meshJson["numberHeight"]) { Position = ParseVector3(meshJson["position"]), Rotation = ParseQuaternion(meshJson["rotation"]), Scaling = ParseVector3(meshJson["scaling"]), Name = (string)meshJson["name"] }; scene.Meshes.Add(mesh); } else if (((string)meshJson["name"]).Equals("Cylinder")) { var mesh = new Cylinder((float)meshJson["height"], (float)meshJson["bottomRadius1"], (float)meshJson["bottomRadius2"], (float)meshJson["topRadius1"], (float)meshJson["topRadius2"], (int)meshJson["numberSides"]) { Position = ParseVector3(meshJson["position"]), Rotation = ParseQuaternion(meshJson["rotation"]), Scaling = ParseVector3(meshJson["scaling"]), Name = (string)meshJson["name"] }; scene.Meshes.Add(mesh); } } else { // Plane var verticesArray = (JArray)meshJson["vertices"]; var indicesArray = (JArray)meshJson["indices"]; var verticesCount = verticesArray.Count / 3; var facesCount = indicesArray.Count / 3; var mesh = new Mesh(verticesCount, facesCount) { Position = ParseVector3(meshJson["position"]), Rotation = ParseQuaternion(meshJson["rotation"]), Scaling = ParseVector3(meshJson["scaling"]), Name = (string)meshJson["name"] }; for (int i = 0; i < verticesCount; i++) { mesh.Vertices[i] = ParseVector3(verticesArray, i * 3); } // Import triangles. for (int i = 0; i < facesCount; i++) { var a = (int)indicesArray[i * 3]; var b = (int)indicesArray[i * 3 + 1]; var c = (int)indicesArray[i * 3 + 2]; mesh.Faces[i] = new Face(a, b, c); } scene.Meshes.Add(mesh); } } // Import camera settings. var cameraTarget = ParseVector3(json["cameras"][0]["target"]); var cameraPosition = ParseVector3(json["cameras"][0]["position"]); scene.Camera = new Camera { Position = cameraPosition, //Rotation = ParseQuaternion(json["cameras"][0]["rotation"]), LookDirection = (cameraTarget - cameraPosition).Normalize(), FieldOfViewRadians = (float)json["cameras"][0]["fov"] }; // Placing tthe "floor" grid hightest on the list. // The first one will be drawn, and thus it will be hidden behind the polyhedrons in the foreground. var plane = scene.Meshes.First(m => m.Name == "Plane"); scene.Meshes.Remove(plane); scene.Meshes.Insert(0, plane); return(scene); }