protected override void CreateScene() { RenderManager.BackgroundColor = Color.Black; RenderManager.DebugLines = true; FreeCamera camera = new FreeCamera("MainCamera", new Vector3(0, 4, 12), new Vector3(0, 4, 0)); camera.Speed = 5.0f; EntityManager.Add(camera); RenderManager.SetActiveCamera(camera.Entity); DirectionalLight skylight = new DirectionalLight("SkyLight", new Vector3(1)); EntityManager.Add(skylight); float value = 0.0f; Color c = new Color(value, value, value, 1); Entity cubeModel = new Entity("Sphere") .AddComponent(new Spinner() { AxisTotalIncreases = new Vector3(0.3f, 0.5f,0.4f) }) .AddComponent(new Transform3D() { Scale = new Vector3(6) }) .AddComponent(Model.CreateSphere()) .AddComponent(new MaterialsMap(new EnvironmentMapMaterial("Content/tile1.wpk", "Content/Sky.wpk") {LightingEnabled = true})) .AddComponent(new ModelRenderer()); EntityManager.Add(cubeModel); }
public Environment AddLight(DirectionalLight light) { if (_lights.Count > MaximumNumberOfLights) throw new NotSupportedException(String.Format("A maximum of {0} environment lights are supported.", MaximumNumberOfLights)); _lights.Add(light); return this; }
/// Computes the diffuse and specular components of the Phong /// reflection model for a directional light. public override Color ComputeDirectionalLight( DirectionalLight dL, Object3D obj, V3 p, V2 uv ) { V3 incidentVec = -dL.Direction; return ComputeDiffuseSpecular(dL, obj, p, uv, incidentVec); }
public void SetDirLights(DirectionalLight[] lights) { System.Diagnostics.Debug.Assert(lights.Length <= 3, "BasicEffect only supports up to 3 lights"); var array = new List<byte>(); foreach (var light in lights) { var d = Util.GetArray(light); array.AddRange(d); } _dirLights.SetRawValue(new DataStream(array.ToArray(), false, false), array.Count); }
public void SetDirLights(DirectionalLight[] lights) { System.Diagnostics.Debug.Assert(lights.Length <= MaxLights, "BasicEffect only supports up to 3 lights"); for (int i = 0; i < lights.Length && i < MaxLights; i++) { var light = lights[i]; var d = Util.GetArray(light); Array.Copy(d, 0, _dirLightsArray, i * DirectionalLight.Stride, DirectionalLight.Stride); } _dirLights.SetRawValue(new DataStream(_dirLightsArray, false, false), _dirLightsArray.Length); }
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); DefaultFont = Content.Load<SpriteFont>("DefaultFont"); Scene.Objects.Add(new SkySphere(this)); //Scene.Objects.Add(new Terrain(this, Content.Load<Texture2D>("Map"))); //Scene.Objects.Add(new Water(this, Scene.Objects, Vector3.Zero, new Vector2(40000, 40000))); Scene.Objects.Add(new ComplexModel(this, "Models/Plane", Vector3.Down, Vector3.Zero, new Vector3(1000), Materials.Grass)); //Scene.Objects.Add(teaPot = new ComplexModel(this, "Models/Car", Vector3.Zero, Vector3.Zero, new Vector3(10))); Scene.Objects.Add(mia = new AnimatedModel(this, "Models/Characters/Mia/Mia", Vector3.Zero, Vector3.Zero, Vector3.One)); //Scene.Objects.Add(dude = new ComplexModel(this, "Models/Characters/Dude", Vector3.Zero, Vector3.Zero, Vector3.One)); Scene.Lights.Add(sunLight = new DirectionalLight(Color.White, 1, new Vector3(-1, -1, 0))); }
public void Execute(ref WooState state) { Vector3 colourVec = _ColourExpr.EvaluateVector(ref state); Colour colour = new Colour(colourVec.x, colourVec.y, colourVec.z); Vector3 direction = _DirectionExpr.EvaluateVector(ref state); double area = _AreaExpr.EvaluateFloat(ref state); if (area < 0) area = 0; if (area > 0.99) area = 0.99; double samples = _SamplesExpr.EvaluateFloat(ref state); if (samples < 1) samples = 1; DirectionalLight directionalLight = new DirectionalLight(colour, direction, (float)area, (int)samples); directionalLight.CreateElement(state._Parent, new Vector3(0,0,0)); }
public DirectionalLight( EffectParameter directionParameter, EffectParameter diffuseColorParameter, EffectParameter specularColorParameter, DirectionalLight cloneSource ) { this.diffuseColorParameter = diffuseColorParameter; this.directionParameter = directionParameter; this.specularColorParameter = specularColorParameter; if (cloneSource != null) { DiffuseColor = cloneSource.DiffuseColor; Direction = cloneSource.Direction; SpecularColor = cloneSource.SpecularColor; Enabled = cloneSource.Enabled; } }
protected override void CreateScene() { ViewCamera camera = new ViewCamera("MainCamera", new Vector3(0, 2, 4), Vector3.Zero); camera.BackgroundColor = Color.Black; EntityManager.Add(camera.Entity); DirectionalLight skylight = new DirectionalLight("SkyLight", new Vector3(1)); EntityManager.Add(skylight); Entity primitive = new Entity("Primitive") .AddComponent(new Transform3D()) .AddComponent(new BoxCollider()) .AddComponent(new Spinner() { AxisTotalIncreases = new Vector3(1f, 1f, 1f) }) .AddComponent(Model.CreateCube()) .AddComponent(new MaterialsMap(new BasicMaterial((WaveServices.ScreenContextManager.CurrentContext[0] as MyScene).SmallTarget) { LightingEnabled = true })) .AddComponent(new ModelRenderer()); EntityManager.Add(primitive); }
/// <summary> /// This should get called the first time the stage scene is put /// into an active scene tree. So returning from the editor /// might be safe without it unloading this. /// </summary> public override void _Ready() { world = GetNode <Node>("World"); HUD = GetNode <MicrobeHUD>("MicrobeHUD"); rootOfDynamicallySpawned = GetNode <Node>("World/DynamicallySpawned"); spawner = new SpawnSystem(rootOfDynamicallySpawned); Camera = world.GetNode <MicrobeCamera>("PrimaryCamera"); Clouds = world.GetNode <CompoundCloudSystem>("CompoundClouds"); worldLight = world.GetNode <DirectionalLight>("WorldLight"); TimedLifeSystem = new TimedLifeSystem(rootOfDynamicallySpawned); ProcessSystem = new ProcessSystem(rootOfDynamicallySpawned); microbeAISystem = new MicrobeAISystem(rootOfDynamicallySpawned); FluidSystem = new FluidSystem(rootOfDynamicallySpawned); HUD.Init(this); // Do stage setup to spawn things and setup all parts of the stage SetupStage(); }
public void LoadPreview3D() { PointCloudTileSource tileSource = CurrentTileSource; Jacere.Core.Geometry.Extent3D extent = tileSource.Extent; Model3DGroup modelGroup = new Model3DGroup(); Model3DGroup modelSubGroup = new Model3DGroup(); modelGroup.Children.Add(modelSubGroup); DirectionalLight lightSource = new DirectionalLight(System.Windows.Media.Colors.White, new Vector3D(-1, -1, -1)); modelGroup.Children.Add(lightSource); ModelVisual3D model = new ModelVisual3D(); model.Content = modelGroup; Jacere.Core.Geometry.Point3D centerOfMass = tileSource.CenterOfMass; Point3D lookatPoint = new Point3D(0, 0, 0); Point3D cameraPoint = new Point3D(0, extent.MinY - centerOfMass.Y, centerOfMass.Z - extent.MinZ + extent.RangeX); Vector3D lookDirection = lookatPoint - cameraPoint; lookDirection.Normalize(); PerspectiveCamera camera = new PerspectiveCamera(); camera.Position = cameraPoint; camera.LookDirection = lookDirection; camera.UpDirection = new Vector3D(0, 0, 1); camera.FieldOfView = 70; RenderOptions.SetEdgeMode(viewport, EdgeMode.Aliased); //viewport.ClipToBounds = false; //viewport.IsHitTestVisible = false; viewport.Camera = camera; viewport.Children.Add(model); m_backgroundWorker.RunWorkerAsync(CurrentTileSource); }
private void UpdateDirectionalLight() { if (_directionalLight == null) { _directionalLight = new DirectionalLight(); var modelVisual3D = new ModelVisual3D(); modelVisual3D.Content = _directionalLight; this.Children.Add(modelVisual3D); } var parentViewport3DCamera = this.ParentViewport3D.Camera; var projectionCamera = parentViewport3DCamera as ProjectionCamera; if (projectionCamera != null) // MatrixCamera is currently not supported { _directionalLight.Direction = projectionCamera.LookDirection; } // Update currently subscribed camera if changed var currentCamera = this.Camera; if (!ReferenceEquals(parentViewport3DCamera, currentCamera)) { if (currentCamera != null && !currentCamera.IsFrozen) { currentCamera.Changed -= OnCameraChanged; } if (parentViewport3DCamera != null && !parentViewport3DCamera.IsFrozen) { parentViewport3DCamera.Changed += OnCameraChanged; } this.Camera = parentViewport3DCamera; } }
/// <summary> /// /// </summary> /// <param name="control"></param> public override void Load(Control control) { base.Load(control); camera = new OrthographicCamera(control.Width / -2, control.Width / 2, control.Height / 2, control.Height / -2, -500, 1000); scene = new Scene(); var light = new DirectionalLight(Color.White, 1); light.Position = new Vector3(1, 1, 1).Normalize(); scene.Add(light); var geometry = new BoxGeometry(20, 20, 20); for (var i = 0; i < 2000; i++) { var object3D = new Mesh(geometry, new MeshLambertMaterial() { Color = new Color().Random() }); object3D.Position.X = Mat.Random() * 800 - 400; object3D.Position.Y = Mat.Random() * 800 - 400; object3D.Position.Z = Mat.Random() * 800 - 400; object3D.Rotation.X = Mat.Random() * 2 * (float)System.Math.PI; object3D.Rotation.Y = Mat.Random() * 2 * (float)System.Math.PI; object3D.Rotation.Z = Mat.Random() * 2 * (float)System.Math.PI; object3D.Scale.X = Mat.Random() + 0.5f; object3D.Scale.Y = Mat.Random() + 0.5f; object3D.Scale.Z = Mat.Random() + 0.5f; scene.Add(object3D); } raycaster = new Raycaster(); renderer.SetClearColor((Color)colorConvertor.ConvertFromString("#f0f0f0")); renderer.SortObjects = false; }
public PlanarShadows() { InitializeComponent(); //var bitmapImage = new BitmapImage(new Uri("pack://application:,,,/Resources/10x10-texture.png")); //GroundPlane.Material = new DiffuseMaterial(new ImageBrush(bitmapImage)); _solidShadowMaterial = new DiffuseMaterial(Brushes.Black); _transparentShadowMaterial = new DiffuseMaterial(new SolidColorBrush(System.Windows.Media.Color.FromArgb(180, 0, 0, 0))); _loadedModel3D = LoadModel(); MainViewport.Children.Add(_loadedModel3D.CreateModelVisual3D()); // Create PlanarShadowMeshCreator // If your model is very complex, then it is recommended to use a simplified 3D model for shadow generation _planarShadowMeshCreator = new PlanarShadowMeshCreator(_loadedModel3D); _planarShadowMeshCreator.SetPlane(GroundPlane.CenterPosition, GroundPlane.Normal, GroundPlane.HeightDirection, GroundPlane.Size); _lightHorizontalAngle = -25; _lightVerticalAngle = 22; _lightDistance = 500; _shadowPointLight = new PointLight(); _shadowDirectionalLight = new DirectionalLight(); Camera1.ShowCameraLight = ShowCameraLightType.Never; SetShadowLight(isDirectionalLight: true); UpdateLights(); UpdateShadowModel(); this.PreviewKeyDown += OnPreviewKeyDown; // This will allow receiving keyboard events this.Focusable = true; this.Focus(); }
private void FormMain_Load(object sender, EventArgs e) { var position = new vec3(0, 5, 4); var center = new vec3(0, 0, 0); var up = new vec3(0, 1, 0); var camera = new Camera(position, center, up, CameraType.Perspecitive, this.winGLCanvas1.Width, this.winGLCanvas1.Height); this.scene = new Scene(camera); this.scene.ClearColor = new vec4(0, 0, 0, 1); var light = new DirectionalLight(new vec3(4, 5, 3)); light.Specular = new vec3(0); this.scene.Lights.Add(light); this.scene.RootNode = GetRootNode(this.modelCamera); var list = new ActionList(); list.Add(new TransformAction(scene.RootNode)); list.Add(new RenderAction(scene)); list.Add(new BlinnPhongAction(scene)); this.actionList = list; //var manipulater = new FirstPerspectiveManipulater(); //manipulater.Bind(camera, this.winGLCanvas1); // rotate this scene. { var manipulater = new ArcBallManipulater(GLMouseButtons.Left); manipulater.Bind(camera, this.winGLCanvas1); manipulater.Rotated += thisManipulater_Rotated; } // model manipulater also affects teapot in this scene's rtt node. { var manipulater = this.modelManipulater; manipulater.Rotated += manipulater_Rotated; manipulater.MouseDown += manipulater_MouseDown; manipulater.Rotated += manipulater_MouseMove; manipulater.MouseUp += manipulater_MouseUp; this.modelCanvas.MouseMove += modelCanvas_MouseMove; } }
/// <summary> /// Creates the configuration controls of this component. /// </summary> public static void AddControls(DirectionalLight directionalLight, ClipControl owner) { // Enabled CheckBox enabled = CommonControls.CheckBox("Enabled", owner, directionalLight.Enabled, directionalLight, "Enabled"); enabled.Top = 10; // Intensity var intensity = CommonControls.SliderNumericFloat("Intensity", owner, directionalLight.Intensity, false, true, 0, 100, directionalLight, "Intensity"); // Diffuse Color var diffuseColor = CommonControls.SliderColor("Color", owner, directionalLight.Color, directionalLight, "Color"); // Shadow var shadow = CommonControls.AssetSelector<Shadow>("Shadow", owner, directionalLight, "Shadow"); // Enabled enabled.CheckedChanged += delegate { intensity.Enabled = directionalLight.Enabled; diffuseColor.Enabled = directionalLight.Enabled; shadow.Enabled = directionalLight.Enabled; }; owner.AdjustHeightFromChildren(); } // AddControls
protected override void CreateScene() { RenderManager.BackgroundColor = Color.CornflowerBlue; FreeCamera camera = new FreeCamera("MainCamera", new Vector3(0, 20, 30), Vector3.Zero); EntityManager.Add(camera.Entity); DirectionalLight skylight = new DirectionalLight("SkyLight", new Vector3(1)); EntityManager.Add(skylight); Entity sphere = new Entity("Sphere") .AddComponent(new Transform3D() { Scale = new Vector3(10f) }) .AddComponent(new Spinner() { AxisTotalIncreases = new Vector3(0, 1, 0) }) .AddComponent(new BoxCollider()) .AddComponent(Model.CreateSphere()) .AddComponent(new MaterialsMap(new BasicMaterial("Content/tile1.wpk") { LightingEnabled = true })) .AddComponent(new ModelRenderer()); EntityManager.Add(sphere); }
double keyDeltaFactor = 4; // determine the angle delta when the ddirection key pressed public MainWindow() { InitializeComponent(); WavefrontObjLoader wfl = new WavefrontObjLoader(); slider1.ValueChanged += new RoutedPropertyChangedEventHandler <double>(slider1_ValueChanged); slider2.ValueChanged += new RoutedPropertyChangedEventHandler <double>(slider1_ValueChanged); slider3.ValueChanged += new RoutedPropertyChangedEventHandler <double>(slider1_ValueChanged); // Specify where in the 3D scene the camera is. camera.Position = new Point3D(0, 0, 0); // Specify the direction that the camera is pointing. camera.LookDirection = new Vector3D(0, 0, -1); // Define camera's horizontal field of view in degrees. camera.FieldOfView = 1000; // Asign the camera to the viewport vp.Camera = camera; Model3DGroup myModel3DGroup = new Model3DGroup(); DirectionalLight myDirectionalLight = new DirectionalLight(); myDirectionalLight.Color = Colors.White; myDirectionalLight.Direction = new Vector3D(-0.61, -0.5, -0.61); myModel3DGroup.Children.Add(myDirectionalLight); var m = wfl.LoadObjFile(@"F:\MeshedReconstruction.obj"); m.Content = myModel3DGroup; vp.Children.Add(m); camera.UpDirection.Normalize(); this.MouseMove += Viewport3D_MouseMove; this.MouseLeftButtonDown += Viewport3D_MouseLeftButtonDown; this.MouseWheel += Viewport3D_MouseWheel; this.KeyDown += Window_KeyDown; }
protected override void render() { if (material == null) { return; } material.Bind(); if (EngineBase.Renderer.ShadowFrameBuffer.TextureHandle > 0) { GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, EngineBase.Renderer.ShadowFrameBuffer.TextureHandle); material.SetUniform("shadowMap", 0); material.SetUniform("shadowViewProjection", Matrix4.Mult(shadowViewProjection, EngineBase.Renderer.ShadowMapBias)); } Matrix4 mv = Matrix4.Mult(transformation, EngineBase.Renderer.View); Matrix4 nm = Matrix4.Invert(mv); nm.Transpose(); material.SetUniform("normalMatrix", nm); material.SetUniform("model", transformation); material.SetUniform("modelView", mv); material.SetUniform("modelViewProjection", Matrix4.Mult(mv, EngineBase.Renderer.Projection)); if (light == null) { light = (DirectionalLight)EngineBase.Scene.GetLight(0); } material.SetUniform("lightDirection", light.Direction); material.SetUniform("color", ref color); material.SetUniform("time", Time); GL.BindVertexArray(vaoHandle); GL.DrawElements(PrimitiveType.Triangles, indicesVboData.Length, DrawElementsType.UnsignedInt, IntPtr.Zero); GL.BindVertexArray(0); material.Unbind(); }
/// <summary> /// Initializes a new instance of the <see cref="AssetPreview"/> class. /// </summary> /// <param name="useWidgets">if set to <c>true</c> use widgets.</param> public AssetPreview(bool useWidgets) : base(RenderTask.Create <SceneRenderTask>(), new ArcBallCamera(Vector3.Zero, 50), useWidgets) { DockStyle = DockStyle.Fill; Task.Flags = ViewFlags.DefaulAssetPreview; Task.AllowGlobalCustomPostFx = false; ((ArcBallCamera)ViewportCamera).SetView(new Quaternion(0.424461186f, -0.0940724313f, 0.0443938486f, 0.899451137f)); // Setup preview scene PreviewLight = DirectionalLight.New(); PreviewLight.Brightness = 6.0f; PreviewLight.ShadowsMode = ShadowsCastingMode.None; PreviewLight.Orientation = Quaternion.Euler(new Vector3(52.1477f, -109.109f, -111.739f)); // EnvProbe = EnvironmentProbe.New(); EnvProbe.AutoUpdate = false; EnvProbe.CustomProbe = FlaxEngine.Content.LoadAsyncInternal <CubeTexture>(EditorAssets.DefaultSkyCubeTexture); // Sky = Sky.New(); Sky.SunLight = PreviewLight; Sky.SunPower = 8.0f; // SkyLight = SkyLight.New(); SkyLight.Mode = SkyLight.Modes.CustomTexture; SkyLight.Brightness = 2.0f; SkyLight.CustomTexture = EnvProbe.CustomProbe; // PostFxVolume = PostFxVolume.New(); PostFxVolume.IsBounded = false; PostFxVolume.Settings.Eye_MinLuminance = 0.1f; // Link actors for rendering Task.ActorsSource = ActorsSources.CustomActors; Task.CustomActors.Add(PreviewLight); Task.CustomActors.Add(EnvProbe); Task.CustomActors.Add(Sky); Task.CustomActors.Add(SkyLight); Task.CustomActors.Add(PostFxVolume); }
private SceneGraph CreateSceneGraph() { var sceneGraph = new SceneGraph(); _dirLight = new DirectionalLight(sceneGraph, intensity: new Vec3(1f), direction: new Vec3(0.7f, 1f, -0.7f), maxShadowDepth: 200f); _camera = new Camera(sceneGraph, position: new Vec3(0f, 10f, 10f), target: new Vec3(0f, 10f, -1f), upDirection: new Vec3(0f, 1f, 0f), frustum: new ViewingFrustum(FrustumKind.Perspective, 1f, 1f, -1f, -400f), aspectRatio: 1f); sceneGraph.GlobalLighting = new GlobalLighting() { AmbientLightIntensity = new Vec3(0.1f), MaxIntensity = 1f, GammaCorrection = 1.8f, }; _terrainScene = new Terrain.Scene(sceneGraph); var fighterGeometry = new FighterGeometry <EntityVertex, PathNode> (); _fighter = new Mesh <EntityVertex> (sceneGraph, fighterGeometry.Fighter.RotateY(0f).Compact()) .OffsetOrientAndScale(new Vec3(0f, 15f, -10f), new Vec3(0f, 0f, 0f), new Vec3(1f)); _infoWindow = new ControlPanel <TexturedVertex> (sceneGraph, Container.Vertical(true, false, Label.Static("Options", FontStyle.Bold), new ListView(React.Ignore <IVisualizable> (), new Visualizable(() => Visual.Label(string.Format("FPS: {0}", _fps))), new Visualizable(() => Visual.Label( string.Format("Mouse: {0}", new Vec2i(Mouse.X, Mouse.Y)))))), new Vec2i(180, 64), false); sceneGraph.Root.Add(_dirLight, _camera, _terrainScene.Root, _fighter, _infoWindow.Offset(new Vec3(-0.95f, 0.95f, 0f))); return(sceneGraph); }
private void InitStageLightListBox() { for (int groupIndex = 1; groupIndex < 17; groupIndex++) { TreeNode[] children = new TreeNode[4]; for (int lightIndex = 0; lightIndex < 4; lightIndex++) { DirectionalLight currentLight = Runtime.lightSetParam.stageDiffuseLights[((groupIndex) * 4) + lightIndex]; children[lightIndex] = new TreeNode(lightIndex.ToString()) { Tag = currentLight }; children[lightIndex].Checked = currentLight.enabled; } string name = GetGroupAndColorName(groupIndex - 1); TreeNode parent = new TreeNode(name, children); stageLightSetTreeView.Nodes.Add(parent); } }
private void setupKinect() { s = 4; points = new GeometryModel3D[320 * 240]; DirLight1 = new DirectionalLight(); DirLight1.Color = Colors.White; DirLight1.Direction = new Vector3D(1, 1, 1); Camera1 = new PerspectiveCamera(); Camera1.FarPlaneDistance = 8000; Camera1.NearPlaneDistance = 100; Camera1.FieldOfView = 10; Camera1.Position = new Point3D(160, 120, -1000); Camera1.LookDirection = new Vector3D(0, 0, 1); Camera1.UpDirection = new Vector3D(0, -1, 0); }
public void Reset() { _modelGroup.Children.Clear(); _models.Clear(); _cropModels.Clear(); DirectionalLight DirLight1 = new DirectionalLight(); DirLight1.Color = Colors.White; DirLight1.Direction = new Vector3D(-1, -1, -1); DirectionalLight DirLight2 = new DirectionalLight(); DirLight2.Color = Colors.White; DirLight2.Direction = new Vector3D(1, 1, 1); _modelGroup.Children.Add(DirLight1); _modelGroup.Children.Add(DirLight2); _vertexCount = 0; }
public void DirectionalLight() { this.Name = "Elements_DirectionalLight"; // <directional_example> // Create a directional light. var origin = new Vector3(10, 10, 10); var light = new DirectionalLight(Colors.White, new Transform(origin, origin.Unitized()), 1.0); var sunMaterial = new Material("Sun", Colors.Yellow, unlit: true); // Create a model curve to visualize the light direction. var dirCurve = new ModelCurve(new Line(light.Transform.Origin, light.Transform.Origin + light.Transform.ZAxis.Negate() * 10), sunMaterial); var floor = new Floor(Polygon.Rectangle(20, 20), 0.1); var column = new Column(new Vector3(5, 5), 5.0, Polygon.Rectangle(0.2, 0.2)); var mass = new Mass(Polygon.Rectangle(1, 1), 1.0, sunMaterial, new Transform(light.Transform.Origin)); // </directional_example> this.Model.AddElements(light, dirCurve, floor, column, mass); }
private void HandleKeyPressEvent(object sender, KeyEventArgs e) { Key[] viewCheck = new Key[] { Key.W, Key.Q, Key.Z, Key.X, Key.R }; if (Array.Exists(viewCheck, element => element == e.Key)) { // Adjust camera PerspectiveCamera newPCamera = myViewport3D.Camera as PerspectiveCamera; if (e.Key == Key.Q) { cameraPhi -= 10.0 * (Math.PI / 180.0); } if (e.Key == Key.W) { cameraPhi += 10.0 * (Math.PI / 180.0); } if (e.Key == Key.Z) { cameraRadius -= 100.0; } if (e.Key == Key.X) { cameraRadius += 100.0; } if (e.Key == Key.R) { cameraRadius = 1000.0; cameraPhi = 0.0; } double cameraX = cv.x + cameraRadius * Math.Sin(cameraTheta) * Math.Cos(cameraPhi - Math.PI / 2.0); double cameraY = cv.y + cameraRadius * Math.Sin(cameraTheta) * Math.Sin(cameraPhi - Math.PI / 2.0); double cameraZ = cv.z + (cameraRadius * Math.Cos(cameraTheta)); newPCamera.Position = new Point3D(cameraX, cameraY, cameraZ); newPCamera.LookDirection = new Vector3D(cv.x - cameraX, cv.y - cameraY, cv.z - cameraZ); newPCamera.UpDirection = new Vector3D(0.0, 0.0, 1.0); myViewport3D.Camera = newPCamera; // Update directional light source (points from camera to origin) DirectionalLight newDirLight = ((myViewport3D.Children[0] as ModelVisual3D).Content as Model3DGroup).Children[0] as DirectionalLight; newDirLight.Direction = newPCamera.LookDirection; ((myViewport3D.Children[0] as ModelVisual3D).Content as Model3DGroup).Children[0] = newDirLight; } }
protected override void InitializeInner() { base.InitializeInner(); DeviceContextHolder.Set <IMaterialsFactory>(new MaterialsProviderDeferred()); Scene.Add(SkyObject.Create(500f)); foreach (var showroom in _kn5.Skip(1)) { Scene.Add(new Kn5RenderableFile(showroom, Matrix.Identity)); } if (_kn5.Length > 1) { _car = new DeferredRenderableCar(CarDescription.FromKn5(_kn5[0]), Matrix.Identity, shadowsHeight: 0.001f, lights: Lights) { IsReflectable = false }; Scene.Add(_car); } Scene.UpdateBoundingBox(); Camera = new CameraOrbit(32) { Alpha = 0.9f, Beta = 0.1f, Radius = _car?.BoundingBox?.GetSize().Length() * 1.2f ?? 4.8f, Target = (_car?.BoundingBox?.GetCenter() ?? Vector3.Zero) - new Vector3(0f, 0.05f, 0f) }; _resetCamera = (CameraOrbit)Camera.Clone(); Sun = new DirectionalLight { Color = FixLight(new Vector3(1.2f, 1.0f, 0.9f)) * 5f, Direction = Vector3.Normalize(new Vector3(-1.2f, -3.4f, -2.2f)) }; _effect = DeviceContextHolder.GetEffect <EffectDeferredGObject>(); }
public Level(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { m_transform = Matrix4.Identity; m_timeMachine = new TimeMachine(); m_tileMap = new TileMap(this, minX, minY, minZ, maxX, maxY, maxZ); m_entities = new List <Entity>(); m_entityCollection = new EntityCollection(this); m_info = new LevelInfo(); m_depthComparer = new EntityDistanceComparer(); m_depthSortedEntities = new List <Entity>(); m_ambientLight = new AmbientLight(new Vector3(0.5f, 0.5f, 0.5f)); m_ambientLight.Active = true; m_skyLight = new DirectionalLight(new Vector3(0.6f, -1.0f, -0.6f), new Vector3(0.5f, 0.5f, 0.5f)); m_skyLight.Active = true; m_skyLight2 = new DirectionalLight(-Vector3.UnitY, Vector3.Zero); m_skyLight2.Active = false; m_pointLights = new List <PointLight>(); m_lightCollection = new LightCollection(this); m_telepadDirectory = new TelepadDirectory(); m_hintDirectory = new HintDirectory(); Visible = true; Random = new Random(); m_flatOpaqueEffect = new FlatEffectInstance(); m_flatCutoutEffect = new FlatCutoutEffectInstance(); m_litOpaqueEffect = new LitEffectInstance(RenderPass.Opaque); m_litCutoutEffect = new LitEffectInstance(RenderPass.Cutout); m_litTranslucentEffect = new LitEffectInstance(RenderPass.Translucent); m_shadowEffect = new ShadowEffectInstance(); m_particles = new ParticleManager(this); }
private ModelVisual3D CreateContainerWorld() { ModelVisual3D modelVisual3D = new ModelVisual3D(); Model3DGroup model3Dgroup = new Model3DGroup(); modelVisual3D.Content = (Model3D)model3Dgroup; Model3DCollection model3Dcollection = new Model3DCollection(); model3Dgroup.Children = model3Dcollection; Color.FromScRgb(1f, 1f, 1f, 1f); Color color = Color.FromScRgb(1f, 0.5f, 0.5f, 0.5f); Vector3D direction = new Vector3D(1.0, -1.0, -1.0); direction.Normalize(); DirectionalLight directionalLight = new DirectionalLight(color, direction); model3Dgroup.Children.Add((Model3D)directionalLight); AmbientLight ambientLight = new AmbientLight(color); model3Dgroup.Children.Add((Model3D)ambientLight); return(modelVisual3D); }
protected override void CreateScene() { SmallTarget = WaveServices.GraphicsDevice.RenderTargets.CreateRenderTarget(256, 256); DirectionalLight skylight = new DirectionalLight("SkyLight", new Vector3(1)); EntityManager.Add(skylight); ViewCamera camera = new ViewCamera("MainCamera", new Vector3(0, 2, 4), Vector3.Zero); camera.BackgroundColor = Color.Red; camera.RenderTarget = SmallTarget; EntityManager.Add(camera.Entity); Entity primitive = new Entity("Primitive") .AddComponent(new Transform3D()) .AddComponent(new BoxCollider()) .AddComponent(new Spinner() { AxisTotalIncreases = new Vector3(-1f, -1f, -1f) }) .AddComponent(Model.CreateCube()) .AddComponent(new MaterialsMap(new BasicMaterial(Color.Yellow) { LightingEnabled = true })) .AddComponent(new ModelRenderer()); EntityManager.Add(primitive); }
private void CalcAndDraw_Click(object sender, RoutedEventArgs e) { DrawSphere(Convert.ToDouble(BoxR.Text), Convert.ToInt32(BoxN.Text), Convert.ToInt32(Boxn.Text)); DirectionalLight directionalLight = new DirectionalLight(); directionalLight.Color = Colors.White; directionalLight.Direction = new Vector3D(-1, -1, 2); PerspectiveCamera perspectiveCamera = new PerspectiveCamera(); perspectiveCamera.Position = new Point3D(10, 10, 0); perspectiveCamera.LookDirection = new Vector3D(-10, -10, 0); mainViewport.Camera = perspectiveCamera; ModelVisual3D myModelVisual3D = new ModelVisual3D(); Model3DGroup myModel3DGroup = new Model3DGroup(); myModel3DGroup.Children.Add(directionalLight); myModelVisual3D.Content = myModel3DGroup; mainViewport.Children.Add(myModelVisual3D); }
void _walkThrough_Checked(object sender, RoutedEventArgs e) { this._settings.view3d.Visibility = System.Windows.Visibility.Visible; if (this._settings._allModels.Children.Count < 2) { var models = this._host.BIM_To_OSM.ParseBIM(this._host.cellularFloor.Territory_Min, this._host.cellularFloor.Territory_Max, 1);//offset); List <GeometryModel3D> meshObjects = new List <GeometryModel3D>(models.Count); foreach (GeometryModel3D item in models) { meshObjects.Add(item); } this._settings._allModels.Children = new System.Windows.Media.Media3D.Model3DCollection(meshObjects); var light = new DirectionalLight() { Color = Colors.White, Direction = new Vector3D(-1, -1, -3), }; this._settings._allModels.Children.Add(light); } this.agent.RaiseVisualEvent += this.updateCamera; this._settings._camera.UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 0, 1); }
ModelVisual3D Create3DModel(out Point3D position, out Vector3D lookDirection) { ModelVisual3D model = new ModelVisual3D(); Model3DGroup group = new Model3DGroup(); DirectionalLight light; PointsGroup = CreatePoints3DGroup(); group.Children.Add(PointsGroup); TrianglesGroup = CreateTriangles3DGroup(); group.Children.Add(TrianglesGroup); light = new DirectionalLight(Colors.White, new Vector3D(0, 0, -1)); group.Children.Add(light); position = new Point3D(group.Bounds.Location.X, group.Bounds.Location.Y, group.Bounds.Location.Z + group.Bounds.SizeZ); lookDirection = new Vector3D(-group.Bounds.SizeX, -group.Bounds.SizeY, -group.Bounds.SizeZ); model.Content = group; return(model); }
/// <summary> /// プロパティからのアクセスに使用する EffectParameter の取得と初期化を行います。 /// </summary> void InitializeParameters() { view = backingEffect.Parameters["View"]; projection = backingEffect.Parameters["Projection"]; ambientLightColor = backingEffect.Parameters["AmbientLightColor"]; directionalLight0 = new DirectionalLight( backingEffect.Parameters["DirLight0Direction"], backingEffect.Parameters["DirLight0DiffuseColor"], backingEffect.Parameters["DirLight0SpecularColor"], null); directionalLight1 = new DirectionalLight( backingEffect.Parameters["DirLight1Direction"], backingEffect.Parameters["DirLight1DiffuseColor"], backingEffect.Parameters["DirLight1SpecularColor"], null); directionalLight2 = new DirectionalLight( backingEffect.Parameters["DirLight2Direction"], backingEffect.Parameters["DirLight2DiffuseColor"], backingEffect.Parameters["DirLight2SpecularColor"], null); fogEnabled = backingEffect.Parameters["FogEnabled"]; fogStart = backingEffect.Parameters["FogStart"]; fogEnd = backingEffect.Parameters["FogEnd"]; fogColor = backingEffect.Parameters["FogColor"]; diffuseColor = backingEffect.Parameters["DiffuseColor"]; alpha = backingEffect.Parameters["Alpha"]; emissiveColor = backingEffect.Parameters["EmissiveColor"]; specularColor = backingEffect.Parameters["SpecularColor"]; specularPower = backingEffect.Parameters["SpecularPower"]; // View の設定時に [M41, M42, M43] を EyePosition へ設定します。 // このため、専用のプロパティによるアクセスを提供しません。 // BasicEffect でも EyePosition は定義済みで、Fog の制御で使用しますが、 // 同様の方法で EyePosition を View から設定しているのではないか、と・・・。 eyePosition = backingEffect.Parameters["EyePosition"]; }
protected override void LoadContent() { base.LoadContent(); Vector2 size = GetScreenPosition(new Vector2(0.5f, 0.6f)); Bounds = new Rectangle(0, 0, (int)size.X, (int)size.Y); List <Tuple <String, GameState> > itemInfo = new List <Tuple <string, GameState> >(); itemInfo.Add(new Tuple <String, GameState>("Back", GameState.MainMenu)); itemInfo.Add(new Tuple <String, GameState>("Start", GameState.Gameplay)); foreach (var info in itemInfo) { MenuItem item = new StateActionMenuItem(info.Item1, info.Item2); item.Background = ButtonBackground; item.Font = MenuFont; item.FontColor = ItemColor; item.FontColorSelected = ItemColorSelected; item.SetWidth(ButtonBackground.Bounds.Width); AddMenuItem(item); } directionalLight = new DirectionalLight( new Vector3(-1.25f, -2f, 5.0f), // Direction new Vector3(.1f, .1f, .1f), //new Vector3(.15f, .14f, .29f), // Ambient new Vector3(1f, 1f, 1f)); // Diffuse MakeCar(); cameraPosition = new Vector3(0, 100f, 300f); projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.01f, 500f); if (availableColors.Exists(c => c == GameSettings.Default.CarColor)) { diffuseColor = GameSettings.Default.CarColor; } }
public MainWindow() { InitializeComponent(); Sphere sphere; Light light; scene = new Scene(); scene.Camera = new PerspectiveCamera(320, 200, 60); scene.Camera.Transformations.Add(new LookAt(Vector3.Zero, new Vector3(0, 0, -5), Vector3.UnitY)); //scene.Camera.Transformations.Add(new Translation(-1, -1, 0)); sphere = new Sphere(1); sphere.Transformations.Add(new Translation(-0.5f, 0, -5)); scene.Primitives.Add(sphere); sphere = new Sphere(1.25f); sphere.Transformations.Add(new Translation(0.5f, 0, -5)); scene.Primitives.Add(sphere); light = new DirectionalLight(); scene.Lights.Add(light); }
public void RenderWaterReflection(WaterPlane water, DirectionalLight Sun, BaseCamera camera, ref Matrix4 ProjectionMatrix, Vector4 clipPlane = new Vector4()) { if (bPostConstructor) { return; } Matrix4 modelMatrix, mirrorMatrix; mirrorMatrix = GetMirrorMatrix(water); modelMatrix = GetWorldMatrix(); /*If clip plane is set - enable clipping plane*/ if (clipPlane.X == 0 && clipPlane.Y == 0 && clipPlane.Z == 0 && clipPlane.W == 0) { GL.Disable(EnableCap.ClipDistance0); } else { GL.Enable(EnableCap.ClipDistance0); } m_liteReflectionShader.startProgram(); m_texture.BindTexture(TextureUnit.Texture0); m_normalMap?.BindTexture(TextureUnit.Texture1); m_liteReflectionShader.SetTexture(0); m_liteReflectionShader.SetNormalMap(1); m_liteReflectionShader.SetMaterial(m_material); m_liteReflectionShader.SetTransformationMatrices(ref mirrorMatrix, ref modelMatrix, camera.GetViewMatrix(), ref ProjectionMatrix); m_liteReflectionShader.SetDirectionalLight(Sun); m_liteReflectionShader.SetClipPlane(ref clipPlane); m_skin.Buffer.RenderVAO(PrimitiveType.Triangles); m_liteReflectionShader.stopProgram(); }
// Declare member variables here. Examples: // private int a = 2; // private string b = "text"; // Called when the node enters the scene tree for the first time. public override void _Ready() { //add perf info label AddChild(new MonoDiagLabel() { position = MonoDiagLabel.POSITION.TOP_CENTER, }); //setup a moveable camera var inputControl = new InputController(); inputControl.Translate(new Vector3(0, 0, 3)); inputControl.AddChild(new Camera()); AddChild(inputControl); var dirLight = new DirectionalLight(); dirLight.Rotation = Vector3.One; //rotate aprox 57' in xyz AddChild(dirLight); //add a fish via code, put it at (0,3,0) { var mesh = GD.Load <Mesh>("res://asset/fish/Fish1.obj"); var shader = GD.Load <Shader>("res://asset/fish/fish1.shader"); var diffuse = GD.Load <Texture>("res://asset/fish/Fish1-diffuse_base.png"); shader.SetDefaultTextureParam("texture_albedo", diffuse); var meshInst = new MeshInstance(); meshInst.Mesh = mesh; var shadMat = new ShaderMaterial(); shadMat.Shader = shader; shadMat.SetShaderParam("texture_albedo", diffuse); meshInst.MaterialOverride = shadMat; meshInst.Translate(Vector3.Up * 3); AddChild(meshInst); } }
public VisualTree3DView(Visual visual) { var directionalLight1 = new DirectionalLight(Colors.White, new Vector3D(0, 0, 1)); var directionalLight2 = new DirectionalLight(Colors.White, new Vector3D(0, 0, -1)); double z = 0; var model = ConvertVisualToModel3D(visual, ref z); var group = new Model3DGroup(); group.Children.Add(directionalLight1); group.Children.Add(directionalLight2); group.Children.Add(model); zScaleTransform = new ScaleTransform3D(); group.Transform = zScaleTransform; var modelVisual = new ModelVisual3D(); modelVisual.Content = group; var bounds = model.Bounds; double fieldOfView = 45; var lookAtPoint = new Point3D(bounds.X + bounds.SizeX / 2, bounds.Y + bounds.SizeY / 2, bounds.Z + bounds.SizeZ / 2); var cameraDistance = 0.5 * bounds.SizeX / Math.Tan(0.5 * fieldOfView * Math.PI / 180); var position = lookAtPoint - new Vector3D(0, 0, cameraDistance); Camera camera = new PerspectiveCamera(position, new Vector3D(0, 0, 1), new Vector3D(0, -1, 0), fieldOfView); zScaleTransform.CenterZ = lookAtPoint.Z; Children.Add(modelVisual); Camera = camera; ClipToBounds = false; Width = 500; Height = 500; trackballBehavior = new TrackballBehavior(this, lookAtPoint); }
private void charLightsListBox_SelectedIndexChanged(object sender, EventArgs e) { if (charLightsListBox.SelectedItems.Count == 0) { return; } switch (charLightsListBox.Items[charLightsListBox.SelectedIndex].ToString()) { default: break; case "Diffuse": selectedCharDiffuseLight = Runtime.lightSetParam.characterDiffuse; SetUpCharDiffuseLight(); // The additional character diffuse lights don't have ambient color. charColor2Button.Visible = true; charColor2Panel.Visible = true; break; case "Diffuse2": selectedCharDiffuseLight = Runtime.lightSetParam.characterDiffuse2; SetUpCharDiffuseLight(); break; case "Diffuse3": selectedCharDiffuseLight = Runtime.lightSetParam.characterDiffuse3; SetUpCharDiffuseLight(); break; case "Fresnel": charColor2Panel.Enabled = true; SetUpCharFresnelLight(); break; } charDifColorGLControl.Invalidate(); }
internal void Use(Camera sender) { if (DataLocker == null || this._Data == null) { return; } lock (DataLocker) { Shader.Use(); GL.BlendFuncSeparate((OpenTK.Graphics.OpenGL4.BlendingFactorSrc)SourceColorBlending, DestinationColorBlending, (OpenTK.Graphics.OpenGL4.BlendingFactorSrc)SourceAlphaBlending, DestinationAlphaBlending); //set the lights DirectionalLight main = DirectionalLight.Main; if (main != null) { this.SetData <Vector4>("mainLightColor", main.Color); this.SetData <Vector3>("mainLightDirection", -main.WObject.Forward); this.SetData <Vector4>("mainLightAmbiant", main.Ambient); } int texCount = 0; if (_Data == null || _DataInMaterial == null) { return; } for (int i = 0; i < _Data.Length; i++) { if (ReferenceEquals(_DataInMaterial[i].Data, _Data[i])) { continue; } MaterialData data = _DataInMaterial[i] = _Data[i]; SetGLData(ref data, ref texCount); } } }
protected override void CreateScene() { // Lights DirectionalLight light = new DirectionalLight("light", new Vector3(-10f, 7f, -5f)); EntityManager.Add(light); RenderManager.FrustumCullingEnabled = false; // Game Behavior GameBehavior gameBehavior = new GameBehavior(); // Create Player this.Player = this.modelFactoryService.CreatePlayer(gameBehavior); EntityManager.Add(this.Player); // Create Camera var camera = new FixedCamera("mainCamera", Vector3.Zero, Vector3.Zero); // Setted in GameBehavior Init camera.BackgroundColor = Color.CornflowerBlue; this.GameCamera = camera.Entity.FindComponent<Camera3D>(); EntityManager.Add(camera); // Add Scene Behavior this.AddSceneBehavior(gameBehavior, SceneBehavior.Order.PostUpdate); }
/// <summary> /// Parses a <see cref="DirectionalLight" /> from the given XML node. /// </summary> /// <param name="node">The XML node.</param> /// <returns>A <see cref="SceneNode" /> instance.</returns> public SceneNode ParseDirectionalLight(XElement node) { var directionalLight = new DirectionalLight( Vector3.Zero, Quaternion.Identity, Vector3.One, this.ParseColor(node.Element("color")), float.Parse(node.Attribute("intensity").Value), this.ParseVector3(node.Element("direction"))); var sceneNode = new SceneNode(); sceneNode.AttachEntity(directionalLight); return sceneNode; }
public void AddDirectionalLight(DirectionalLight light) { DirectionalLights[Buffer].Add(light); }
public void Draw(DeviceContext dc, CameraBase cam, DirectionalLight[] lights) { if (_useTessellation) { dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith4ControlPoints; dc.InputAssembler.InputLayout = InputLayouts.TerrainCP; var stride = TerrainCP.Stride; const int offset = 0; dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_quadPatchVB, stride, offset)); dc.InputAssembler.SetIndexBuffer(_quadPatchIB, Format.R16_UInt, 0); var viewProj = cam.ViewProj; var planes = cam.FrustumPlanes; var toTexSpace = Matrix.Scaling(0.5f, -0.5f, 1.0f) * Matrix.Translation(0.5f, 0.5f, 0); Effects.TerrainFX.SetViewProj(viewProj); Effects.TerrainFX.SetEyePosW(cam.Position); Effects.TerrainFX.SetDirLights(lights); Effects.TerrainFX.SetFogColor(Color.Silver); Effects.TerrainFX.SetFogStart(15.0f); Effects.TerrainFX.SetFogRange(175.0f); Effects.TerrainFX.SetMinDist(MinDist); Effects.TerrainFX.SetMaxDist(MaxDist); Effects.TerrainFX.SetMinTess(MinTess); Effects.TerrainFX.SetMaxTess(MaxTess); Effects.TerrainFX.SetTexelCellSpaceU(1.0f / Info.HeightMapWidth); Effects.TerrainFX.SetTexelCellSpaceV(1.0f / Info.HeightMapHeight); Effects.TerrainFX.SetWorldCellSpace(Info.CellSpacing); Effects.TerrainFX.SetWorldFrustumPlanes(planes); Effects.TerrainFX.SetLayerMapArray(_layerMapArraySRV); Effects.TerrainFX.SetBlendMap(_blendMapSRV); Effects.TerrainFX.SetHeightMap(_heightMapSRV); Effects.TerrainFX.SetMaterial(_material); Effects.TerrainFX.SetViewProjTex(viewProj * toTexSpace); var tech = Shadows ? Effects.TerrainFX.Light1ShadowTech: Effects.TerrainFX.Light1Tech; for (int p = 0; p < tech.Description.PassCount; p++) { var pass = tech.GetPassByIndex(p); pass.Apply(dc); dc.DrawIndexed(_numPatchQuadFaces * 4, 0, 0); } dc.HullShader.Set(null); dc.DomainShader.Set(null); if (DebugBvh) { DrawBVHDebug(dc, cam, offset); } } else { dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; dc.InputAssembler.InputLayout = InputLayouts.TerrainCP; var viewProj = cam.ViewProj; Effects.TerrainFX.SetViewProj(viewProj); Effects.TerrainFX.SetEyePosW(cam.Position); Effects.TerrainFX.SetDirLights(lights); Effects.TerrainFX.SetFogColor(Color.Silver); Effects.TerrainFX.SetFogStart(15.0f); Effects.TerrainFX.SetFogRange(175.0f); Effects.TerrainFX.SetTexelCellSpaceU(1.0f / Info.HeightMapWidth); Effects.TerrainFX.SetTexelCellSpaceV(1.0f / Info.HeightMapHeight); Effects.TerrainFX.SetWorldCellSpace(Info.CellSpacing); Effects.TerrainFX.SetLayerMapArray(_layerMapArraySRV); Effects.TerrainFX.SetBlendMap(_blendMapSRV); Effects.TerrainFX.SetHeightMap(_heightMapSRV); Effects.TerrainFX.SetMaterial(_material); var tech = Effects.TerrainFX.Light1TechNT; for (var p = 0; p < tech.Description.PassCount; p++) { var pass = tech.GetPassByIndex(p); pass.Apply(dc); for (var i = 0; i < _patches.Count; i++) { var patch = _patches[i]; if (cam.Visible(patch.Bounds)) { var ns = new Dictionary<NeighborDir, Patch>(); if (i < NumPatchVertCols) { ns[NeighborDir.Top] = null; } else { ns[NeighborDir.Top] = _patches[i - NumPatchVertCols + 1]; } if (i%(NumPatchVertCols - 1) == 0) { ns[NeighborDir.Left] = null; } else { ns[NeighborDir.Left] = _patches[i - 1]; } if (Util.IsKeyDown(Keys.N)) { patch.Draw(dc, cam.Position); } else { patch.Draw(dc, cam.Position, ns); } } } } } }
public void AddLight(DirectionalLight light) { directionalLights.Add(light); }
public void Draw(Matrix view, Matrix projection, Vector3 cameraPosition, DirectionalLight directionalLight) { Effect.Parameters["EyePosition"].SetValue(cameraPosition); Effect.Parameters["View"].SetValue(view); Effect.Parameters["World"].SetValue(Matrix.Identity); Effect.Parameters["Projection"].SetValue(projection); Effect.Parameters["ShadowMapView"].SetValue(ShadowMapView); Effect.Parameters["ShadowMapProjection"].SetValue(ShadowMapProjection); Effect.Parameters["ShadowMap"].SetValue(ShadowMap); Effect.Parameters["NormalMatrix"].SetValue(Matrix.Invert(Matrix.Transpose(Matrix.Identity))); Effect.Parameters["DirectionalDirection"].SetValue(directionalLight.Direction); Effect.Parameters["DirectionalDiffuse"].SetValue(directionalLight.Diffuse); Effect.Parameters["DirectionalAmbient"].SetValue(directionalLight.Ambient); foreach (EffectPass pass in Effect.CurrentTechnique.Passes) { pass.Apply(); device.Indices = indexBuffer; device.SetVertexBuffer(vertexBuffer); device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexCount, 0, indexBuffer.IndexCount / 3); } }
// [XenkoScript] public static async Task LoadCave(EngineContext engineContext, Entity animationEntity) { // Setup "fake" directional light for outdoor so that normal maps stand out. var outdoorLight = new DirectionalLight { LightDirection = new Vector3(-2.0f, -1.0f, -1.0f) }; //outdoor.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = { outdoorLight } }); //outdoor.Permutations.Set(LightingPermutation.Key, new LightingPermutation { Lights = { outdoorLight } }); var effectMagma = engineContext.RenderContext.Effects.First(x => x.Name == "Magma"); effectMagma.Parameters.AddSources(engineContext.DataContext.RenderPassPlugins.TryGetValue("NoisePlugin").Parameters); //var assetManager = new AssetManager(new ContentSerializerContextGenerator(engineContext.VirtualFileSystem, engineContext.PackageManager, ParameterContainerExtensions.DefaultSceneSerializer)); var caveEntityPrefab1 = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/bg/bg1.hotei#"); var caveEntityPrefab2 = await engineContext.AssetManager.LoadAsync<Entity>("/global_data/gdc_demo/bg/bg2.hotei#"); var caveEntity1 = Prefab.Clone(caveEntityPrefab1); var caveEntity2 = Prefab.Clone(caveEntityPrefab2); SkyBoxPlugin skyBoxPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin)) { var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds"); skyBoxPlugin.Texture = skyBoxTexture; } var magmaTexturePaths = new[] { "/global_data/gdc_demo/bg/GDC2012_map_maguma_04.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_05.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_06.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_00.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_01.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_02.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_03.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_noise_00.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_noise_01.dds", "/global_data/gdc_demo/bg/GDC2012_map_maguma_normals.dds", }; var magmaTextures = new Texture2D[magmaTexturePaths.Length]; for (int i = 0; i < magmaTextures.Length; i++) { magmaTextures[i] = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>(magmaTexturePaths[i]); } var lightVectors = new[] { new Vector3(-1.0f, 0.3f, -1.0f), new Vector3(1.0f, 0.0f, -1.0f), new Vector3(1.0f, 0.0f, -1.0f), }; var random = new Random(0); int planeIndex = 0; foreach (var entity in ParameterContainerExtensions.CollectEntityTree(caveEntity1)) { var meshComponent = entity.Get(ModelComponent.Key); if (meshComponent == null) continue; // Setup textures for magma if (entity.Name.StartsWith("maguma_")) { meshComponent.MeshParameters.Set(LightKeys.LightDirection, lightVectors[planeIndex]); meshComponent.MeshParameters.Set(ParameterKeys.IndexedKey(TexturingKeys.Texture0, 1), magmaTextures[planeIndex]); planeIndex++; for (int i = 3; i < magmaTextures.Length; i++) meshComponent.MeshParameters.Set(ParameterKeys.IndexedKey(TexturingKeys.Texture0, i - 1), magmaTextures[i]); foreach (var effectMesh in meshComponent.SubMeshes) { effectMesh.EffectData.Name = "Magma"; } // Attach a bullet particle emitter to the magma var emitter = new BulletParticleEmitterComponent() { //Count = 4096, Count = 16384, Description = new BulletEmitterDescription() { Target = new Vector3(-3016.261f, -70.52288f, 800.8788f), BulletSize = 4.0f, //MaxTimeTarget = 1000.0f + 5000.0f * (float)random.NextDouble(), VelocityUp = new Vector3(0, 0, 200), MaxTimeUp = 5000.0f, MaxTimeTarget = 20000.0f, VelocityTarget = 200.0f, Opacity = 1.0f, //DistanceDragonRepulse = 1200.0f, //DecayDragonRepulse = 70.0f, DistanceDragonRepulse = 600.0f, DecayDragonRepulse = 70.0f, VelocityRepulse = 200.0f, }, RootAnimation = animationEntity, }; emitter.OnAddToSystem(engineContext.EntityManager, engineContext.RenderContext); emitter.OnUpdateData(); entity.Set(ParticleEmitterComponent.Key, emitter); } foreach (var effectMesh in meshComponent.SubMeshes) { effectMesh.Parameters.Set(ParameterKeys.IndexedKey(TexturingKeys.DiffuseTexture, 3), (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/GDC2012_map_dis_ao.dds")); } } await engineContext.EntityManager.AddEntityAsync(caveEntity1); await engineContext.EntityManager.AddEntityAsync(caveEntity2); foreach (var entity in ParameterContainerExtensions.CollectEntityTree(caveEntity1).Concat(ParameterContainerExtensions.CollectEntityTree(caveEntity2))) { var meshComponent = entity.Get(ModelComponent.Key); if (meshComponent == null) continue; foreach (var effectMesh in meshComponent.InstantiatedSubMeshes) { effectMesh.Value.Parameters.Set(MaterialKeys.SpecularIntensity, 2.0f); effectMesh.Value.Parameters.Set(MaterialKeys.SpecularPower, 0.1f); } } }
public TerrainModel(GraphicsDevice device, int terrainSize, int terrainSegments, float terrainStart, int xOffset, int zOffset, Vector3 terrainScale, float[,] heightMap, float[,] roadMap, Effect effect, DirectionalLight directionalLight) { this.device = device; int terrainSizeMinusOne = terrainSize; terrainSize++; int vertexCount = terrainSize * terrainSize; vertices = new MultitexturedVertex[vertexCount]; for (int z = 0; z < terrainSize; z++) { for (int x = 0; x < terrainSize; x++) { var textureWeights = new Vector4( roadMap[xOffset + x, zOffset + z], MathHelper.Clamp(1 - Math.Abs(heightMap[xOffset + x, zOffset + z] - 0.2f) / 0.4f, 0, 1), MathHelper.Clamp(1 - Math.Abs(heightMap[xOffset + x, zOffset + z] - 0.7f) / 0.2f, 0, 1), MathHelper.Clamp(1 - Math.Abs(heightMap[xOffset + x, zOffset + z] - 1) / 0.3f, 0, 1) ); textureWeights.Normalize(); vertices[z * terrainSize + x] = new MultitexturedVertex( terrainScale * new Vector3( (terrainStart + xOffset + x), // X heightMap[xOffset + x, zOffset + z], // Y (terrainStart + zOffset + z)), // Z Vector3.Zero, // Normal Vector3.Zero, // Binormal Vector3.Zero, // Tangent new Vector2(x / 8f, z / 8f), textureWeights); } } BoundingBox = BoundingBox.CreateFromPoints(vertices.Select(vert => vert.Position)); //MinBox = BoundingBox.CreateFromPoints(new Vector3[] { BoundingBox.Min.GetXZProjection(false), BoundingBox.Max.GetXZProjection(false) }); #region Indicies & Vertex normals setup int flexIndice = 1; int rowIndex = 2; int[] indices = new int[terrainSizeMinusOne * terrainSizeMinusOne * 6]; indices[0] = 0; indices[1] = terrainSize; indices[2] = flexIndice; for (int i = 5; i <= indices.Length; i += 3) { indices[i - 2] = indices[i - 4]; indices[i - 1] = indices[i - 3]; if (i % 2 == 0) { flexIndice -= terrainSizeMinusOne; indices[i] = flexIndice; } else { flexIndice += terrainSize; indices[i] = flexIndice; } if (i + 3 >= indices.Length) break; else if (rowIndex * terrainSize - 1 == indices[i]) { indices[i + 1] = flexIndice - terrainSize + 1; indices[i + 2] = flexIndice + 1; indices[i + 3] = flexIndice - terrainSize + 2; flexIndice = indices[i + 3]; rowIndex++; i += 3; } } for (int i = 0; i < indices.Length / 3; i++) { Vector3 firstvec = vertices[indices[i * 3]].Position; Vector3 secondvec = vertices[indices[i * 3 + 1]].Position; Vector3 thirdvec = vertices[indices[i * 3 + 2]].Position; Vector3 firstsub = secondvec - firstvec; Vector3 secondsub = thirdvec - firstvec; Vector3 normal; if(i % 2 == 0) { normal = Vector3.Cross(firstsub, secondsub); }else{ normal = Vector3.Cross(secondsub, firstsub); } normal.Normalize(); vertices[indices[i * 3]].Normal += normal; vertices[indices[i * 3 + 1]].Normal += normal; vertices[indices[i * 3 + 2]].Normal += normal; #region Binormal & Tangent // Calculate binormal and tangent to get normal map to work // Retrieved from http://xboxforums.create.msdn.com/forums/p/30443/172880.aspx Vector2 w1 = vertices[indices[i * 3]].TextureCoordinate; Vector2 w2 = vertices[indices[i * 3 + 1]].TextureCoordinate; Vector2 w3 = vertices[indices[i * 3 + 2]].TextureCoordinate; float s1 = w2.X - w1.X, s2 = w3.X - w1.X, t1 = w2.Y - w1.Y, t2 = w3.Y - w1.Y; float r = 1.0f / (s1 * t2 - s2 * t1); Vector3 sdir = new Vector3((t2 * firstsub.X - t1 * secondsub.X) * r, (t2 * firstsub.Y - t1 * secondsub.Y) * r, (t2 * firstsub.Z - t1 * secondsub.Z) * r); Vector3 tdir = new Vector3((s1 * secondsub.X - s2 * firstsub.X) * r, (s1 * secondsub.Y - s2 * firstsub.Y) * r, (s1 * secondsub.Z - s2 * firstsub.Z) * r); // Gram-Schmidt orthogonalize Vector3 tangent = sdir - normal * Vector3.Dot(normal, sdir); tangent.Normalize(); // Calculate handedness (here maybe you need to switch >= with <= depend on the geometry winding order) float tangentdir = (Vector3.Dot(Vector3.Cross(normal, sdir), tdir) <= 0.0f) ? 1.0f : -1.0f; Vector3 binormal = Vector3.Cross(normal, tangent) * tangentdir; // Set the values to the vertices vertices[indices[i * 3]].Tangent = tangent; vertices[indices[i * 3 + 1]].Tangent = tangent; vertices[indices[i * 3 + 2]].Tangent = tangent; vertices[indices[i * 3]].Binormal = binormal; vertices[indices[i * 3 + 1]].Binormal = binormal; vertices[indices[i * 3 + 2]].Binormal = binormal; #endregion } for (int i = 0; i < vertices.Length; i++) { vertices[i].Normal.Normalize(); } #endregion indexBuffer = new IndexBuffer(device, typeof(int), terrainSizeMinusOne * terrainSizeMinusOne * 6, BufferUsage.None); indexBuffer.SetData(indices); vertexBuffer = new VertexBuffer(device, typeof(MultitexturedVertex), vertices.Length, BufferUsage.None); vertexBuffer.SetData(vertices); #region Effect this.Effect = effect; this.ShadowMap = new RenderTarget2D(device, 1024, 1024, false, SurfaceFormat.Single, DepthFormat.Depth24Stencil8); #endregion }
public Surface(int w, int h, string pathToFile, System.Windows.Forms.ToolStripProgressBar bar = null, System.Windows.Forms.ToolStripLabel label = null, Form1 form = null, bool shaderOption = false) { this.shaderOption = shaderOption; this.form = form; toolStripBar = bar; toolStripLabel = label; WhatToDraw = 1; Status = colrscl = rotate = false; minX = minY = min = float.MaxValue; maxX = maxY = max = float.MinValue; scale = 1.0f; angleX = angleY = 0.0f; width = w; height = h; NumOfIndexes = NumOfVertices = Xwidth = Ywidth = 0; //svetlo - smer,ambient,specular,diffuse light = new DirectionalLight(new Vector3(0.0f, 0.0f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f)); //material - ambient,specular,diffuse,koeficienty - ambient, specular, diffuse, shininess material = new Material(0.29f, 0.86f, 0.57f, 128); //BigBrother = new Kamera(new Vector3(0.0f, 0.0f, 3.5f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f)); coords = new List<Vector3>(); VBO = new int[4]; VAO = new int[1]; VertexShader = new Shaders.Shader(); FragmentShader = new Shaders.Shader(); spMain = new Shaders.ShaderProgram(); var bw = new System.ComponentModel.BackgroundWorker(); bw.DoWork += (sender, args) => { // do your lengthy stuff here -- this will happen in a separate thread LoadData(pathToFile); if (Status = SetWidth()) { vertices = new Vector3[NumOfVertices]; color = new Vector3[NumOfVertices]; normals = new Vector3[NumOfVertices]; Indices = new List<int>(); Indexes = new int[NumOfIndexes]; //SetIndices(); SetIndexes(); if (Ywidth > Xwidth) { rotate = true; MatrixStore_Rotations = Matrix4.CreateFromAxisAngle(new Vector3(0.0f, 0.0f, 1.0f), -90.0f * (float)Math.PI / 180.0f); } } else { //dorobit sem este resetovanie progressBaru/labelu System.Windows.Forms.MessageBox.Show("Súbor " + pathToFile + " nemá podporu!", "Vnimanie!", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); label lab = new label(SetToolStripLabel); progres progres = new progres(SetProgressBar); form.statusStrip1.Invoke(lab, "Súbor nemá podporu..."); form.statusStrip1.Invoke(progres, 0); } }; bw.RunWorkerCompleted += (sender, args) => { if (args.Error != null) // if an exception occurred during DoWork, System.Windows.Forms.MessageBox.Show(args.Error.ToString()); // do your error handling here if (Status) { colorScale = new ColorScale(min, max, width, height); CalculateColor(); ScaleHeights(10.0f); CalculateNormals(); InitScene(false); FirstDraw(); form.SetBoolean_surface(true); } else form.SetMenuStrip_Enabled(true); }; bw.RunWorkerAsync(); // starts the background worker }
public abstract Color ComputeDirectionalLight( DirectionalLight dL, Object3D obj, V3 p, V2 uv );
/// <summary>Initializes this instance.</summary> protected override void Initialize() { textureParam = Parameters["Texture"]; samplerParam = Parameters["TextureSampler"]; diffuseColorParam = Parameters["DiffuseColor"]; emissiveColorParam = Parameters["EmissiveColor"]; specularColorParam = Parameters["SpecularColor"]; specularPowerParam = Parameters["SpecularPower"]; eyePositionParam = Parameters["EyePosition"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldParam = Parameters["World"]; worldInverseTransposeParam = Parameters["WorldInverseTranspose"]; worldViewProjParam = Parameters["WorldViewProj"]; light0 = new DirectionalLight(Parameters["DirLight0Direction"], Parameters["DirLight0DiffuseColor"], Parameters["DirLight0SpecularColor"], null); light1 = new DirectionalLight(Parameters["DirLight1Direction"], Parameters["DirLight1DiffuseColor"], Parameters["DirLight1SpecularColor"], null); light2 = new DirectionalLight(Parameters["DirLight2Direction"], Parameters["DirLight2DiffuseColor"], Parameters["DirLight2SpecularColor"], null); samplerParam.SetResource(GraphicsDevice.SamplerStates.Default); }
public override Color ComputeDirectionalLight( DirectionalLight dL, Object3D obj, V3 p, V2 uv ) { return new Color(0, 0, 0); }
public void RemoveDirectionalLight(DirectionalLight light) { DirectionalLights[Buffer].Remove(light); }
public void AddDirectionalLight(DirectionalLight light) { this.DirectionalLights.Add (light); }
public void UpdateLightSpaceMatrices(Camera camera, DirectionalLight light) { viewLightMatrices &= light.CameraToCsmProjections (camera, MapCount); }
internal void addLight(DirectionalLight light) { throw new NotImplementedException(); }
public void UpdateLightSpaceMatrix(Camera camera, DirectionalLight light) { lightSpaceMatrix &= light.CameraToShadowProjection (camera); }
public void RemoveLight(DirectionalLight light) { directionalLights.Remove(light); }
/// <summary> /// Looks up shortcut references to our effect parameters. /// </summary> void CacheEffectParameters(BasicEffect cloneSource) { textureParam = Parameters["Texture"]; diffuseColorParam = Parameters["DiffuseColor"]; emissiveColorParam = Parameters["EmissiveColor"]; specularColorParam = Parameters["SpecularColor"]; specularPowerParam = Parameters["SpecularPower"]; eyePositionParam = Parameters["EyePosition"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldParam = Parameters["World"]; worldInverseTransposeParam = Parameters["WorldInverseTranspose"]; worldViewProjParam = Parameters["WorldViewProj"]; shaderIndexParam = Parameters["ShaderIndex"]; light0 = new DirectionalLight(Parameters["DirLight0Direction"], Parameters["DirLight0DiffuseColor"], Parameters["DirLight0SpecularColor"], (cloneSource != null) ? cloneSource.light0 : null); light1 = new DirectionalLight(Parameters["DirLight1Direction"], Parameters["DirLight1DiffuseColor"], Parameters["DirLight1SpecularColor"], (cloneSource != null) ? cloneSource.light1 : null); light2 = new DirectionalLight(Parameters["DirLight2Direction"], Parameters["DirLight2DiffuseColor"], Parameters["DirLight2SpecularColor"], (cloneSource != null) ? cloneSource.light2 : null); }