public void Knockback(LightSource lightSource) { if (lightSource is Player) { Transform player = lightSource.transform; Rigidbody playerRigidbody = player.GetComponent<Rigidbody>(); this.controllerRumble = player.GetComponent<ControllerRumble>(); // Calculate a knockback force pushing the player away from the enemy fish Vector2 distance = (player.position - gameObject.transform.position); Vector2 knockback = distance.normalized * knockbackForce; playerRigidbody.velocity = Vector3.zero; playerRigidbody.AddForce(knockback, ForceMode.Impulse); // Instantiate hit particles GameObject.Instantiate(hitParticles, player.position, Quaternion.Euler(0, 0, 0)); FlashColor(probeColorHit, hitFlashDuration); // Rumble the controller when the player hits a fish. controllerRumble.PlayerHitByFish(); // The player was just hit // lastTimeHit = Time.time; } }
public BossSeekPlayer(int priority, string id, LightSource targetLightSource, bool bossSafe) : base(priority, id) { this.targetLightSource = targetLightSource; this.bossAtSafeZone = bossSafe; this.SetPriority(priority); this.SetID(id); }
public SeekOrFleeLight(int priority, string id, LightSource targetLightSource) : base(priority, id) { this.targetLightSource = targetLightSource; SetPriority(priority); SetID(id); }
public virtual void Awake() { // Cache the GameObject's components lightSource = GetComponentInParent<LightSource>(); // Set the initial colour of the light source. OnLightChanged(lightSource.LightEnergy.CurrentEnergy); }
internal AddStaticItem(LightSource lightSource) : this() { Coords = lightSource.Coords; StaticItemType = StaticItemType.LightSource; SubType = (ushort)lightSource.Type; AttachedToFace = lightSource.AttachedToFace; GameObjectId = lightSource.Id; }
public TorchItem(Vector2 _position, string _name, Light _light):base(_position, _name) { name = "Torch"; position = _position; light = new Light(_light.color, _light.intensity, _light.type, _light.position); source = new LightSource(position, name, light); Managers.Executive.level.AddLightSource(ref source); intTick = 300f; texture = Managers.AssetManager.GetTextureAsset(name); }
protected override void LoadContent() { if (Engine.SpriteBatch == null) Engine.SpriteBatch = new SpriteBatch(GraphicsDevice); cloner = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); shadowMapResolver = new ShadowMapResolver(GraphicsDevice, World.LightsFX, GraphicsDevice.Viewport.Width); _lightSource = new LightSource(Engine.AnglerGame.GraphicsDeviceManager, GraphicsDevice.Viewport.Width, LightAreaQuality.VeryHigh, Color.White); shadowMap = new ShadowCasterMap(PrecisionSettings.VeryHigh, Engine.AnglerGame.GraphicsDeviceManager, Engine.SpriteBatch); base.LoadContent(); }
void Start() { this.timer = cooldownTime; this.lightSource = GetComponent<LightSource>(); this.controllerRumble = GetComponent<ControllerRumble>(); this.rigidbody = GetComponent<Rigidbody>(); player = GameObject.FindWithTag("Player").transform; playerSound = player.GetComponent<PlayerSound>(); GameObject mainCamera = GameObject.Find("Main Camera"); if (mainCamera != null) { this.smoothCamera = mainCamera.GetComponent<SmoothCamera>(); } }
public PlayerLightToggle(GameObject lightsToToggle, bool defaultLightStatus, LightSource lightSource, float minimalEnergy, float propulsionLightRange) { this.lightsToToggle = lightsToToggle; this.lightsEnabled = defaultLightStatus; this.lightButtonPressed = defaultLightStatus; this.lightSource = lightSource; this.minimalEnergyRestriction = minimalEnergy; this.propulsionLightRange = propulsionLightRange; this.ToggleLights(); // Cache very close light - needs to be refactored Transform lightTransform = lightsToToggle.transform.Find("VeryClose Light"); if (lightTransform != null) { this.closeLight = lightTransform.GetComponent<Light>(); this.closeLight.intensity = 0; } }
public virtual void Start() { lightSource = GetComponentInParent<LightSource>(); // Choose either the override (if assigned in the Inspector) or the component // attached to this GameObject. if (lightEnergyOverride != null) { this.lightEnergy = lightEnergyOverride; } else if (lightSource) { this.lightEnergy = lightSource.LightEnergy; } else { this.lightEnergy = null; } Subscribe(); // Initialize the attribute to the light's initial energy OnLightChanged(lightEnergy.CurrentEnergy); }
private void Construct(float x, float y) { Strength = 10; Dexterity = 10; Wisdom = 10; UpdateMaxHP(); HP = MaxHP; UpdateMaxMana(); Mana = MaxMana; XP = 0; Faction = "Allies"; LightSource = new LightSource(); LightSource.Width = 32 * 8; LightSource.Height = 32 * 8; LightSource.Color = Color.White; LightSource.PositionType = LightPositionType.Relative; CollisionGroup = "Shadow"; }
/// <summary> /// Register a given light source with the camera, so its lighting can be applied as a pixel shader /// effect. /// </summary> /// <param name="ls"></param> public void registerLightSource(LightSource ls) { Camera.lightSources.Add(ls); }
/// <summary> /// Determines if the specified <see cref="LightSource" /> is one of the defined enumerations. This method is more efficient than using /// <see cref="Enum.IsDefined" />, since <see cref="Enum.IsDefined" /> uses reflection. /// </summary> /// <param name="lightSource">An instance of <see cref="LightSource" /> to test.</param> /// <returns>Returns true if <paramref name="lightSource"/> is one of the defined items in the enumeration; otherwise returns false.</returns> public static bool IsValidLightSource(LightSource lightSource) { switch (lightSource) { case LightSource.D55: case LightSource.D65: case LightSource.D75: case LightSource.Daylight: case LightSource.Flash: case LightSource.Fluorescent: case LightSource.Other: case LightSource.StandardLightA: case LightSource.StandardLightB: case LightSource.StandardLightC: case LightSource.Tungsten: case LightSource.Unknown: break; default: return false; } return true; }
/// <summary> /// Add a new light to the list. /// </summary> /// <param name="light"></param> public void Add(LightSource light) { lights.Add(light); }
/// <summary> /// Applies a knockback force going away from the enemy light source /// </summary> public virtual void Knockback(LightSource enemyLightSource) { }
/// <summary> /// Checks the light sources equiped by the player and makes sure the brightest one is in use /// </summary> public void UpdateLightSources() { //Check for lights if (lt == null) { lt = this.gameObject.GetComponentInChildren<Light> (); } ls = null; int MaxBrightness = LightSource.MagicBrightness; //Start with magically generated light. for (int i = 5; i <= 8; i++) { ls = null; //Update the gameobject at the slot if needed if (LightGameObjects [i - 5] != null) { if (GetObjectAtSlot (i) != LightGameObjects [i - 5].name) { LightGameObjects [i - 5] = GetGameObjectAtSlot (i); } } else { //No object if (GetObjectAtSlot (i) != "") { LightGameObjects [i - 5] = GetGameObjectAtSlot (i); } } if (GetObjectAtSlot (i) != "") { //GameObject objAtSlot = GetGameObjectAtSlot(i); //GameObject.Find (GetObjectAtSlot(i)); if (LightGameObjects [i - 5] != null) { ls = LightGameObjects [i - 5].GetComponent<LightSource> (); if (ls != null) { if (ls.IsOn == true) { if (MaxBrightness < ls.Brightness) { MaxBrightness = ls.Brightness; } } } } } } lt.range = LightSource.BaseBrightness + MaxBrightness; if(MaxBrightness>0) { playerUW.LightActive=true; } else { playerUW.LightActive=false; } }
public RenderObjectHandle(LightSource light) { obj = light; type = RenderObjectType.LIGHT; }
partial void ExplodeProjSpecific(Vector2 worldPosition, Hull hull) { if (shockwave) { GameMain.ParticleManager.CreateParticle("shockwave", worldPosition, Vector2.Zero, 0.0f, hull); } hull ??= Hull.FindHull(worldPosition, useWorldCoordinates: true); bool underwater = hull == null || worldPosition.Y < hull.WorldSurface; if (underwater && underwaterBubble) { var underwaterExplosion = GameMain.ParticleManager.CreateParticle("underwaterexplosion", worldPosition, Vector2.Zero, 0.0f, hull); if (underwaterExplosion != null) { underwaterExplosion.Size *= MathHelper.Clamp(attack.Range / 150.0f, 0.5f, 10.0f); underwaterExplosion.StartDelay = 0.0f; } } for (int i = 0; i < attack.Range * 0.1f; i++) { if (!underwater) { float particleSpeed = Rand.Range(0.0f, 1.0f); particleSpeed = particleSpeed * particleSpeed * attack.Range; if (flames) { float particleScale = MathHelper.Clamp(attack.Range * 0.0025f, 0.5f, 2.0f); var flameParticle = GameMain.ParticleManager.CreateParticle("explosionfire", ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, attack.Range))), hull), Rand.Vector(Rand.Range(0.0f, particleSpeed)), 0.0f, hull); if (flameParticle != null) { flameParticle.Size *= particleScale; } } if (smoke) { GameMain.ParticleManager.CreateParticle(Rand.Range(0.0f, 1.0f) < 0.5f ? "explosionsmoke" : "smoke", ClampParticlePos(worldPosition + Rand.Vector((float)System.Math.Sqrt(Rand.Range(0.0f, attack.Range))), hull), Rand.Vector(Rand.Range(0.0f, particleSpeed)), 0.0f, hull); } } else if (underwaterBubble) { Vector2 bubblePos = Rand.Vector(Rand.Range(0.0f, attack.Range * 0.5f)); GameMain.ParticleManager.CreateParticle("risingbubbles", worldPosition + bubblePos, Vector2.Zero, 0.0f, hull); if (i < attack.Range * 0.02f) { var underwaterExplosion = GameMain.ParticleManager.CreateParticle("underwaterexplosion", worldPosition + bubblePos, Vector2.Zero, 0.0f, hull); if (underwaterExplosion != null) { underwaterExplosion.Size *= MathHelper.Clamp(attack.Range / 300.0f, 0.5f, 2.0f) * Rand.Range(0.8f, 1.2f); } } } if (sparks) { GameMain.ParticleManager.CreateParticle("spark", worldPosition, Rand.Vector(Rand.Range(500.0f, 800.0f)), 0.0f, hull); } } if (flash) { float displayRange = flashRange.HasValue ? flashRange.Value : attack.Range; if (displayRange < 0.1f) { return; } var light = new LightSource(worldPosition, displayRange, Color.LightYellow, null); CoroutineManager.StartCoroutine(DimLight(light)); } }
/** * Update the light list for this scene. * * @param lights array of light source objects */ public void setLightList(LightSource[] lights) { lightServer.setLights(lights); }
/// <summary> /// Remove a light from the list. /// </summary> /// <param name="light"></param> public void Remove(LightSource light) { lights.Remove(light); }
private void OnConsumedLightSource(LightSource consumedLightSource) { // If the player ate a fish if (consumedLightSource.CompareTag("Fish")) { FlashColor(probeColorEatFish, eatFlashDuration); } // If the player collected a pickup (yellow ball) if (consumedLightSource.CompareTag("Pickup")) { FlashColor(probeColorEatPickup, eatFlashDuration); } }
/// <summary> /// Called when the player is hit by a light source that is stronger than him /// </summary> public override void Knockback(LightSource enemyLightSource) { // Calculate a knockback force pushing the player away from the enemy fish Vector2 distance = (Transform.position - enemyLightSource.Transform.position); Vector2 knockback = distance.normalized * knockbackForce; Rigidbody.velocity = Vector3.zero; Rigidbody.AddForce(knockback, ForceMode.Impulse); // If the player was hit by a fish if (enemyLightSource.CompareTag("Fish")) { // Instantiate hit particles GameObject.Instantiate(fishHitParticles, transform.position, Quaternion.Euler(0, 0, 0)); FlashColor(probeColorHit, hitFlashDuration); // Rumble the controller when the player hits a fish. controllerRumble.PlayerHitByFish(); } // The player was just hit lastTimeHit = Time.time; }
public static void BuildCastle(Position center, int radius, int height, Block.BlockType blockType, Facing frontFace) { //make sure diagonal positions are valid if (!WorldData.IsValidBlockLocation(center.X - radius, center.Y, center.Z - radius)) return; if (!WorldData.IsValidBlockLocation(center.X + radius, center.Y, center.Z + radius)) return; //clear area with air WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z - radius), new Position(center.X + radius, center.Y + height - 1, center.Z + radius), Block.BlockType.Air, true); //front wall WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z + radius), new Position(center.X + radius, center.Y + height - 1, center.Z + radius), blockType, true); //back wall WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z - radius), new Position(center.X + radius, center.Y + height - 1, center.Z - radius), blockType, true); //left wall WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z - radius), new Position(center.X - radius, center.Y + height - 1, center.Z + radius), blockType, true); //right wall WorldData.PlaceCuboid(new Position(center.X + radius, center.Y, center.Z - radius), new Position(center.X + radius, center.Y + height - 1, center.Z + radius), blockType, true); //front and back tops for (var x = center.X - radius; x <= center.X + radius; x += 2) { WorldData.PlaceBlock(new Position(x, center.Y + height, center.Z + radius), blockType, true); WorldData.PlaceBlock(new Position(x, center.Y + height, center.Z - radius), blockType, true); } //side tops for (var z = center.Z - radius; z <= center.Z + radius; z += 2) { WorldData.PlaceBlock(new Position(center.X + radius, center.Y + height, z), blockType, true); WorldData.PlaceBlock(new Position(center.X - radius, center.Y + height, z), blockType, true); } //top wood floor WorldData.PlaceCuboid(new Position(center.X - radius + 1, center.Y + height - 2, center.Z - radius + 1), new Position(center.X + radius - 1, center.Y + height - 2, center.Z + radius - 1), Block.BlockType.WoodTile2, true); //door/lights Position doorBottom = center; Position outsideLight1; Position outsideLight2; switch (frontFace) { case Facing.North: doorBottom.Z -= radius; outsideLight1 = doorBottom; outsideLight1.Z--; outsideLight2 = outsideLight1; outsideLight1.X--; outsideLight2.X++; break; case Facing.East: doorBottom.X += radius; outsideLight1 = doorBottom; outsideLight1.X++; outsideLight2 = outsideLight1; outsideLight1.Z--; outsideLight2.Z++; break; case Facing.South: doorBottom.Z += radius; outsideLight1 = doorBottom; outsideLight1.Z++; outsideLight2 = outsideLight1; outsideLight1.X--; outsideLight2.X++; break; default: doorBottom.X -= radius; outsideLight1 = doorBottom; outsideLight1.X--; outsideLight2 = outsideLight1; outsideLight1.Z--; outsideLight2.Z++; break; } outsideLight1.Y += 2; outsideLight2.Y += 2; WorldData.PlaceCuboid(doorBottom, new Position(doorBottom.X, doorBottom.Y + 1, doorBottom.Z), Block.BlockType.Air, true); //clear space for door //add lights //todo: downside to this is its causing extra chunk queues and lightbox rebuilds, only for structure builds so not a huge deal for now //-clients are independently adding the lightsources, so id's might not match with server, for now theres no reason requiring them to match //-another quirk is if the location ends up not being valid, the client will get an error msg and not know why if this came from the server //-eventually may want a way for the AddStructure packet to include them, structures might get built containing many static items... if (WorldData.IsValidStaticItemPosition(outsideLight1)) { var ls1 = new LightSource(ref outsideLight1, LightSourceType.Lantern, frontFace.ToFace().ToOpposite()); new LightSource(ref ls1.Coords, ls1.Type, ls1.AttachedToFace, ls1.Id); } if (WorldData.IsValidStaticItemPosition(outsideLight2)) { var ls2 = new LightSource(ref outsideLight2, LightSourceType.Lantern, frontFace.ToFace().ToOpposite()); new LightSource(ref ls2.Coords, ls2.Type, ls2.AttachedToFace, ls2.Id); } }
public static void BuildCastle(Position center, int radius, int height, Block.BlockType blockType, Facing frontFace) { //make sure diagonal positions are valid if (!WorldData.IsValidBlockLocation(center.X - radius, center.Y, center.Z - radius)) { return; } if (!WorldData.IsValidBlockLocation(center.X + radius, center.Y, center.Z + radius)) { return; } //clear area with air WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z - radius), new Position(center.X + radius, center.Y + height - 1, center.Z + radius), Block.BlockType.Air, true); //front wall WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z + radius), new Position(center.X + radius, center.Y + height - 1, center.Z + radius), blockType, true); //back wall WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z - radius), new Position(center.X + radius, center.Y + height - 1, center.Z - radius), blockType, true); //left wall WorldData.PlaceCuboid(new Position(center.X - radius, center.Y, center.Z - radius), new Position(center.X - radius, center.Y + height - 1, center.Z + radius), blockType, true); //right wall WorldData.PlaceCuboid(new Position(center.X + radius, center.Y, center.Z - radius), new Position(center.X + radius, center.Y + height - 1, center.Z + radius), blockType, true); //front and back tops for (var x = center.X - radius; x <= center.X + radius; x += 2) { WorldData.PlaceBlock(new Position(x, center.Y + height, center.Z + radius), blockType, true); WorldData.PlaceBlock(new Position(x, center.Y + height, center.Z - radius), blockType, true); } //side tops for (var z = center.Z - radius; z <= center.Z + radius; z += 2) { WorldData.PlaceBlock(new Position(center.X + radius, center.Y + height, z), blockType, true); WorldData.PlaceBlock(new Position(center.X - radius, center.Y + height, z), blockType, true); } //top wood floor WorldData.PlaceCuboid(new Position(center.X - radius + 1, center.Y + height - 2, center.Z - radius + 1), new Position(center.X + radius - 1, center.Y + height - 2, center.Z + radius - 1), Block.BlockType.WoodTile2, true); //door/lights Position doorBottom = center; Position outsideLight1; Position outsideLight2; switch (frontFace) { case Facing.North: doorBottom.Z -= radius; outsideLight1 = doorBottom; outsideLight1.Z--; outsideLight2 = outsideLight1; outsideLight1.X--; outsideLight2.X++; break; case Facing.East: doorBottom.X += radius; outsideLight1 = doorBottom; outsideLight1.X++; outsideLight2 = outsideLight1; outsideLight1.Z--; outsideLight2.Z++; break; case Facing.South: doorBottom.Z += radius; outsideLight1 = doorBottom; outsideLight1.Z++; outsideLight2 = outsideLight1; outsideLight1.X--; outsideLight2.X++; break; default: doorBottom.X -= radius; outsideLight1 = doorBottom; outsideLight1.X--; outsideLight2 = outsideLight1; outsideLight1.Z--; outsideLight2.Z++; break; } outsideLight1.Y += 2; outsideLight2.Y += 2; WorldData.PlaceCuboid(doorBottom, new Position(doorBottom.X, doorBottom.Y + 1, doorBottom.Z), Block.BlockType.Air, true); //clear space for door //add lights //todo: downside to this is its causing extra chunk queues and lightbox rebuilds, only for structure builds so not a huge deal for now //-clients are independently adding the lightsources, so id's might not match with server, for now theres no reason requiring them to match //-another quirk is if the location ends up not being valid, the client will get an error msg and not know why if this came from the server //-eventually may want a way for the AddStructure packet to include them, structures might get built containing many static items... if (WorldData.IsValidStaticItemPosition(outsideLight1)) { var ls1 = new LightSource(ref outsideLight1, LightSourceType.Lantern, frontFace.ToFace().ToOpposite()); new LightSource(ref ls1.Coords, ls1.Type, ls1.AttachedToFace, ls1.Id); } if (WorldData.IsValidStaticItemPosition(outsideLight2)) { var ls2 = new LightSource(ref outsideLight2, LightSourceType.Lantern, frontFace.ToFace().ToOpposite()); new LightSource(ref ls2.Coords, ls2.Type, ls2.AttachedToFace, ls2.Id); } }
/// <summary> /// Rumbles the controller when the player eats a fish /// </summary> public void PlayerAteFish(LightSource fish) { StartCoroutine(Rumble(playerIndex, eatFishRumbleIntensity, eatFishRumbleIntensity, eatFishRumbleTime)); }
private void Form1_Load(object sender, EventArgs e) { Sphere = new Mesh(); Sphere.ToUVSphere(2, 30); Camera1 = new Camera(); Camera1.FOV = new Size(90, 90); Camera1.NormalAxis = Axes.Z; Camera1.VerticalAxis = Axes.Y; Camera1.RightAxis = Axes.X; Cubes = new List <Mesh> { new Mesh(), new Mesh(), new Mesh() }; Sun = new LightSource(); Sun.Position = new _Point(0, 10, 1); bm = new Bitmap(800, 800); Globals.BMSize = bm.Size; graphics = Graphics.FromImage(bm); for (int x = 0; x < bm.Width; x++) { for (int y = 0; y < bm.Height; y++) { bm.SetPixel(x, y, Color.White); } } CameraAngles = new Point(90, 90); /* * PSystem = new ParticleSystem(); * * PSystem.GenerateParticles(10, new _Point(0, 0, 4), 1, new _Point(0, 0, 0)); * PSystem.TimeInterval = .1; * PSystem.ParticleRadius = .01; * PSystem.AttractionRadius = .5; * PSystem.ParticleColor = Color.Black; * DrawParticles(PSystem); */ Cubes[0].ToCube(new _Point(-1, -1, 2), .8); Cubes[1].ToCube(new _Point(0, 1.5, 2), 1.5); Cubes[2].ToCube(new _Point(2, -1, 3), 1); foreach (Mesh cube in Cubes) { DrawMesh(cube); } //DrawMesh(Sphere); /* * for(int i=0; i<Sphere.Verts.Count; i++) * { * for (int j = 0; j < Sphere.Verts[i].Count; j++) * { * _Point point = Sphere.Verts[i][j]; * Sphere.Verts[i][j] = VectMath.Add(new _Point(0, -2, 4), point); * point = Sphere.Verts[i][j]; * if (convert2D(point).X > 0 && convert2D(point).X < bm.Width && convert2D(point).Y > 0 && convert2D(point).X < bm.Height) * { * * bm.SetPixel(convert2D(point).X, convert2D(point).Y, Color.Black); * } * } * } */ pictureBox1.Image = bm; }
private static void _fastToolTimer_Elapsed(object sender, ElapsedEventArgs e) { if (CurrentTool == ToolType.FastDestroy && !BlockCursorHost.Position.Equals(_prevFastPositionSent)) { _prevFastPositionSent = BlockCursorHost.Position; Game.InputHost.AddOrRemoveBlock(Block.BlockType.Air); } else if (CurrentTool == ToolType.FastBuild && !BlockCursorHost.PositionAdd.Equals(_prevFastPositionSent)) { _prevFastPositionSent = BlockCursorHost.PositionAdd; var buttonToolBlockType = _toolButtons[(int)ToolType.ToolBlockType]; if (buttonToolBlockType.BlockType > 0) //only add a block if a non air block type is selected { Game.InputHost.AddOrRemoveBlock(buttonToolBlockType.BlockType); } else if (buttonToolBlockType.LightSourceType.HasValue) { var position = BlockCursorHost.PositionAdd; if (WorldData.IsValidStaticItemPosition(position)) { var lightSource = new LightSource(ref position, buttonToolBlockType.LightSourceType.Value, BlockCursorHost.SelectedFace.ToOpposite()); new AddStaticItem(lightSource).Send(); } } } }
public void SetParameters(List <LightNode> globalLights, List <LightNode> localLights) { bool ambientSet = false; ClearBasicEffectLights(); lightSources.Clear(); LightNode lNode = null; Vector4 ambientLightColor = new Vector4(0, 0, 0, 1); // traverse the local lights in reverse order in order to get closest light sources // in the scene graph for (int i = localLights.Count - 1; i >= 0; i--) { lNode = localLights[i]; // only set the ambient light color if it's not set yet and not the default color (0, 0, 0, 1) if (!ambientSet && (!lNode.AmbientLightColor.Equals(ambientLightColor))) { ambientLightColor = lNode.AmbientLightColor; ambientSet = true; } if (lightSources.Count < MaxLights) { // skip the light source if not enabled or not a directional light if (!lNode.LightSource.Enabled || (lNode.LightSource.Type != LightType.Directional)) { continue; } LightSource source = new LightSource(); source.Diffuse = lNode.LightSource.Diffuse; tmpVec1 = lNode.LightSource.Direction; Matrix.CreateTranslation(ref tmpVec1, out tmpMat1); tmpMat2 = lNode.WorldTransformation; MatrixHelper.GetRotationMatrix(ref tmpMat2, out tmpMat2); Matrix.Multiply(ref tmpMat1, ref tmpMat2, out tmpMat3); source.Direction = tmpMat3.Translation; source.Specular = lNode.LightSource.Specular; lightSources.Add(source); // If there are already 3 lights, then skip other lights if (lightSources.Count >= MaxLights) { break; } } } // Next, traverse the global lights in normal order for (int i = 0; i < globalLights.Count; i++) { lNode = globalLights[i]; // only set the ambient light color if it's not set yet and not the default color (0, 0, 0, 1) if (!ambientSet && (!lNode.AmbientLightColor.Equals(ambientLightColor))) { ambientLightColor = lNode.AmbientLightColor; ambientSet = true; } if (lightSources.Count < MaxLights) { // skip the light source if not enabled or not a directional light if (!lNode.LightSource.Enabled || (lNode.LightSource.Type != LightType.Directional)) { continue; } LightSource source = new LightSource(); source.Diffuse = lNode.LightSource.Diffuse; tmpVec1 = lNode.LightSource.Direction; Matrix.CreateTranslation(ref tmpVec1, out tmpMat1); tmpMat2 = lNode.WorldTransformation; MatrixHelper.GetRotationMatrix(ref tmpMat2, out tmpMat2); Matrix.Multiply(ref tmpMat1, ref tmpMat2, out tmpMat3); source.Direction = tmpMat3.Translation; source.Specular = lNode.LightSource.Specular; lightSources.Add(source); // If there are already 3 lights, then skip other lights if (lightSources.Count >= MaxLights) { break; } } } ambientLight = Vector3Helper.GetVector3(ambientLightColor); if (lightSources.Count > 0) { DirectionalLight[] lights = { skinnedEffect.DirectionalLight0, skinnedEffect.DirectionalLight1, skinnedEffect.DirectionalLight2 }; int numLightSource = lightSources.Count; for (int i = 0; i < numLightSource; i++) { lights[i].Enabled = true; lights[i].DiffuseColor = Vector3Helper.GetVector3(lightSources[i].Diffuse); lights[i].Direction = lightSources[i].Direction; lights[i].SpecularColor = Vector3Helper.GetVector3(lightSources[i].Specular); } } skinnedEffect.AmbientLightColor = ambientLight; lightsChanged = true; }
/// <summary> /// Returns true if this LightSource can absorb the given LightSource /// Calculated by comparing the amount of energy in LightEnergy property of LightSources /// </summary> private bool CanAbsorb(LightSource otherLightSource) { if (!otherLightSource.CanBeAbsorbed()) { return false; } // If this light source has more energy than the other one, return true. This light source can absorb the given argument. if (canAbsorb && LightEnergy.CurrentEnergy > otherLightSource.LightEnergy.CurrentEnergy) { return true; } if (canAbsorb && !otherLightSource.canAbsorb) { return true; } // The player can always absorb a light source with LightSource.playerWillAlwaysAbsorb set to true if (this is Player && canAbsorb && otherLightSource.playerWillAlwaysAbsorb) { return true; } return false; }
/// <summary>Process a user entered slash command.</summary> /// <remarks> /// when a command is successful use 'return' to leave the function /// when a command is not succesful use 'break' for an invalid command msg to get displayed /// </remarks> public static void ProcessSlashCommand(string text) { if (text.Length <= 1) { AddSlashResult("Unknown command."); return;} LastSlashCommand = text; var args = text.TrimStart('/').ToLower().Split(' '); switch (args[0]) { case "?": case "help": case "commands": DisplayCommandHelp(); return; case "admin": if (ArgCountInvalid(2, args)) return; new PlayerOption(PlayerOption.OptionType.Admin, System.Text.Encoding.UTF8.GetBytes(args[1])).Send(); return; case "broadcast": if (Config.IsSinglePlayer) { AddSlashResult("Only available in Multiplayer."); return; } new ServerCommand(ServerCommandType.Broadcast).Send(); //this would still need a way to send the actual message return; case "clear": Game.UiHost.ClearChatMessages(); return; case "cr": case "creative": if (args.Length == 1) { AddSlashResult(string.Format("Creative mode {0}.", Config.CreativeMode ? "On" : "Off")); return; } if (ArgCountInvalid(2, args)) return; switch (args[1]) { case "on": new PlayerOption(PlayerOption.OptionType.Creative, BitConverter.GetBytes(1)).Send(); return; case "off": new PlayerOption(PlayerOption.OptionType.Creative, BitConverter.GetBytes(0)).Send(); return; } break; case "ci": case "chunk": var chunk = WorldData.Chunks[Game.Player.Coords]; AddSlashResult(string.Format("Chunk {0}: VBOs {1}; Primitives {2}; Deepest transparent level {3}; Highest non air level {4}", chunk.Coords, chunk.VboCount, chunk.PrimitiveCount, chunk.DeepestTransparentLevel, chunk.HighestNonAirLevel)); return; case "cu": case "chunkupdates": if (ArgCountInvalid(2, args)) return; switch (args[1]) { case "on": Settings.ChunkUpdatesDisabled = false; AddSlashResult("Chunk updates enabled."); return; case "off": Settings.ChunkUpdatesDisabled = true; AddSlashResult("Chunk updates disabled."); return; } break; case "heightmap": if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } AddSlashResult(string.Format("HeightMap value for {0} is {1}", BlockCursorHost.Position, WorldData.Chunks[BlockCursorHost.Position].HeightMap[BlockCursorHost.Position.X % Chunk.CHUNK_SIZE, BlockCursorHost.Position.Z % Chunk.CHUNK_SIZE])); return; case "id": AddSlashResult(string.Format("UserName: {0} (Id {1})", Game.Player.UserName, Game.Player.Id)); return; case "invhack": for (int i = 0; i < Game.Player.Inventory.Length; i++) Game.Player.Inventory[i] += 200; return; case "itemcount": if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } AddSlashResult(string.Format("World contains {0} items.", WorldData.GameItems.Count)); return; case "lantern": var position = BlockCursorHost.PositionAdd; if (WorldData.IsValidStaticItemPosition(position)) { var lantern = new LightSource(ref position, LightSourceType.Lantern, BlockCursorHost.SelectedFace.ToOpposite()); new AddStaticItem(lantern).Send(); } return; case "loc": case "location": AddSlashResult(string.Format("{0}:", Game.Player.UserName)); AddSlashResult(string.Format(" Block {0}", Game.Player.Coords)); AddSlashResult(string.Format(" Coords (x={0}, y={1}, z={2})", Game.Player.Coords.Xf, Game.Player.Coords.Yf, Game.Player.Coords.Zf)); AddSlashResult(string.Format(" Dir ({0}) Pitch ({1})", MathHelper.RadiansToDegrees(Game.Player.Coords.Direction), MathHelper.RadiansToDegrees(Game.Player.Coords.Pitch))); return; case "maxtexturesize": int mts; GL.GetInteger(GetPName.MaxTextureSize, out mts); AddSlashResult("Max texture size: " + mts); return; case "m": case "move": if (ArgCountInvalid(3, args)) return; if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } short moveTo; if (!short.TryParse(args[2], out moveTo)) break; var newCoords = Game.Player.Coords; switch (args[1]) { case "x": newCoords.Xf = moveTo; break; case "y": newCoords.Yf = moveTo; break; case "z": newCoords.Zf = moveTo; break; } if (!newCoords.Equals(Game.Player.Coords)) { if (newCoords.IsValidPlayerLocation) { Game.Player.Coords = newCoords; return; } AddSlashResult("Invalid location."); return; } break; case "movechunk": case "movetochunk": if (ArgCountInvalid(3, args)) return; if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } byte chunkX, chunkZ; if (!byte.TryParse(args[1], out chunkX) || !byte.TryParse(args[2], out chunkZ)) break; var newChunkMoveCoords = new Coords(chunkX * Chunk.CHUNK_SIZE + Chunk.CHUNK_SIZE / 2, Chunk.CHUNK_HEIGHT, chunkZ * Chunk.CHUNK_SIZE + Chunk.CHUNK_SIZE / 2, Game.Player.Coords.Direction, Game.Player.Coords.Pitch); if (newChunkMoveCoords.IsValidPlayerLocation) { Game.Player.Coords = newChunkMoveCoords; return; } break; case "music": if (ArgCountInvalid(2, args)) return; if (!Config.SoundEnabled) { AddSlashResult("Sound is disabled."); return; } switch (args[1]) { case "on": if (!Config.MusicEnabled) { Config.MusicEnabled = true; Config.Save(); Sounds.Music.StartMusic(); } AddSlashResult("Music enabled."); return; case "off": Config.MusicEnabled = false; Config.Save(); Sounds.Music.StopMusic(); AddSlashResult("Music disabled."); return; } break; case "opengl": AddSlashResult(Utilities.Diagnostics.OpenGlInfo()); return; case "outline": Settings.OutlineChunks = !Settings.OutlineChunks; WorldData.Chunks.QueueAllWithinViewDistance(); AddSlashResult(string.Format("Chunk outlining {0}.", Settings.OutlineChunks ? "enabled" : "disabled")); return; case "phack": case "playerhack": NetworkClient.Players.TryAdd(5000, new Player(5000, "Tester McGee", new Coords(Game.Player.Coords.Xf - 1, Game.Player.Coords.Yf, Game.Player.Coords.Zf, Game.Player.Coords.Direction, Game.Player.Coords.Pitch))); NetworkClient.Players.TryAdd(5001, new Player(5001, "Tester McGee2", new Coords(Game.Player.Coords.Xf + 3, Game.Player.Coords.Yf, Game.Player.Coords.Zf, Game.Player.Coords.Direction + MathHelper.Pi, Game.Player.Coords.Pitch))); return; case "raiseexception": //-can be used to test the msgbox error handler in release mode //-can be used to test obfuscation was done properly by looking at the stack trace displayed in release mode throw new Exception("Manually created exception from slash command."); case "server": AddSlashResult(Config.IsSinglePlayer ? "Not applicable in single player mode." : string.Format("{0}:{1}", NetworkClient.ServerIp, NetworkClient.ServerPort)); return; case "serverversion": if (Config.IsSinglePlayer) { AddSlashResult("Not applicable in single player mode."); return; } new ServerCommand(ServerCommandType.ServerVersion).Send(); return; case "sp": case "speed": if (ArgCountInvalid(2, args)) return; switch (args[1]) { case "on": new PlayerOption(PlayerOption.OptionType.Speed, BitConverter.GetBytes(5)).Send(); return; case "off": new PlayerOption(PlayerOption.OptionType.Speed, BitConverter.GetBytes(1)).Send(); return; default: int multiplier; if (int.TryParse(args[1], out multiplier)) { new PlayerOption(PlayerOption.OptionType.Speed, BitConverter.GetBytes(multiplier)).Send(); return; } break; } break; case "sound": if (ArgCountInvalid(2, args)) return; switch (args[1]) { case "on": Config.SoundEnabled = true; Sounds.Audio.LoadSounds(); AddSlashResult("Sound enabled."); return; case "off": Config.SoundEnabled = false; Sounds.Audio.Dispose(); AddSlashResult("Sound disabled."); return; } break; case "stuck": Game.Player.Coords = new Coords(WorldData.SizeInBlocksX / 2f, Chunk.CHUNK_HEIGHT, WorldData.SizeInBlocksZ / 2f, Game.Player.Coords.Direction, Game.Player.Coords.Pitch); return; case "sun": if (ArgCountInvalid(2, 3, args)) return; if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } switch (args[1]) { case "loc": case "info": case "position": case "speed": AddSlashResult(string.Format("Sun: Degrees {0}, Strength {1}, Speed {2}", MathHelper.RadiansToDegrees(SkyHost.SunAngleRadians), SkyHost.SunLightStrength, SkyHost.SpeedMultiplier)); return; case "move": case "degrees": if (ArgCountInvalid(3, args)) return; ushort sunDegrees; if (ushort.TryParse(args[2], out sunDegrees) && sunDegrees <= 360) { new ServerCommand(ServerCommandType.MoveSun, sunDegrees).Send(); return; } AddSlashResult("Invalid degrees."); return; } //following commands only work in single player if (!Config.IsSinglePlayer) { AddSlashResult("Cannot change sun speed in Multiplayer."); return; } switch (args[1]) { case "+": case "faster": SkyHost.SpeedMultiplier *= 2; AddSlashResult("Sun speed increased."); return; case "-": case "slower": SkyHost.SpeedMultiplier /= 2; AddSlashResult("Sun speed decreased."); return; case "default": case "start": SkyHost.SpeedMultiplier = SkyHost.DEFAULT_SPEED_MULTIPLIER; AddSlashResult("Sun reset to default speed."); return; case "stop": SkyHost.SpeedMultiplier = 0; AddSlashResult("Sun stopped."); return; } break; case "tp": case "teleport": if (ArgCountInvalid(2, args)) return; int playerId; if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); } else if (!int.TryParse(args[1], out playerId) || !NetworkClient.Players.ContainsKey(playerId)) { AddSlashResult("Invalid player id."); } else if(playerId == Game.Player.Id) { AddSlashResult("Cannot teleport to yourself."); } else { Game.Player.Coords = NetworkClient.Players[playerId].Coords; } return; case "throwexception": new ThrowException().Send(); return; case "time": AddSlashResult(string.Format("Time in game: {0:h:mm tt}", SkyHost.Time)); return; case "ui": if (ArgCountInvalid(2, args)) return; switch (args[1]) { case "on": Settings.UiDisabled = false; AddSlashResult("UI enabled."); return; case "off": Settings.UiDisabled = true; AddSlashResult("UI disabled."); return; } break; case "username": AddSlashResult(Game.Player.UserName); return; case "ver": case "version": AddSlashResult(string.Format("Version {0}", Settings.VersionDisplay)); return; case "vd": case "view": case "viewdistance": switch (args.Length) { case 1: AddSlashResult(string.Format("{0} ({1} blocks)", Config.ViewDistance, Settings.ZFar)); return; case 2: //view distance can be changed by either entering the string view distance or the numeric enum value //the check of enum length is needed because the TryParse lets numeric values through that are larger then the number of values strangely ViewDistance vd; if (Enum.TryParse(args[1], true, out vd) && (int)vd < Enum.GetValues(typeof(ViewDistance)).Length) { Utilities.Misc.ChangeViewDistance(vd); AddSlashResult(string.Format("{0} ({1} blocks)", Config.ViewDistance, Settings.ZFar)); } else { AddSlashResult("Unknown view distance."); } return; } break; case "vsync": Config.VSync = !Config.VSync; Settings.Game.VSync = Config.VSync ? VSyncMode.On : VSyncMode.Off; AddSlashResult("VSync: " + Settings.Game.VSync); return; case "walloftext": for (int i = 0; i < 10; i++) AddSlashResult(new string('X', 80)); return; case "who": switch (args.Length) { case 1: if (NetworkClient.Players.Count > 1) AddSlashResult(string.Format("{0} players connected:", NetworkClient.Players.Count)); foreach (var player in NetworkClient.Players.Values) AddSlashResult(player); return; case 2: foreach (var player in NetworkClient.Players.Values.Where(player => player.UserName.Equals(args[1], StringComparison.InvariantCultureIgnoreCase))) { AddSlashResult(player); return; } AddSlashResult("Player not found."); return; } break; case "wireframe": if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } int mode; GL.GetInteger(GetPName.PolygonMode, out mode); GL.PolygonMode(MaterialFace.FrontAndBack, mode == (int)PolygonMode.Fill ? PolygonMode.Line : PolygonMode.Fill); return; case "worldname": AddSlashResult(string.Format("World name: {0}", Settings.WorldName)); return; case "worldsave": if (Config.IsSinglePlayer) { System.Threading.Tasks.Task.Factory.StartNew(WorldData.SaveToDisk).ContinueWith(task => AddSlashResult(string.Format("World saved: {0}", Settings.WorldFilePath))); } else { AddSlashResult("Cannot save in Multiplayer."); } return; case "worldsize": case "size": new ServerCommand(ServerCommandType.WorldSize).Send(); return; case "worldtype": AddSlashResult(string.Format("World type: {0}", WorldData.WorldType)); return; case "xmldump": if (!Config.CreativeMode) { AddSlashResult("Must be in Creative Mode."); return; } var xml = WorldSettings.GetXmlByteArray(); using (var file = new FileStream(Path.Combine(Config.SaveDirectory.FullName, Settings.WorldName) + ".xml", FileMode.Create)) { file.Write(xml, 0, xml.Length); AddSlashResult("Dumped XML to " + file.Name); file.Close(); } return; } AddSlashResult("Invalid command."); }
//Method to rebuild lighting variables private void Rebuild() { LightSource blanklight; //Ensure an empty light entity exists to fill empty slots blanklight.lightPos = new Vector4(0f, 0f, 0f, 1f); blanklight.lightCol = new Vector4(0f, 0f, 0f, 1f); //It may be ugly, but it works every time for (int i = 0; i < lights.Count(); i++) { if (i == 0) { l1 = lights[i]; } if (i == 1) { l2 = lights[i]; } if (i == 2) { l3 = lights[i]; } if (i == 3) { l4 = lights[i]; } if (i == 4) { l5 = lights[i]; } if (i == 5) { l6 = lights[i]; } if (i == 6) { l7 = lights[i]; } if (i == 7) { l8 = lights[i]; } if (i == 8) { l9 = lights[i]; } if (i == 9) { l10 = lights[i]; } if (i == 10) { l11 = lights[i]; } if (i == 11) { l12 = lights[i]; } if (i == 12) { l13 = lights[i]; } if (i == 13) { l14 = lights[i]; } if (i == 14) { l15 = lights[i]; } } //Fill any remaining variables with empty or "off" lights for (int i = lights.Count(); i < 15; i++) { if (i == 0) { l1 = blanklight; } if (i == 1) { l2 = blanklight; } if (i == 2) { l3 = blanklight; } if (i == 3) { l4 = blanklight; } if (i == 4) { l5 = blanklight; } if (i == 5) { l6 = blanklight; } if (i == 6) { l7 = blanklight; } if (i == 7) { l8 = blanklight; } if (i == 8) { l9 = blanklight; } if (i == 9) { l10 = blanklight; } if (i == 10) { l11 = blanklight; } if (i == 11) { l12 = blanklight; } if (i == 12) { l13 = blanklight; } if (i == 13) { l14 = blanklight; } if (i == 14) { l15 = blanklight; } } }
public void put(string name, LightSource light) { renderObjects[name] = new RenderObjectHandle(light); }
void Start() { animator = gameObject.GetComponent<Animator>(); shadowScript = shadow.GetComponent<shadowMovement>(); lightSourceScript = shadow.GetComponent<LightSource>(); }
public void setLights(LightSource[] lights) { this.lights = lights; }
void Start() { toPoint = GetComponent <Camera>(); lightSource = GameObject.FindObjectOfType <LightSource>(); }