public override void OnGameTick(float deltaTime)
        {
            if (entity.Pos.Y < -30)
            {
                entity.ReceiveDamage(new DamageSource()
                {
                    Source = EnumDamageSource.Void,
                    Type   = EnumDamageType.Gravity
                }, 4);
            }

            secondsSinceLastUpdate += deltaTime;

            if (secondsSinceLastUpdate >= 1)
            {
                secondsSinceLastUpdate = 0;

                if (entity.Alive && Health < MaxHealth)
                {
                    float recoverySpeed = 0.01f;

                    EntityBehaviorHunger ebh = entity.GetBehavior <EntityBehaviorHunger>();

                    if (ebh != null)
                    {
                        EntityPlayer plr = (EntityPlayer)entity;
                        if (plr != null && entity.World.PlayerByUid(plr.PlayerUID).WorldData.CurrentGameMode == EnumGameMode.Creative)
                        {
                            return;
                        }

                        // When below 75% satiety, autoheal starts dropping
                        recoverySpeed = GameMath.Clamp(0.01f * ebh.Saturation / ebh.MaxSaturation * 1 / 0.75f, 0, 0.01f);

                        ebh.ConsumeSaturation(150f * recoverySpeed);
                    }

                    Health = Math.Min(Health + recoverySpeed, MaxHealth);
                }

                int rainy = entity.World.BlockAccessor.GetRainMapHeightAt((int)entity.ServerPos.X, (int)entity.ServerPos.Z);
                if (entity.World.Side == EnumAppSide.Server && entity is EntityPlayer && rainy <= entity.ServerPos.Y)
                {
                    WeatherSystemBase wsys = entity.Api.ModLoader.GetModSystem <WeatherSystemBase>();
                    var state = wsys.GetPrecipitationState(entity.ServerPos.XYZ);

                    if (state != null && state.ParticleSize > 0.6 && state.Type == EnumPrecipitationType.Hail && entity.World.Rand.NextDouble() < state.Level / 2)
                    {
                        entity.ReceiveDamage(new DamageSource()
                        {
                            Source = EnumDamageSource.Weather,
                            Type   = EnumDamageType.BluntAttack
                        }, (float)state.ParticleSize / 15f);
                    }
                }
            }
        }
 float getPrecipNoise(double posX, double posZ, double totalDays, float wgenRain)
 {
     return((float)GameMath.Max(
                precipitationNoise.Noise(posX / 9 / 2 + totalDays * 18, posZ / 9 / 2, totalDays * 4) * 1.6f -
                GameMath.Clamp(precipitationNoiseSub.Noise(posX / 4 / 2 + totalDays * 24, posZ / 4 / 2, totalDays * 6) * 5 - 1 - wgenRain, 0, 1)
                + wgenRain,
                0
                ));
 }
Beispiel #3
0
        public override void OnBeforeGameRender(float dt)
        {
            if (!capi.IsGamePaused)
            {
                var            eplr       = capi.World.Player;
                ITreeAttribute healthTree = eplr.Entity.WatchedAttributes.GetTreeAttribute("health");
                float          healthRel  = healthTree == null ? 1 : healthTree.GetFloat("currenthealth") / healthTree.GetFloat("maxhealth");

                float f             = Math.Max(0, (0.23f - healthRel) * 1 / 0.18f);
                float lowHealthness = 0;

                if (f > 0)
                {
                    float ellapseSec = (float)(capi.InWorldEllapsedMilliseconds / 1000.0);

                    float bla = (float)noisegen.Noise(12412, ellapseSec / 2) * 0.5f + (float)Math.Pow(Math.Abs(GameMath.Sin(ellapseSec * 1 / 0.7f)), 30) * 0.5f;
                    lowHealthness = Math.Min(f * 1.5f, 1) * (bla * 0.75f + 0.5f);

                    if (eplr.Entity.Alive)
                    {
                        capi.Render.ShaderUniforms.ExtraSepia = GameMath.Clamp(f * (float)noisegen.Noise(0, ellapseSec / 3) * 1.2f, 0, 1.2f);
                        if (capi.World.Rand.NextDouble() < 0.01)
                        {
                            capi.World.AddCameraShake(0.15f * f);
                        }

                        capi.Input.MouseYaw += f * (float)(noisegen.Noise(76, ellapseSec / 50) - 0.5f) * 0.003f;

                        float dp = f * (float)(noisegen.Noise(ellapseSec / 50, 987) - 0.5f) * 0.003f;;

                        eplr.Entity.Pos.Pitch += dp;
                        capi.Input.MousePitch += dp;
                    }
                }
                else
                {
                    capi.Render.ShaderUniforms.ExtraSepia = 0;
                }

                int val = GameMath.Clamp((int)(damangeVignettingUntil - capi.ElapsedMilliseconds), 0, duration);

                capi.Render.ShaderUniforms.DamageVignetting = GameMath.Clamp(GameMath.Clamp(strength / 2, 0.5f, 3.5f) * ((float)val / Math.Max(1, duration)) + lowHealthness, 0, 1.5f);

                float freezing = eplr.Entity.WatchedAttributes.GetFloat("freezingEffectStrength", 0);

                curFreezingVal += (freezing - curFreezingVal) * dt;

                if (curFreezingVal > 0.1 && eplr.CameraMode == EnumCameraMode.FirstPerson)
                {
                    float ellapseSec = (float)(capi.InWorldEllapsedMilliseconds / 1000.0);
                    capi.Input.MouseYaw += capi.Settings.Float["cameraShakeStrength"] * (float)(Math.Max(0, noisegen.Noise(ellapseSec, 12) - 0.4f) * Math.Sin(ellapseSec * 90) * 0.01) * GameMath.Clamp(curFreezingVal * 3, 0, 1);
                }

                capi.Render.ShaderUniforms.FrostVignetting = curFreezingVal;
            }
        }
Beispiel #4
0
        public void TickEntityPhysics(EntityPos pos, EntityControls controls, float dt)
        {
            IBlockAccessor blockAccessor = entity.World.BlockAccessor;

            foreach (EntityLocomotion locomotor in Locomotors)
            {
                if (locomotor.Applicable(entity, pos, controls))
                {
                    locomotor.Apply(dt, entity, pos, controls);
                }
            }

            EntityAgent agent = entity as EntityAgent;

            if (agent?.MountedOn != null)
            {
                pos.SetFrom(agent.MountedOn.MountPosition);
                pos.Motion.X = 0;
                pos.Motion.Y = 0;
                pos.Motion.Z = 0;
                return;
            }


            pos.Motion.X = GameMath.Clamp(pos.Motion.X, -10, 10);
            pos.Motion.Y = GameMath.Clamp(pos.Motion.Y, -10, 10);
            pos.Motion.Z = GameMath.Clamp(pos.Motion.Z, -10, 10);

            if (!controls.NoClip)
            {
                DisplaceWithBlockCollision(pos, controls, dt);
            }
            else
            {
                pos.X += pos.Motion.X;
                pos.Y += pos.Motion.Y;
                pos.Z += pos.Motion.Z;

                entity.Swimming     = false;
                entity.FeetInLiquid = false;
                entity.OnGround     = false;
            }



            // Shake the player violently when falling at high speeds

            /*if (movedy < -50)
             * {
             *  pos.X += (rand.NextDouble() - 0.5) / 5 * (-movedy / 50f);
             *  pos.Z += (rand.NextDouble() - 0.5) / 5 * (-movedy / 50f);
             * }
             */

            //return result;
        }
Beispiel #5
0
        public override void OnCollideWithLiquid()
        {
            if (motionBeforeCollide.Y <= 0)
            {
                LocalPos.Motion.Y       = GameMath.Clamp(motionBeforeCollide.Y * -0.5f, -0.1f, 0.1f);
                PositionBeforeFalling.Y = Pos.Y + 1;
            }

            base.OnCollideWithLiquid();
        }
Beispiel #6
0
 public virtual double GetCloudDensityAt(int dx, int dz)
 {
     try
     {
         return(GameMath.Clamp(State.nowbaseThickness + CloudDensityNoiseCache[GameMath.Clamp(dx + NoisePadding, 0, tilesPerRegion - 1), GameMath.Clamp(dz + NoisePadding, 0, tilesPerRegion - 1)], 0, 1) * State.nowThicknessMul);
     } catch (Exception)
     {
         throw new Exception(string.Format("{0}/{1} is out of range. Width/Height: {2}/{3}", dx, dz, CloudDensityNoiseCache.GetLength(0), CloudDensityNoiseCache.GetLength(1)));
     }
 }
Beispiel #7
0
        public override bool OnHeldInteractStep(float secondsUsed, IItemSlot slot, IEntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            if (byEntity.World is IClientWorldAccessor)
            {
                slot.Itemstack.TempAttributes.SetInt("renderVariant", GameMath.Clamp((int)Math.Ceiling(secondsUsed * 4), 0, 3));
            }


            return(true);
        }
        protected override void loadYPosAndThickness(IMapChunk heremapchunk, int lx, int lz, BlockPos pos, double distanceToEdge)
        {
            double curTh = depoitThickness * GameMath.Clamp(distanceToEdge * 2 - 0.2, 0, 1);

            hereThickness = (int)curTh + ((DepositRand.NextDouble() < (curTh - (int)curTh)) ? 1 : 0);

            int yOff = (int)getDepositYDistort(targetPos, lx, lz, step, heremapchunk);

            pos.Y = posyi + yOff;
        }
Beispiel #9
0
        public void OnRenderFrame(float deltaTime, EnumRenderStage stage)
        {
            if (workItemMeshRef == null)
            {
                return;
            }
            if (stage == EnumRenderStage.AfterFinalComposition)
            {
                RenderRecipeOutLine();
                return;
            }

            IRenderAPI           rpi         = api.Render;
            IClientWorldAccessor worldAccess = api.World;
            Vec3d     camPos = worldAccess.Player.Entity.CameraPos;
            EntityPos plrPos = worldAccess.Player.Entity.Pos;
            int       temp   = (int)ingot.Collectible.GetTemperature(api.World, ingot);

            Vec4f lightrgbs = worldAccess.BlockAccessor.GetLightRGBs(pos.X, pos.Y, pos.Z);

            float[] glowColor = ColorUtil.GetIncandescenceColorAsColor4f(temp);
            lightrgbs[0] += 2 * glowColor[0];
            lightrgbs[1] += 2 * glowColor[1];
            lightrgbs[2] += 2 * glowColor[2];



            rpi.GlDisableCullFace();

            IStandardShaderProgram prog = rpi.StandardShader;

            prog.Use();
            rpi.BindTexture2d(texId);
            prog.RgbaAmbientIn    = rpi.AmbientColor;
            prog.RgbaFogIn        = rpi.FogColor;
            prog.FogMinIn         = rpi.FogMin;
            prog.DontWarpVertices = 0;
            prog.AddRenderFlags   = 0;
            prog.FogDensityIn     = rpi.FogDensity;
            prog.RgbaTint         = ColorUtil.WhiteArgbVec;
            prog.RgbaLightIn      = lightrgbs;
            prog.RgbaBlockIn      = ColorUtil.WhiteArgbVec;
            prog.ExtraGlow        = GameMath.Clamp((temp - 700) / 2, 0, 255);
            prog.ModelMatrix      = ModelMat
                                    .Identity()
                                    .Translate(pos.X - camPos.X, pos.Y - camPos.Y, pos.Z - camPos.Z)
                                    .Values
            ;


            prog.ViewMatrix       = rpi.CameraMatrixOriginf;
            prog.ProjectionMatrix = rpi.CurrentProjectionMatrix;
            rpi.RenderMesh(workItemMeshRef);
            prog.Stop();
        }
Beispiel #10
0
        protected void Event_OnGetClimate(ref ClimateCondition climate, BlockPos pos, EnumGetClimateMode mode = EnumGetClimateMode.WorldGenValues, double totalDays = 0)
        {
            if (mode == EnumGetClimateMode.WorldGenValues)
            {
                return;
            }
            float rainCloudness = GetRainCloudness(climate, pos.X + 0.5, pos.Z + 0.5, totalDays);

            climate.Rainfall         = GameMath.Clamp(rainCloudness - 0.5f, 0, 1);
            climate.RainCloudOverlay = GameMath.Clamp(rainCloudness, 0, 1);
        }
Beispiel #11
0
 public override void OnEntityCollide(IWorldAccessor world, Entity entity, BlockPos pos, BlockFacing facing, Vec3d collideSpeed, bool isImpact)
 {
     if (isImpact && facing.Axis == EnumAxis.Y)
     {
         if (Sounds?.Break != null && System.Math.Abs(collideSpeed.Y) > 0.2)
         {
             world.PlaySoundAt(Sounds.Break, entity.Pos.X, entity.Pos.Y, entity.Pos.Z);
         }
         entity.Pos.Motion.Y = GameMath.Clamp(-entity.Pos.Motion.Y * 0.8, -0.5, 0.5);
     }
 }
        private void onClientTick50ms(float dt)
        {
            if (processComplete || !structureComplete)
            {
                return;
            }

            receivesHeatSmooth = GameMath.Clamp(receivesHeatSmooth + (receivesHeat ? dt / 10 : -dt / 3), 0, 1);

            if (receivesHeatSmooth == 0)
            {
                return;
            }

            Random rnd = Api.World.Rand;

            for (int i = 0; i < Entity.FireParticleProps.Length; i++)
            {
                int index = Math.Min(Entity.FireParticleProps.Length - 1, Api.World.Rand.Next(Entity.FireParticleProps.Length + 1));
                AdvancedParticleProperties particles = Entity.FireParticleProps[index];

                for (int j = 0; j < particlePositions.Length; j++)
                {
                    BlockPos pos = particlePositions[j];

                    if (j >= 6)
                    {
                        particles = smokeParticles;
                        particles.Quantity.avg = 0.2f;
                        particles.basePos.Set(pos.X + 0.5, pos.Y + 0.75, pos.Z + 0.5);
                        particles.Velocity[1].avg  = (float)(0.3 + 0.3 * rnd.NextDouble());
                        particles.PosOffset[1].var = 0.2f;
                        particles.Velocity[0].avg  = (float)(rnd.NextDouble() - 0.5) / 4;
                        particles.Velocity[2].avg  = (float)(rnd.NextDouble() - 0.5) / 4;
                    }
                    else
                    {
                        particles.Quantity.avg = GameMath.Sqrt(0.5f * (index == 0 ? 0.5f : (index == 1 ? 5 : 0.6f))) / 2f;
                        particles.basePos.Set(pos.X + 0.5, pos.Y + 0.5, pos.Z + 0.5);
                        particles.Velocity[1].avg  = (float)(0.5 + 0.5 * rnd.NextDouble());
                        particles.PosOffset[1].var = 1;
                        particles.Velocity[0].avg  = (float)(rnd.NextDouble() - 0.5) / 2;
                        particles.Velocity[2].avg  = (float)(rnd.NextDouble() - 0.5) / 2;
                    }


                    particles.PosOffset[0].var = 0.49f;
                    particles.PosOffset[2].var = 0.49f;


                    Api.World.SpawnParticles(particles);
                }
            }
        }
        public override void Update(float dt, ref float accuracy)
        {
            accuracy = GameMath.Clamp((float)Math.Pow(SecondsSinceAimStart * 1.1, 1.5), 0, 0.9f);

            accuracy -= GameMath.Clamp((SecondsSinceAimStart - 1.75f) / 3, 0, 0.3f);

            if (SecondsSinceAimStart >= 0.75f)
            {
                accuracy += GameMath.Sin(SecondsSinceAimStart * 8) / 80f;
            }
        }
Beispiel #14
0
        override internal void OnDeserialized()
        {
            base.OnDeserialized();

            // Only one collision/selectionbox
            if (CollisionBoxR != null)
            {
                CollisionBoxes = ToCuboidf(CollisionBoxR);
            }
            if (SelectionBoxR != null)
            {
                SelectionBoxes = ToCuboidf(SelectionBoxR);
            }

            // Multiple collision/selectionboxes
            if (CollisionBoxesR != null)
            {
                CollisionBoxes = ToCuboidf(CollisionBoxesR);
            }
            if (SelectionBoxesR != null)
            {
                SelectionBoxes = ToCuboidf(SelectionBoxesR);
            }

            // Merged collision+selectioboxes
            if (CollisionSelectionBoxR != null)
            {
                CollisionBoxes = ToCuboidf(CollisionSelectionBoxR);
                SelectionBoxes = ToCuboidf(CollisionSelectionBoxR);
            }

            if (CollisionSelectionBoxesR != null)
            {
                CollisionBoxes = ToCuboidf(CollisionSelectionBoxesR);
                SelectionBoxes = ToCuboidf(CollisionSelectionBoxesR);
            }


            ResolveStringBoolDictFaces(SideSolid);
            ResolveStringBoolDictFaces(SideOpaque);
            ResolveStringBoolDictFaces(SideAo);

            TintIndex = GameMath.Clamp(TintIndex, 0, 2);

            if (LightHsv == null)
            {
                LightHsv = new byte[3];
            }

            // Boundary check light values, if they go beyond allowed values the lighting system will crash
            LightHsv[0] = (byte)GameMath.Clamp(LightHsv[0], 0, ColorUtil.HueQuantities - 1);
            LightHsv[1] = (byte)GameMath.Clamp(LightHsv[1], 0, ColorUtil.SatQuantities - 1);
            LightHsv[2] = (byte)GameMath.Clamp(LightHsv[2], 0, ColorUtil.BrightQuantities - 1);
        }
        protected override void loadYPosAndThickness(IMapChunk heremapchunk, int lx, int lz, BlockPos pos, double distanceToEdge)
        {
            hereThickness = depoitThickness;

            pos.Y  = (int)(depthf * heremapchunk.WorldGenTerrainHeightMap[lz * chunksize + lx]);
            pos.Y -= (int)getDepositYDistort(pos, lx, lz, step, heremapchunk);

            double curTh = depoitThickness * GameMath.Clamp(distanceToEdge * 2 - 0.2, 0, 1);

            hereThickness = (int)curTh + ((DepositRand.NextDouble() < (curTh - (int)curTh)) ? 1 : 0);
        }
Beispiel #16
0
        public override void StartExecute()
        {
            base.StartExecute();
            idleUntilMs = entity.World.ElapsedMilliseconds + minduration + entity.World.Rand.Next(maxduration - minduration);

            entity.ServerPos.Yaw = (float)GameMath.Clamp(
                entity.World.Rand.NextDouble() * GameMath.TWOPI,
                entity.ServerPos.Yaw - GameMath.PI / 4 * GlobalConstants.OverallSpeedMultiplier,
                entity.ServerPos.Yaw + GameMath.PI / 4 * GlobalConstants.OverallSpeedMultiplier
                );
        }
Beispiel #17
0
        public override bool ShouldReceiveServerGameTicks(IWorldAccessor world, BlockPos pos, Random offThreadRandom, out object extra)
        {
            extra = null;
            if (!canMelt)
            {
                return(false);
            }
            ClimateCondition conds = world.BlockAccessor.GetClimateAt(pos, EnumGetClimateMode.NowValues);

            return(conds != null && offThreadRandom.NextDouble() < GameMath.Clamp((conds.Temperature - 0.5f) / (15f - 10f * conds.Rainfall), 0, 1));
        }
        public override void Render(GuiElementMap map, float dt)
        {
            //if (Texture.Disposed) throw new Exception("Fatal. Trying to render a disposed texture");
            if (quadModel == null || quadModel.Disposed)
            {
                throw new Exception("Fatal. Trying to render a disposed meshref");
            }

            map.TranslateWorldPosToViewPos(waypoint.Position, ref viewPos);

            float x = (float)(map.Bounds.renderX + viewPos.X);
            float y = (float)(map.Bounds.renderY + viewPos.Y);

            if (waypoint.Pinned)
            {
                map.Api.Render.PushScissor(null);
                x = (float)GameMath.Clamp(x, map.Bounds.renderX + 2, map.Bounds.renderX + map.Bounds.InnerWidth - 2);
                y = (float)GameMath.Clamp(y, map.Bounds.renderY + 2, map.Bounds.renderY + map.Bounds.InnerHeight - 2);
            }

            ICoreClientAPI api = map.Api;

            IShaderProgram prog = api.Render.GetEngineShader(EnumShaderProgram.Gui);

            prog.Uniform("rgbaIn", color);
            prog.Uniform("extraGlow", 0);
            prog.Uniform("applyColor", 0);
            prog.Uniform("noTexture", 0f);

            LoadedTexture tex;

            float hover = (mouseOver ? 6 : 0) - 1.5f * Math.Max(1, 1 / map.ZoomLevel);


            if (wpLayer.texturesByIcon.TryGetValue(waypoint.Icon, out tex))
            {
                prog.BindTexture2D("tex2d", wpLayer.texturesByIcon[waypoint.Icon].TextureId, 0);
                mvMat
                .Set(api.Render.CurrentModelviewMatrix)
                .Translate(x, y, 60)
                .Scale(tex.Width + hover, tex.Height + hover, 0)
                .Scale(0.5f, 0.5f, 0)
                ;
                prog.UniformMatrix("projectionMatrix", api.Render.CurrentProjectionMatrix);
                prog.UniformMatrix("modelViewMatrix", mvMat.Values);

                api.Render.RenderMesh(quadModel);
            }

            if (waypoint.Pinned)
            {
                map.Api.Render.PopScissor();
            }
        }
Beispiel #19
0
        public override void Start(ICoreAPI api)
        {
            api.Logger.Debug("[Compass] Start");
            base.Start(api);

            config = ModConfig.Load(api);

            api.RegisterItemClass("ItemMagneticCompass", typeof(ItemMagneticCompass));
            api.RegisterItemClass("ItemRelativeCompass", typeof(ItemRelativeCompass));
            api.RegisterItemClass("ItemOriginCompass", typeof(ItemOriginCompass));

            api.RegisterBlockClass("BlockMagneticCompass", typeof(BlockMagneticCompass));
            api.RegisterBlockClass("BlockRelativeCompass", typeof(BlockRelativeCompass));
            api.RegisterBlockClass("BlockOriginCompass", typeof(BlockOriginCompass));

            api.RegisterBlockEntityClass("BlockEntityCompass", typeof(BlockEntityCompass));

            if (api.Side == EnumAppSide.Server)
            {
                var sapi = (ICoreServerAPI)api;
                sapi.Event.ServerRunPhase(EnumServerRunPhase.GameReady, () => {
                    var compassModGridRecipes = sapi.World.GridRecipes.FindAll(gr => gr.Name.Domain == "compass");
                    var scrap    = compassModGridRecipes.Find(gr => gr.Name.Path == scrapRecipeAssetLoc.Path);
                    var origin   = compassModGridRecipes.Find(gr => gr.Name.Path == originRecipeAssetLoc.Path);
                    var relative = compassModGridRecipes.Find(gr => gr.Name.Path == relativeRecipeAssetLoc.Path);

                    if (!config.EnableScrapRecipe)
                    {
                        sapi.World.GridRecipes.Remove(scrap);
                    }

                    if (!config.EnableOriginRecipe)
                    {
                        sapi.World.GridRecipes.Remove(origin);
                    }
                    else
                    {
                        origin.IngredientPattern = "C".PadRight(GameMath.Clamp(config.OriginCompassGears, 1, 8) + 1, 'G').PadRight(9, '_');
                        origin.ResolveIngredients(sapi.World);
                    }

                    if (!config.EnableRelativeRecipe)
                    {
                        sapi.World.GridRecipes.Remove(relative);
                    }
                    else
                    {
                        relative.IngredientPattern = "C".PadRight(GameMath.Clamp(config.RelativeCompassGears, 1, 8) + 1, 'G').PadRight(9, '_');
                        relative.ResolveIngredients(sapi.World);
                    }
                });
            }
        }
        public override void Update(UpdateEventArgs e)
        {
            this.asteroidChance = Math.Min(asteroidChanceMax, this.asteroidChance + (float)e.ElapsedTimeInS * asteroidChanceIncrease);

            if (this.environment.Offset > firePlanetChanceThreshold)
            {
                this.fireplanetChance = GameMath.Clamp(firePlanetChanceInitial, firePlanetChanceMax, this.fireplanetChance + (float)e.ElapsedTimeInS * firePlanetChanceIncrease);
            }
            if (this.environment.Offset > repellingPlanetChanceThreshold)
            {
                this.repellingPlanetChance = GameMath.Clamp(repellingPlanetChanceInitial, repellingPlanetChanceMax, this.repellingPlanetChance + (float)e.ElapsedTimeInS * repellingPlanetChanceIncrease);
            }

            // Check for planets out of the screen
            while (!this.planets.First.Value.IsOnScreen())
            {
                this.environment.RemoveWorldObject(this.planets.First.Value.ID);

                if (this.planets.First.Value is FirePlanet)
                {
                    this.fireplanetCount--;
                }
                if (this.planets.First.Value is RepellingPlanet)
                {
                    this.repellingPlanetCount--;
                }

                this.environment.Planets.RemoveFirst();
            }

            // Check if spacecore is still visible
            if (this.spacecore != null && this.spacecore.Position.X + 645 + LevelGenerator.SideBuffer < this.environment.Offset)
            {
                this.environment.RemoveWorldObject("spacecore");
                this.spacecore = null;
            }

            // Always have at least a certain amount of planets on the playfield
            if (this.planets.Count < minPlanets)
            {
                this.generatePlanet();
            }

            if (GlobalRandom.NextDouble() < this.asteroidChance)
            {
                this.generateAsteroid();
            }

            if (GlobalRandom.NextDouble() < spacecoreChance && this.spacecore == null)
            {
                this.generateSpacecore();
            }
        }
Beispiel #21
0
        public void UpdateCloudTiles()
        {
            weatherSim.EnsureNoiseCacheIsFresh();
            byte zero = 0;
            int  end  = CloudTileLength - 2;

            // Load density from perlin noise
            for (int dx = 0; dx < CloudTileLength; dx++)
            {
                for (int dz = 0; dz < CloudTileLength; dz++)
                {
                    int x = (tilePosX + dx - CloudTileLength / 2 - tileOffsetX);
                    int z = (tilePosZ + dz - CloudTileLength / 2 - tileOffsetZ);
                    brightnessRand.InitPositionSeed(x, z);
                    double density = weatherSim.GetBlendedCloudDensityAt(dx, dz);

                    CloudTile cloudTile = cloudTiles[dx * CloudTileLength + dz];

                    cloudTile.MaxDensity = (byte)GameMath.Clamp((int)((64 * 255 * density * 3)) / 64, 0, 255);
                    cloudTile.Brightness = (byte)(235 + brightnessRand.NextInt(21));
                    cloudTile.YOffset    = (float)weatherSim.GetBlendedCloudOffsetYAt(dx, dz);
                }
            }


            // Has to be done after all densities have updated
            for (int dx = 0; dx < CloudTileLength; dx++)
            {
                for (int dz = 0; dz < CloudTileLength; dz++)
                {
                    CloudTile cloud = cloudTiles[dx * CloudTileLength + dz];

                    byte northDensity = dz < 1 ? zero : cloudTiles[dx * CloudTileLength + dz - 1].MaxDensity;
                    byte southDensity = dz >= end ? zero : cloudTiles[dx * CloudTileLength + dz + 1].MaxDensity;
                    byte eastDensity  = dx >= end ? zero : cloudTiles[(dx + 1) * CloudTileLength + dz].MaxDensity;
                    byte westDensity  = dx < 1 ? zero : cloudTiles[(dx - 1) * CloudTileLength + dz].MaxDensity;

                    int changeVal = northDensity == 0 || cloud.MaxDensity - northDensity > 5 ? 1 : -1;
                    cloud.NorthFaceDensity = (byte)GameMath.Clamp((cloud.NorthFaceDensity + changeVal), 0, cloud.MaxDensity);

                    changeVal             = eastDensity == 0 || cloud.MaxDensity - eastDensity > 5 ? 1 : -1;
                    cloud.EastFaceDensity = (byte)GameMath.Clamp((cloud.EastFaceDensity + changeVal), 0, cloud.MaxDensity);

                    changeVal = southDensity == 0 || cloud.MaxDensity - southDensity > 5 ? 1 : -1;
                    cloud.SouthFaceDensity = (byte)GameMath.Clamp((cloud.SouthFaceDensity + changeVal), 0, cloud.MaxDensity);

                    changeVal             = westDensity == 0 || cloud.MaxDensity - westDensity > 5 ? 1 : -1;
                    cloud.WestFaceDensity = (byte)GameMath.Clamp((cloud.WestFaceDensity + changeVal), 0, cloud.MaxDensity);

                    cloud.UpDownDensity += (byte)GameMath.Clamp(cloud.MaxDensity - cloud.UpDownDensity, -1, 1);
                }
            }
        }
 public override void OnBlockBroken()
 {
     if (Api.World is IServerWorldAccessor)
     {
         ItemSlot slot = inventory[0];
         while (slot.StackSize > 0)
         {
             ItemStack split = slot.TakeOut(GameMath.Clamp(slot.StackSize, 1, System.Math.Max(1, slot.Itemstack.Collectible.MaxStackSize / 4)));
             Api.World.SpawnItemEntity(split, Pos.ToVec3d().Add(0.5, 0.5, 0.5));
         }
     }
 }
Beispiel #23
0
        public override bool ShouldReceiveServerGameTicks(IWorldAccessor world, BlockPos pos, Random offThreadRandom, out object extra)
        {
            extra = null;
            if (!GlobalConstants.MeltingFreezingEnabled)
            {
                return(false);
            }
            if (habitat == EnumReedsHabitat.Land)
            {
                return(false);
            }

            if (habitat == EnumReedsHabitat.Ice)  // ice -> water
            {
                ClimateCondition conds = world.BlockAccessor.GetClimateAt(pos, EnumGetClimateMode.NowValues);
                if (conds == null)
                {
                    return(false);
                }

                float chance = GameMath.Clamp((conds.Temperature - 2f) / 20f, 0, 1);
                return(offThreadRandom.NextDouble() < chance);
            }

            // water -> ice

            if (Variant["type"] == "papyrus")
            {
                return(false);                               //TODO: currently we do not have an ice version of Papyrus
            }
            if (offThreadRandom.NextDouble() < 0.6)
            {
                int rainY = world.BlockAccessor.GetRainMapHeightAt(pos);
                if (rainY <= pos.Y)
                {
                    for (int i = 0; i < BlockFacing.HORIZONTALS.Length; i++)
                    {
                        BlockFacing facing = BlockFacing.HORIZONTALS[i];
                        if (world.BlockAccessor.GetBlock(pos.AddCopy(facing)).Replaceable < 6000)
                        {
                            ClimateCondition conds = world.BlockAccessor.GetClimateAt(pos, EnumGetClimateMode.NowValues);
                            if (conds != null && conds.Temperature < -4)
                            {
                                return(true);
                            }
                        }
                    }
                }
            }

            return(false);
        }
        public void ClientTick(float dt)
        {
            Random rnd = capi.World.Rand;
            WeatherDataSnapshot weatherData = weatherSys.BlendedWeatherData;

            if (weatherSys.clientClimateCond.Temperature >= weatherData.lightningMinTemp)
            {
                float deepnessSub = GameMath.Clamp(1 - (float)capi.World.Player.Entity.Pos.Y / capi.World.SeaLevel, 0, 1);

                double rndval = capi.World.Rand.NextDouble();
                rndval -= weatherData.distantLightningRate * weatherSys.clientClimateCond.RainCloudOverlay;
                if (rndval <= 0)
                {
                    lightningTime      = 0.07f + (float)rnd.NextDouble() * 0.17f;
                    lightningIntensity = 0.25f + (float)rnd.NextDouble();



                    float pitch  = GameMath.Clamp((float)rnd.NextDouble() * 0.3f + lightningTime / 2 + lightningIntensity / 2 - deepnessSub / 2, 0.6f, 1.15f);
                    float volume = GameMath.Clamp(Math.Min(1, 0.25f + lightningTime + lightningIntensity / 2) - 2f * deepnessSub, 0, 1);

                    capi.World.PlaySoundAt(new AssetLocation("sounds/weather/lightning-distant.ogg"), 0, 0, 0, null, EnumSoundType.Weather, pitch, 32, volume);
                }
                else if (nearLightningCoolDown <= 0)
                {
                    rndval -= weatherData.nearLightningRate * weatherSys.clientClimateCond.RainCloudOverlay;
                    if (rndval <= 0)
                    {
                        lightningTime      = 0.07f + (float)rnd.NextDouble() * 0.17f;
                        lightningIntensity = 1 + (float)rnd.NextDouble() * 0.9f;

                        float         pitch  = GameMath.Clamp(0.75f + (float)rnd.NextDouble() * 0.3f - deepnessSub / 2, 0.5f, 1.2f);
                        float         volume = GameMath.Clamp(0.5f + (float)rnd.NextDouble() * 0.5f - 2f * deepnessSub, 0, 1);
                        AssetLocation loc;

                        if (rnd.NextDouble() > 0.25)
                        {
                            loc = new AssetLocation("sounds/weather/lightning-near.ogg");
                            nearLightningCoolDown = 5;
                        }
                        else
                        {
                            loc = new AssetLocation("sounds/weather/lightning-verynear.ogg");
                            nearLightningCoolDown = 10;
                        }


                        capi.World.PlaySoundAt(loc, 0, 0, 0, null, EnumSoundType.Weather, pitch, 32, volume);
                    }
                }
            }
        }
Beispiel #25
0
        public static ModConfig Load(ICoreAPI api)
        {
            ModConfig config = null;

            try {
                for (int attempts = 1; attempts < 4; attempts++)
                {
                    try {
                        config = api.LoadModConfig <ModConfig>(filename);
                    } catch (JsonReaderException e) {
                        var badLineNum = e.LineNumber;
                        api.Logger.Error($"[CompassMod Error] Unable to parse config JSON. Attempt {attempts} to salvage the file...");
                        var configFilepath     = Path.Combine(GamePaths.ModConfig, filename);
                        var badConfigFilepath  = Path.Combine(GamePaths.Logs, "ERROR_" + filename);
                        var compassLogFilepath = Path.Combine(GamePaths.Logs, "compass-mod-logs.txt");
                        if (attempts == 1)
                        {
                            if (File.Exists(badConfigFilepath))
                            {
                                File.Delete(badConfigFilepath);
                            }
                            File.Copy(configFilepath, badConfigFilepath);
                            File.WriteAllText(compassLogFilepath, e.ToString());
                        }
                        if (attempts != 3)
                        {
                            var lines = new List <string>(File.ReadAllLines(configFilepath));
                            lines.RemoveAt(badLineNum - 1);
                            File.WriteAllText(configFilepath, string.Join("\n", lines.ToArray()));
                        }
                    }
                }
                try {
                    config = api.LoadModConfig <ModConfig>(filename);
                } catch (JsonReaderException) {
                    api.Logger.Error("[CompassMod Error] Unable to salvage config.");
                }
            } catch (System.Exception e) {
                api.Logger.Error("[CompassMod Error] Something went really wrong with reading the config file.");
                File.WriteAllText(Path.Combine(GamePaths.Logs, "compass-mod-logs.txt"), e.ToString());
            }

            if (config == null)
            {
                api.Logger.Warning("[CompassMod Warning] Unable to load valid config file. Generating default config.");
                config = new ModConfig();
            }
            config.OriginCompassGears   = GameMath.Clamp(config.OriginCompassGears, 1, 8);
            config.RelativeCompassGears = GameMath.Clamp(config.RelativeCompassGears, 1, 8);
            Save(api, config);
            return(config);
        }
Beispiel #26
0
        public virtual void Update(float dt)
        {
            if (!State.BeginUseExecuted)
            {
                int a = 1;
            }

            //EnsureNoiseCacheIsFresh();

            double timeAxis = api.World.Calendar.TotalDays / 10.0;

            State.nowPrecIntensity = State.nowBasePrecIntensity + (float)GameMath.Clamp(TimeBasePrecIntenstityGen?.Noise(0, timeAxis) ?? 0, 0, 1);
        }
Beispiel #27
0
        public float GetHeatStrength(IWorldAccessor world, BlockPos heatSourcePos, BlockPos heatReceiverPos)
        {
            if (block.EntityClass != null)
            {
                var behs = world.BlockAccessor.GetBlockEntity(heatSourcePos) as IHeatSource;
                if (behs != null)
                {
                    return(behs.GetHeatStrength(world, heatSourcePos, heatReceiverPos) * GameMath.Clamp(1 - (heatSourcePos.DistanceTo(heatReceiverPos) - 1) / 3f, 0, 1));
                }
            }

            return(heatStrength * GameMath.Clamp(1 - (heatSourcePos.DistanceTo(heatReceiverPos) - 1) / 3f, 0, 1));
        }
        public void OnRenderFrame(float deltaTime, EnumRenderStage stage)
        {
            IRenderAPI rpi    = capi.Render;
            Vec3d      camPos = capi.World.Player.Entity.CameraPos;

            rpi.GlDisableCullFace();
            rpi.GlToggleBlend(true);

            IStandardShaderProgram prog = rpi.PreparedStandardShader(pos.X, pos.Y, pos.Z);

            capi.Render.BindTexture2d(capi.BlockTextureAtlas.AtlasTextureIds[0]);

            prog.DontWarpVertices = 0;
            prog.AddRenderFlags   = 0;
            prog.ModelMatrix      = ModelMat
                                    .Identity()
                                    .Translate(pos.X - camPos.X + 0.001f, pos.Y - camPos.Y, pos.Z - camPos.Z - 0.001f)
                                    .Translate(0f, 1 / 16f, 0f)
                                    .Values
            ;
            prog.ViewMatrix       = rpi.CameraMatrixOriginf;
            prog.ProjectionMatrix = rpi.CurrentProjectionMatrix;

            rpi.RenderMesh(potRef);

            if (!isInOutputSlot)
            {
                float origx = GameMath.Sin(capi.World.ElapsedMilliseconds / 300f) * 5 / 16f;
                float origz = GameMath.Cos(capi.World.ElapsedMilliseconds / 300f) * 5 / 16f;

                float cookIntensity = GameMath.Clamp((temp - 50) / 50, 0, 1);

                prog.ModelMatrix = ModelMat
                                   .Identity()
                                   .Translate(pos.X - camPos.X, pos.Y - camPos.Y, pos.Z - camPos.Z)
                                   .Translate(0, 6.5f / 16f, 0)
                                   .Translate(-origx, 0, -origz)
                                   .RotateX(cookIntensity * GameMath.Sin(capi.World.ElapsedMilliseconds / 50f) / 60)
                                   .RotateZ(cookIntensity * GameMath.Sin(capi.World.ElapsedMilliseconds / 50f) / 60)
                                   .Translate(origx, 0, origz)
                                   .Values
                ;
                prog.ViewMatrix       = rpi.CameraMatrixOriginf;
                prog.ProjectionMatrix = rpi.CurrentProjectionMatrix;


                rpi.RenderMesh(lidRef);
            }

            prog.Stop();
        }
Beispiel #29
0
    public void heatInput(float dt)
    {
        float oldTemp      = InputStackTemp;
        float nowTemp      = oldTemp;
        float meltingPoint = inputSlot.Itemstack.Collectible.GetMeltingPoint(Api.World, inventory, inputSlot);

        // Only Heat ore. Cooling happens already in the itemstack
        if (oldTemp < furnaceTemperature)
        {
            float f = (1 + GameMath.Clamp((furnaceTemperature - oldTemp) / 30, 0, 1.6f)) * dt;
            if (nowTemp >= meltingPoint)
            {
                f /= 11;
            }

            float newTemp = changeTemperature(oldTemp, furnaceTemperature, f);
            int   maxTemp = 0;
            if (inputStack.ItemAttributes != null)
            {
                maxTemp = Math.Max(inputStack.Collectible.CombustibleProps == null ? 0 : inputStack.Collectible.CombustibleProps.MaxTemperature, inputStack.ItemAttributes["maxTemperature"] == null ? 0 : inputStack.ItemAttributes["maxTemperature"].AsInt(0));
            }
            else
            {
                maxTemp = inputStack.Collectible.CombustibleProps == null ? 0 : inputStack.Collectible.CombustibleProps.MaxTemperature;
            }
            if (maxTemp > 0)
            {
                newTemp = Math.Min(maxTemp, newTemp);
            }

            if (oldTemp != newTemp)
            {
                InputStackTemp = newTemp;
                nowTemp        = newTemp;
            }
        }

        // Begin smelting when hot enough
        if (nowTemp >= meltingPoint)
        {
            float diff = nowTemp / meltingPoint;
            inputStackCookingTime += GameMath.Clamp((int)(diff), 1, 30) * dt;
        }
        else
        {
            if (inputStackCookingTime > 0)
            {
                inputStackCookingTime--;
            }
        }
    }
Beispiel #30
0
        public override bool ContinueExecute(float dt)
        {
            EntityPos own = entity.ServerPos;
            EntityPos his = targetEntity.ServerPos;

            float desiredYaw = (float)Math.Atan2(his.X - own.X, his.Z - own.Z);
            float yawDist    = GameMath.AngleRadDistance(entity.ServerPos.Yaw, desiredYaw);

            entity.ServerPos.Yaw += GameMath.Clamp(yawDist, -curTurnRadPerSec * dt * GlobalConstants.OverallSpeedMultiplier, curTurnRadPerSec * dt * GlobalConstants.OverallSpeedMultiplier);
            entity.ServerPos.Yaw  = entity.ServerPos.Yaw % GameMath.TWOPI;


            if (lastCheckOrAttackMs + damagePlayerAtMs > entity.World.ElapsedMilliseconds)
            {
                return(true);
            }

            if (!damageInflicted)
            {
                if (!hasDirectContact(targetEntity))
                {
                    return(false);
                }

                bool alive = targetEntity.Alive;

                ((EntityAgent)targetEntity).ReceiveDamage(
                    new DamageSource()
                {
                    Source       = EnumDamageSource.Entity,
                    SourceEntity = entity,
                    Type         = damageType,
                    DamageTier   = damageTier
                },
                    damage * GlobalConstants.CreatureDamageModifier
                    );

                if (alive && !targetEntity.Alive)
                {
                    this.entity.GetBehavior <EntityBehaviorEmotionStates>()?.TryTriggerState("saturated");
                }

                damageInflicted = true;
            }

            if (lastCheckOrAttackMs + attackDurationMs > entity.World.ElapsedMilliseconds)
            {
                return(true);
            }
            return(false);
        }