/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { //constructs necessary objects cube = new Cube(); sphere = new SpherePrimitive(GraphicsDevice, 1f, 20); effect = new BasicEffect(GraphicsDevice); ballEffect = new BasicEffect(GraphicsDevice); indicaterEffect = new BasicEffect(GraphicsDevice); paddleEffect = new BasicEffect(GraphicsDevice); field = new LineCube(); cubeData = new CubeData[5]; sphereData = new SphereData[1]; //creats cube objects CreateCubes(); //sets the info for the ball sphereData[0].position = Vector3.Zero; sphereData[0].velocity = new Vector3(0, 0, ballSpeed); sphereData[0].color = new Color(NextFloat(0.5f, 1), NextFloat(0, 1), NextFloat(0, 1)); //creates the bounding box fieldBoundingBox = new BoundingBox(new Vector3(-cubeData[0].xScale + cubeData[0].position.X, -cubeData[0].yScale + cubeData[0].position.Y, -cubeData[0].zScale + cubeData[0].position.Z), new Vector3(cubeData[0].xScale + cubeData[0].position.X, cubeData[0].yScale + cubeData[0].position.Y, cubeData[0].zScale + cubeData[0].position.Z)); playerPaddle2 = new BoundingBox(new Vector3(-cubeData[2].xScale + cubeData[2].position.X, -cubeData[2].yScale + cubeData[2].position.Y, -cubeData[2].zScale + cubeData[2].position.X), new Vector3(cubeData[2].xScale + cubeData[2].position.X, cubeData[2].yScale + cubeData[2].position.Y, cubeData[2].zScale + cubeData[2].position.Z)); world = Matrix.Identity; view = Matrix.CreateLookAt(cameraPosition, new Vector3(0, 0, 0), Vector3.Up); projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45f), GraphicsDevice.DisplayMode.AspectRatio, 1f, 1000f); base.Initialize(); }
/// <inheritdoc /> protected override void LoadContent() { // We load the sphere meshe into a model Primitive = new SpherePrimitive(GraphicsDevice, 1f, 6); SpriteFont = Game.Content.Load <SpriteFont>(ContentFolderSpriteFonts + "Arial"); LoadArrows(Primitive); // Load the effect Effect = Game.Content.Load <Effect>(ContentFolderEffects + "BackFace"); // Load the debug texture effect to visualize the shadow map DebugTextureEffect = Game.Content.Load <Effect>(ContentFolderEffects + "DebugTexture"); // Assign the near and far plane distances of the light camera to debug depth DebugTextureEffect.Parameters["nearPlaneDistance"].SetValue(Camera.DefaultNearPlaneDistance); DebugTextureEffect.Parameters["farPlaneDistance"].SetValue(Camera.DefaultFarPlaneDistance); DebugTextureEffect.CurrentTechnique = DebugTextureEffect.Techniques["DebugDepth"]; DrawDepthEffect = Game.Content.Load <Effect>(ContentFolderEffects + "ShadowMap"); FullScreenQuad = new FullScreenQuad(GraphicsDevice); // Create a depth render target. It stores depth from the camera DepthRenderTarget = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, false, SurfaceFormat.Single, DepthFormat.Depth24, 0, RenderTargetUsage.PlatformContents); base.LoadContent(); }
public GeometricObject() { rendering = false; initialized = false; pointAppearance = new Stack <Appearance> (); pointAppearance.Push(new Appearance(Color.red, Color.red, 60f, 1f, 1f)); lineAppearance = new Stack <Appearance> (); lineAppearance.Push(new Appearance(Color.blue, Color.blue, 60f, 1f, 1f)); surfaceAppearance = new Stack <Appearance> (); surfaceAppearance.Push(new Appearance(Color.green, Color.grey, 60f, 1f, 1f)); primitives = new List <PrimitiveBase> (); ptp = new PointPrimitive(); primitives.Add(ptp); lp = new LinePrimitive(); primitives.Add(lp); pp = new PolygonPrimitive(); primitives.Add(pp); sp = new SpherePrimitive(); primitives.Add(sp); mp = new MeshPrimitive(); primitives.Add(mp); }
/// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load the model. currentModel = Content.Load <Model>("dude"); // Look up our custom skinning information. skinningData = currentModel.Tag as SkinningData; if (skinningData == null) { throw new InvalidOperationException ("This model does not contain a SkinningData tag."); } boneTransforms = new Matrix[skinningData.BindPose.Count]; // Load the baseball bat model. baseballBat = Content.Load <Model>("baseballbat"); // Create an animation player, and start decoding an animation clip. animationPlayer = new AnimationPlayer(skinningData); AnimationClip clip = skinningData.AnimationClips["Take 001"]; animationPlayer.StartClip(clip); // Load the bounding spheres. skinnedSpheres = Content.Load <SkinnedSphere[]>("CollisionSpheres"); boundingSpheres = new BoundingSphere[skinnedSpheres.Length]; spherePrimitive = new SpherePrimitive(GraphicsDevice, 1, 12); }
public override RenderableLightPrimitive GetRenderablePrimitive() { LightShader shader = new LightShader(Renderer); using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLight.vs"), true, false))) { shader.VertexShader = new VertexShader(Renderer.Device, bytecode); shader.InputLayout = new InputLayout(Renderer.Device, bytecode, new[] { new InputElement("Position", 0, Format.R32G32B32_Float, sizeof(float) * 0, 0), }); } using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLightShadowless.ps"), true, false))) { shader.PixelShader = new PixelShader(Renderer.Device, bytecode); } using (ShaderBytecode bytecode = new ShaderBytecode(new DataStream(File.ReadAllBytes("Shaders\\DeferredPointLightShadowless.ps"), true, false))) { shader.PixelShaderShadowless = new PixelShader(Renderer.Device, bytecode); } shader.Topology = PrimitiveTopology.TriangleList; ConstantBufferWrapper MatricesCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 32, ShaderType.VertexShader, 0); ConstantBufferWrapper LightCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 64, ShaderType.PixelShader, 0); ConstantBufferWrapper ShadowCBuffer = new ConstantBufferWrapper(Renderer, sizeof(float) * 16 * 4, ShaderType.PixelShader, 1); MatricesCBuffer.Semantics.Add(Semantic.WorldViewProj); MatricesCBuffer.Semantics.Add(Semantic.World); LightCBuffer.Semantics.Add(Semantic.View); LightCBuffer.Semantics.Add(Semantic.ViewInverse); LightCBuffer.Semantics.Add(Semantic.ViewProjInverse); LightCBuffer.Semantics.Add(Semantic.CameraPosition); shader.ConstantBuffers.Add(MatricesCBuffer); shader.ConstantBuffers.Add(LightCBuffer); shader.ConstantBuffers.Add(ShadowCBuffer); GeometricPrimitive prim = new SpherePrimitive(Renderer, 1, 16); DataStream str = new DataStream(prim.GeometryData.Positions, true, false); Buffer vertexBuffer = new Buffer(Renderer.Device, str, new BufferDescription() { SizeInBytes = (int)str.Length, BindFlags = BindFlags.VertexBuffer, StructureByteStride = 3 * sizeof(float), CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None, Usage = ResourceUsage.Default, }); int vertexCount = prim.GeometryData.VertexCount; DataStream IndicesStream = new DataStream(prim.GeometryData.Indices.ToArray(), true, true); int indexCount = prim.GeometryData.IndexCount; Buffer indexBuffer = new Buffer(Renderer.Device, IndicesStream, sizeof(ushort) * indexCount, ResourceUsage.Default, BindFlags.IndexBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, sizeof(ushort)); prim.Dispose(); return new RenderableLightPrimitive(shader, vertexBuffer, vertexCount, indexBuffer, indexCount); }
public Ball(GraphicsDevice device, Vector3 position, Vector3 velocity, Color color, SoundEffect sound) : base(device, position) { Color = color; this.velocity = velocity; sphere = new SpherePrimitive(GraphicsDevice); Sound = sound; Effect = new BasicEffect(GraphicsDevice); }
public GeometricPrimitives(GraphicsDevice graphicsDevice) { Box = new BoxPrimitive(graphicsDevice); Capsule = new CapsulePrimitive(graphicsDevice); Cone = new ConePrimitive(graphicsDevice); Cylinder = new CylinderPrimitive(graphicsDevice); Sphere = new SpherePrimitive(graphicsDevice); }
public void Initialize(GraphicsDevice device, Color color, float angle, Vector3 positionVector, Vector3 rotationVector) { _sphere = new SpherePrimitive(device, _diameter, _tesselation, 2); Color = color; Angle = angle; PositionVector = positionVector; RotationVector = rotationVector; }
public override void GenerateGeometry(string scenePath, List <PrimitiveBase> output) { SpherePrimitive sphere = SpherePrimitive.Create(); sphere.position = Position; sphere.euler = Vector3.zero; sphere.scale = new Vector3(Radius, Radius, Radius) * 2.0f; sphere.material = shaders[0]; output.Add(sphere); }
/// <inheritdoc /> public override void Initialize() { Camera = new TargetCamera(GraphicsDevice.Viewport.AspectRatio, new Vector3(0, 100, 1500), Vector3.Zero, 1, 3000); Sun = new SpherePrimitive(GraphicsDevice, 20, 32, Color.MonoGameOrange); Earth = new SpherePrimitive(GraphicsDevice, 20, 32, Color.LightSkyBlue); Moon = new SpherePrimitive(GraphicsDevice, 20, 32, Color.LightSlateGray); base.Initialize(); }
// Token: 0x0600424D RID: 16973 RVA: 0x00150EBC File Offset: 0x0014F2BC public override void GenerateColliderGeometry() { Mesh colliderMesh = base.GetColliderMesh(); if (colliderMesh) { colliderMesh.Clear(); SpherePrimitive.GenerateGeometry(colliderMesh, this.radius, this.segments, this.hemisphere, this.innerRadius, this.slice, this.normalsType, this.pivotPosition); base.RefreshMeshCollider(); } base.GenerateColliderGeometry(); }
public override void LoadContent() { // Load mesh mesh = new SpherePrimitive(1.0f, 50); // Load effects earthVertexShader = VertexShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/EarthVS.vs", UriKind.Relative)).Stream); earthPixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/EarthPS.ps", UriKind.Relative)).Stream); atmosphereVertexShader = VertexShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/AtmosphereVS.vs", UriKind.Relative)).Stream); cloudsPixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/CloudsPS.ps", UriKind.Relative)).Stream); lowerAtmospherePixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/AtmosphereLowerPS.ps", UriKind.Relative)).Stream); upperAtmospherePixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/AtmosphereUpperPS.ps", UriKind.Relative)).Stream); upperAtmosphereVertexShader = VertexShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/AtmosphereUpperVS.vs", UriKind.Relative)).Stream); // Load textures atmosphereTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthAtmosphere.png"); cloudTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthClouds.png"); dayTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthDay.jpg"); maskTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthMask.png"); nightTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthNight.png"); nightLightsTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthNightLights.png"); normalTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Earth/EarthNormal.jpg"); // Set initial state depthState = new DepthStencilState { DepthBufferEnable = true, DepthBufferWriteEnable = true, DepthBufferFunction = CompareFunction.LessEqual }; cloudBlendState = new BlendState() { ColorSourceBlend = Blend.SourceAlpha, AlphaSourceBlend = Blend.SourceAlpha, ColorDestinationBlend = Blend.One, AlphaDestinationBlend = Blend.One }; atmosphereBlendState = new BlendState() { ColorSourceBlend = Blend.SourceAlpha, AlphaSourceBlend = Blend.SourceAlpha, ColorDestinationBlend = Blend.One, AlphaDestinationBlend = Blend.One }; // Load Moon data Moon.LoadContent(); }
/// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load <SpriteFont>("Font"); sphere = new SpherePrimitive(GraphicsDevice); cylinder = new CylinderPrimitive(GraphicsDevice); faceEffect = new BasicEffect(GraphicsDevice); faceEffect.PreferPerPixelLighting = true; vertexEffect = new BasicEffect(GraphicsDevice); vertexEffect.EnableDefaultLighting(); vertexEffect.PreferPerPixelLighting = true; edgeEffect = new BasicEffect(GraphicsDevice); edgeEffect.EnableDefaultLighting(); edgeEffect.PreferPerPixelLighting = true; }
// Token: 0x0600424B RID: 16971 RVA: 0x00150DF8 File Offset: 0x0014F1F8 public void GenerateGeometry(float radius, int segments, float hemisphere, float innerRadius, float slice, NormalsType normalsType, PivotPosition pivotPosition) { MeshFilter component = base.GetComponent <MeshFilter>(); if (component.sharedMesh == null) { component.sharedMesh = new Mesh(); } Mesh sharedMesh = component.sharedMesh; base.GenerationTimeMS = SpherePrimitive.GenerateGeometry(sharedMesh, radius, segments, hemisphere, innerRadius, slice, normalsType, pivotPosition); this.radius = radius; this.segments = segments; this.hemisphere = hemisphere; this.normalsType = normalsType; this.flipNormals = false; this.innerRadius = innerRadius; this.slice = slice; this.pivotPosition = pivotPosition; }
/// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load the model. currentModel = Content.Load <Model>("dude"); // Look up our custom skinning information. skinningData = currentModel.Tag as SkinningData; if (skinningData == null) { throw new InvalidOperationException ("This model does not contain a SkinningData tag."); } boneTransforms = new Matrix[skinningData.BindPose.Count]; // Load the baseball bat model. baseballBat = Content.Load <Model>("baseballbat"); // Create an animation player, and start decoding an animation clip. animationPlayer = new AnimationPlayer(skinningData); AnimationClip clip = skinningData.AnimationClips["Take 001"]; animationPlayer.StartClip(clip); // Load the bounding spheres. skinnedSpheres = Content.Load <SkinnedSphere[]>("CollisionSpheres"); boundingSpheres = new BoundingSphere[skinnedSpheres.Length]; spherePrimitive = new SpherePrimitive(GraphicsDevice, 1, 12); // Create a new SpriteBatch, which can be used to draw textures. napis = new SpriteBatch(GraphicsDevice); Font1 = Content.Load <SpriteFont>("napis1"); this.port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived); port.Open(); }
/// <inheritdoc /> public override void Initialize() { Game.Background = Color.CornflowerBlue; Camera = new TargetCamera(GraphicsDevice.Viewport.AspectRatio, new Vector3(0, 20, 60), Vector3.Zero); Box = new CubePrimitive(GraphicsDevice, 10, Color.DarkCyan, Color.DarkMagenta, Color.DarkGreen, Color.MonoGameOrange, Color.Black, Color.DarkGray); BoxPosition = Vector3.Zero; Cylinder = new CylinderPrimitive(GraphicsDevice, 20, 10, 16); CylinderPosition = new Vector3(-20, 0, 0); Sphere = new SpherePrimitive(GraphicsDevice, 10); SpherePosition = new Vector3(0, -15, 0); Teapot = new TeapotPrimitive(GraphicsDevice, 10); TeapotPosition = new Vector3(20, 0, 0); Torus = new TorusPrimitive(GraphicsDevice, 10, 1, 16); TorusPosition = new Vector3(-20, 15, 0); Triangle = new TrianglePrimitive(GraphicsDevice, new Vector3(-10f, 10f, 0f), new Vector3(0f, 20f, 0f), new Vector3(10f, 10f, 0f), Color.Black, Color.Cyan, Color.Magenta); base.Initialize(); }
public override void LoadContent() { // Load mesh mesh = new SpherePrimitive(0.2f, 50); // Load effects moonVertexShader = VertexShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/MoonVS.vs", UriKind.Relative)).Stream); moonPixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/MoonPS.ps", UriKind.Relative)).Stream); // Load textures moonTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Moon/moon.jpg"); moonNormalTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Moon/moon_normal.jpg"); // Set initial state depthState = new DepthStencilState { DepthBufferEnable = true, DepthBufferWriteEnable = true, DepthBufferFunction = CompareFunction.LessEqual }; }
/// <inheritdoc /> protected override void LoadContent() { // We load the city meshes into a model Scene = Game.Content.Load <Model>(ContentFolder3D + "scene/city"); Sphere = new SpherePrimitive(GraphicsDevice, 100f, 16, Color.White); // Load the tank which will contain reflections Robot = Game.Content.Load <Model>(ContentFolder3D + "tgcito-classic/tgcito-classic"); // Load the shadowmap effect Effect = Game.Content.Load <Effect>(ContentFolderEffects + "EnvironmentMap"); BasicEffect = (BasicEffect)Robot.Meshes.FirstOrDefault().Effects[0]; // Assign the Environment map effect to our robot foreach (var modelMesh in Robot.Meshes) { foreach (var part in modelMesh.MeshParts) { part.Effect = Effect; } } DebugTextureEffect = Game.Content.Load <Effect>(ContentFolderEffects + "DebugTexture"); DebugTextureEffect.CurrentTechnique = DebugTextureEffect.Techniques["DebugCubeMap"]; // Create a full screen quad to debug the environment map FullScreenQuad = new FullScreenQuad(GraphicsDevice); QuadWorld = Matrix.CreateScale(new Vector3(0.9f, 0.2f, 0f)) * Matrix.CreateTranslation(Vector3.Down * 0.7f); // Create a render target for the scene EnvironmentMapRenderTarget = new RenderTargetCube(GraphicsDevice, EnvironmentmapSize, false, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.DiscardContents); GraphicsDevice.BlendState = BlendState.Opaque; base.LoadContent(); }
public GeometricObject() { rendering = false; initialized = false; primitives = new List <PrimitiveBase> (); ptp = new PointPrimitive(); primitives.Add(ptp); lp = new LinePrimitive(); primitives.Add(lp); pp = new PolygonPrimitive(); primitives.Add(pp); sp = new SpherePrimitive(); primitives.Add(sp); mp = new MeshPrimitive(); primitives.Add(mp); }
/// <summary> /// Creates a StaticModel from a GeometricPrimitive and specified dimensions. /// </summary> /// <param name="primitiveType">Type of primitive to create</param> /// <param name="height">Height of primitive, used by cubes and cylinders.</param> /// <param name="width">Width of primitive, used by cubes.</param> /// <param name="depth">Depth of primitive, used by cubes.</param> /// <param name="diameter">Diameter of primitive, used by cylinders, spheres, toruses, and teapots.</param> private void LoadModelFromPrimitive(GeometricPrimitiveType primitiveType, float height, float width, float depth, float diameter) { GeometricPrimitive primitive; switch (primitiveType) { case GeometricPrimitiveType.Box: primitive = new CubePrimitive(this.parentEntity.Game.GraphicsDevice, height, width, depth); break; case GeometricPrimitiveType.Sphere: primitive = new SpherePrimitive(this.parentEntity.Game.GraphicsDevice, diameter, 16); break; case GeometricPrimitiveType.Cylinder: primitive = new CylinderPrimitive(this.parentEntity.Game.GraphicsDevice, height, diameter, 16); break; case GeometricPrimitiveType.Cone: primitive = new ConePrimitive(this.parentEntity.Game.GraphicsDevice, height, diameter, 16); break; case GeometricPrimitiveType.Torus: primitive = new TorusPrimitive(this.parentEntity.Game.GraphicsDevice, diameter, 0.3333f, 16); break; case GeometricPrimitiveType.Teapot: primitive = new TeapotPrimitive(this.parentEntity.Game.GraphicsDevice, diameter, 8); break; default: throw new Exception("LoadPrimitive does not handle this type of GeometricPrimitive. Was a new primitive type made and not handled here?"); } if (null != primitive) { model = new StaticModel(primitive, this.parentEntity.Game.GraphicsDevice); } }
public override void LoadContent() { // Load mesh mesh = new SpherePrimitive(1.5f, 50); // Load effects sunVertexShader = VertexShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/SunVS.vs", UriKind.Relative)).Stream); sunPixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/SunPS.ps", UriKind.Relative)).Stream); refractionPixelShader = PixelShader.FromStream(GraphicsDeviceManager.Current.GraphicsDevice, Application.GetResourceStream(new Uri(@"/SLARToolKit3DSample;component/Shaders/RefractionPS.ps", UriKind.Relative)).Stream); // Load textures sunTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Sun/Sun.jpg"); gradientTexture = ContentManager.LoadBitmapAndMipFromResource("Textures/Sun/FireGradient.png"); turbulence1Texture = ContentManager.LoadBitmapAndMipFromResource("Textures/Sun/Turbulence1.png"); turbulence2Texture = ContentManager.LoadBitmapAndMipFromResource("Textures/Sun/Turbulence2.png"); depthState = new DepthStencilState { DepthBufferEnable = true, DepthBufferWriteEnable = true, DepthBufferFunction = CompareFunction.LessEqual }; }
void simDisplay1_OnInitialize(object sender, EventArgs e) { spritebatch = new SpriteBatch(GraphicsDevice); camera = new Camera(GraphicsDevice); sphere = new SpherePrimitive(GraphicsDevice, 2, 16); cube = new CubePrimitive(GraphicsDevice, 2); }
public static void CreatePrimitives(GameObject gameObject, ref Dictionary <Material, List <Primitive> > primitives) { if (primitives == null) { primitives = new Dictionary <Material, List <Primitive> >(); } MeshRenderer meshRenderer = gameObject.GetComponent <MeshRenderer>(); Primitive primitive = null; if (!meshRenderer || !meshRenderer.sharedMaterial) { return; } if (primitive == null) { BoxCollider boxCollider = gameObject.GetComponent <BoxCollider>(); if (boxCollider) { Vector3 scale = new Vector3(boxCollider.size.x * boxCollider.transform.lossyScale.x, boxCollider.size.y * boxCollider.transform.lossyScale.y, boxCollider.size.z * boxCollider.transform.lossyScale.z); if ((scale.x < 0.02f && scale.y >= 0.02f && scale.z >= 0.02f) || (scale.y < 0.02f && scale.z >= 0.02f && scale.x >= 0.02f) || (scale.z < 0.02f && scale.x >= 0.02f && scale.y >= 0.02f)) { primitive = new QuadPrimitive(boxCollider); } else { primitive = new CubePrimitive(boxCollider); } } } if (primitive == null) { SphereCollider sphereCollider = gameObject.GetComponent <SphereCollider>(); if (sphereCollider) { primitive = new SpherePrimitive(sphereCollider); } } if (primitive == null) { MeshFilter meshFilter = gameObject.GetComponent <MeshFilter>(); if (meshFilter && meshFilter.sharedMesh) { int[] triangles = meshFilter.sharedMesh.triangles; Vector3[] vertices = meshFilter.sharedMesh.vertices; Vector3[] normals = meshFilter.sharedMesh.normals; Matrix4x4 localToWorld = meshFilter.transform.localToWorldMatrix; for (int i = 0; i < triangles.Length; i += 3) { Vector3 vertex0 = localToWorld.MultiplyPoint(vertices[triangles[i]]); Vector3 vertex1 = localToWorld.MultiplyPoint(vertices[triangles[i + 1]]); Vector3 vertex2 = localToWorld.MultiplyPoint(vertices[triangles[i + 2]]); Vector3 normal0 = localToWorld.MultiplyVector(normals[triangles[i]]); Vector3 normal1 = localToWorld.MultiplyVector(normals[triangles[i + 1]]); Vector3 normal2 = localToWorld.MultiplyVector(normals[triangles[i + 2]]); Primitive trianglePrimitive = new TrianglePrimitive(vertex0, vertex1, vertex2, normal0, normal1, normal2); if (primitives.ContainsKey(meshRenderer.sharedMaterial) == false) { primitives.Add(meshRenderer.sharedMaterial, new List <Primitive>()); } primitives[meshRenderer.sharedMaterial].Add(trianglePrimitive); } } } else { if (primitives.ContainsKey(meshRenderer.sharedMaterial) == false) { primitives.Add(meshRenderer.sharedMaterial, new List <Primitive>()); } primitives[meshRenderer.sharedMaterial].Add(primitive); } }
protected override void LoadContent() { Simulation = Simulation.Create(BufferPool, new NarrowPhaseCallbacks(), new PoseIntegratorCallbacks(new NumericVector3(0, -10, 0)), new PositionFirstTimestepper()); SphereHandles = new List <BodyHandle>(); ActiveBoxesWorld = new List <Matrix>(); InactiveBoxesWorld = new List <Matrix>(); SpheresWorld = new List <Matrix>(); Random = new Random(); BoxHandles = new List <BodyHandle>(800); Radii = new List <float>(); var boxShape = new Box(1, 1, 1); boxShape.ComputeInertia(1, out var boxInertia); var boxIndex = Simulation.Shapes.Add(boxShape); const int pyramidCount = 40; for (var pyramidIndex = 0; pyramidIndex < pyramidCount; ++pyramidIndex) { const int rowCount = 20; for (var rowIndex = 0; rowIndex < rowCount; ++rowIndex) { var columnCount = rowCount - rowIndex; for (var columnIndex = 0; columnIndex < columnCount; ++columnIndex) { var bh = Simulation.Bodies.Add(BodyDescription.CreateDynamic( new NumericVector3((-columnCount * 0.5f + columnIndex) * boxShape.Width, (rowIndex + 0.5f) * boxShape.Height, (pyramidIndex - pyramidCount * 0.5f) * (boxShape.Length + 4)), boxInertia, new CollidableDescription(boxIndex, 0.1f), new BodyActivityDescription(0.01f))); BoxHandles.Add(bh); } } } //Prevent the boxes from falling into the void. Simulation.Statics.Add(new StaticDescription(new NumericVector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2500, 1, 2500)), 0.1f))); cubePrimitive = new CubePrimitive(GraphicsDevice, 1f, Color.White); spherePrimitive = new SpherePrimitive(GraphicsDevice); var count = BoxHandles.Count; GraphicsDevice.DepthStencilState = DepthStencilState.Default; for (var index = 0; index < count; index++) { var bodyHandle = BoxHandles[index]; var bodyReference = Simulation.Bodies.GetBodyReference(bodyHandle); var position = bodyReference.Pose.Position; var quaternion = bodyReference.Pose.Orientation; var world = Matrix.CreateFromQuaternion(new Quaternion(quaternion.X, quaternion.Y, quaternion.Z, quaternion.W)) * Matrix.CreateTranslation(new Vector3(position.X, position.Y, position.Z)); cubePrimitive.Draw(world, Camera.View, Camera.Projection); } base.LoadContent(); }
/// <inheritdoc /> protected override void LoadContent() { Random = new Random(5); SpriteFont = Game.Content.Load <SpriteFont>(ContentFolderSpriteFonts + "Arial"); //The buffer pool is a source of raw memory blobs for the engine to use. BufferPool = new BufferPool(); Radii = new List <float>(); Camera = new SimpleCamera(GraphicsDevice.Viewport.AspectRatio, new Vector3(40, 60, 150), 55, 0.4f); var boxTexture = Game.Content.Load <Texture2D>(ContentFolderTextures + "wood/caja-madera-3"); Box = new BoxPrimitive(GraphicsDevice, Vector3.One * 10, boxTexture); Sphere = new SpherePrimitive(GraphicsDevice); SphereHandles = new List <BodyHandle>(); BoxHandles = new List <BodyHandle>(); var targetThreadCount = Math.Max(1, Environment.ProcessorCount > 4 ? Environment.ProcessorCount - 2 : Environment.ProcessorCount - 1); ThreadDispatcher = new SimpleThreadDispatcher(targetThreadCount); // This are meshes/model/primitives collections to render // The PositionFirstTimestepper is the simplest timestepping mode, but since it integrates velocity into position at the start of the frame, directly modified velocities outside of the timestep // will be integrated before collision detection or the solver has a chance to intervene. That's fine in this demo. Other built-in options include the PositionLastTimestepper and the SubsteppingTimestepper. // Note that the timestepper also has callbacks that you can use for executing logic between processing stages, like BeforeCollisionDetection. Simulation = Simulation.Create(BufferPool, new NarrowPhaseCallbacks(), new PoseIntegratorCallbacks(new NumericVector3(0, -100, 0)), new PositionFirstTimestepper()); // Creates a floor var floorTexture = Game.Content.Load <Texture2D>(ContentFolderTextures + "floor/adoquin-2"); //Floor = new QuadPrimitive(GraphicsDevice); TilingEffect = Game.Content.Load <Effect>(ContentFolderEffects + "TextureTiling"); TilingEffect.Parameters["Texture"].SetValue(floorTexture); TilingEffect.Parameters["Tiling"].SetValue(Vector2.One * 50f); FloorWorld = Matrix.CreateScale(400f) * Matrix.CreateTranslation(new Vector3(75, 0, -150)); Simulation.Statics.Add(new StaticDescription(new NumericVector3(0, -0.5f, 0), new CollidableDescription(Simulation.Shapes.Add(new Box(2000, 1, 2000)), 0.1f))); BoxesWorld = new List <Matrix>(); SpheresWorld = new List <Matrix>(); // Single Box var radius = 10; for (var j = 0; j < 5; j++) { for (var i = 0; i < 20; i++) { var boxShape = new Box(radius, radius, radius); boxShape.ComputeInertia(0.4f, out var boxInertia); var boxIndex = Simulation.Shapes.Add(boxShape); var position = new NumericVector3(-30 + i * 10 + 1, j * 10 + 1, -40); var bodyDescription = BodyDescription.CreateDynamic(position, boxInertia, new CollidableDescription(boxIndex, 0.1f), new BodyActivityDescription(0.01f)); var bodyHandle = Simulation.Bodies.Add(bodyDescription); BoxHandles.Add(bodyHandle); } } base.LoadContent(); }
public Dna(GraphicsDevice graphicsDevice) { sphere = new SpherePrimitive(graphicsDevice, 20, 10); }
public Sphere(GraphicsDevice graphics, float radius, int tellselation, Color baseColor) { primitive = new SpherePrimitive(graphics, radius * 2f, tellselation, baseColor); Radius = radius; Color = baseColor; }